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(warehouse-sources): add OAuth2 auth for custom REST sources (#66621)

Marcus Hoffff7298300f8
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 735436150ab6..4a9c9debf7f9 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -282,6 +282,7 @@ export const FEATURE_FLAGS = {
DATA_MODELING_TAB: 'data-modeling-tab', // owner: #team-data-modeling
DATA_WAREHOUSE_COLUMN_STATISTICS: 'data-warehouse-column-statistics', // owner: #team-warehouse-sources
DATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sources
+ DATA_WAREHOUSE_CUSTOM_SOURCE_OAUTH2: 'dwh-custom-source-oauth2', // owner: #team-warehouse-sources
DATA_WAREHOUSE_SCENE: 'data-warehouse-scene', // owner: #team-data-modeling
DATA_WAREHOUSE_SEMANTIC_ENRICHMENT: 'data-warehouse-semantic-enrichment', // owner: #team-warehouse-sources
DEFAULT_EVALUATION_ENVIRONMENTS: 'default-evaluation-environments', // owner: @dmarticus #team-feature-flags
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index 11bf3f85c65c..086788dc8d6a 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -5172,6 +5172,58 @@ class TestExternalDataSource(APIBaseTest):
# The credential probe only runs once the re-entry gate has passed.
assert mock_validate_credentials.called == (expected_status == 200)
+ def _custom_oauth2_source(self, token_url: str) -> ExternalDataSource:
+ manifest = {
+ "client": {
+ "base_url": "https://api.example.com",
+ "auth": {"type": "oauth2", "client_id": "cid", "token_url": token_url},
+ },
+ "resources": [{"name": "users", "endpoint": {"path": "/users"}}],
+ }
+ return ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="Custom",
+ created_by=self.user,
+ prefix="custom_oauth2",
+ job_inputs={"manifest_json": json.dumps(manifest), "auth_oauth2_client_secret": "cs_existing"},
+ )
+
+ @parameterized.expand(
+ [("without_credentials", {}, 400), ("with_credentials", {"auth_oauth2_client_secret": "cs_new"}, 200)]
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_update_custom_source_oauth2_token_url_change_requires_reentry(
+ self, _name, extra_creds, expected_status, mock_validate_credentials
+ ):
+ # The OAuth2 token endpoint receives the stored client_secret. Repointing token_url to a new
+ # host without re-supplying the secret would exfiltrate it to a server the editor chose — so it
+ # is gated exactly like a base_url change. This is the net-new credential-redirect coverage that
+ # the Smokescreen egress proxy structurally cannot provide.
+ source = self._custom_oauth2_source("https://auth.example.com/oauth2/token")
+ new_manifest = {
+ "client": {
+ "base_url": "https://api.example.com",
+ "auth": {"type": "oauth2", "client_id": "cid", "token_url": "https://attacker.example.net/token"},
+ },
+ "resources": [{"name": "users", "endpoint": {"path": "/users"}}],
+ }
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={"job_inputs": {"manifest_json": json.dumps(new_manifest), **extra_creds}},
+ )
+
+ assert response.status_code == expected_status, response.json()
+ assert ("re-entering your credentials" in str(response.json())) == (expected_status == 400)
+ # The credential probe only runs once the re-entry gate has passed.
+ assert mock_validate_credentials.called == (expected_status == 200)
+
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",
return_value=(True, None),
diff --git a/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx b/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx
index 51fd7e82919b..d6d12883c4c8 100644
--- a/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx
@@ -4,6 +4,7 @@ import { IconPlus, IconSparkles, IconTrash } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonDivider, LemonInput, LemonSelect } from '@posthog/lemon-ui'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'
+import { FEATURE_FLAGS } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { organizationLogic } from 'scenes/organizationLogic'
@@ -11,7 +12,6 @@ import { organizationLogic } from 'scenes/organizationLogic'
import {
API_KEY_LOCATIONS,
type ApiKeyLocation,
- AUTH_TYPES,
type AuthType,
CURSOR_TYPES,
type CursorType,
@@ -20,6 +20,10 @@ import {
type HeaderEntry,
isCustomSourceAiBuilderEnabled,
type ManifestState,
+ OAUTH2_CLIENT_AUTH_METHODS,
+ type OAuth2ClientAuthMethod,
+ OAUTH2_GRANT_TYPES,
+ type OAuth2GrantType,
type Paginator,
PAGINATOR_DEFAULTS,
PAGINATOR_TYPES,
@@ -27,6 +31,7 @@ import {
SORT_MODES,
type SortMode,
type TableForm,
+ visibleAuthTypes,
} from './customSourceManifest'
import {
customSourceManifestBuilderLogic,
@@ -51,8 +56,23 @@ const AUTH_LABELS: Record<AuthType, string> = {
bearer: 'Bearer token',
api_key: 'API key',
http_basic: 'HTTP basic auth',
+ oauth2: 'OAuth2',
}
-const AUTH_OPTIONS = AUTH_TYPES.map((value) => ({ value, label: AUTH_LABELS[value] }))
+
+const OAUTH2_GRANT_LABELS: Record<OAuth2GrantType, string> = {
+ client_credentials: 'Client credentials',
+ refresh_token: 'Refresh token',
+}
+const OAUTH2_GRANT_OPTIONS = OAUTH2_GRANT_TYPES.map((value) => ({ value, label: OAUTH2_GRANT_LABELS[value] }))
+
+const OAUTH2_CLIENT_AUTH_METHOD_LABELS: Record<OAuth2ClientAuthMethod, string> = {
+ body: 'In request body',
+ basic: 'HTTP basic header',
+}
+const OAUTH2_CLIENT_AUTH_METHOD_OPTIONS = OAUTH2_CLIENT_AUTH_METHODS.map((value) => ({
+ value,
+ label: OAUTH2_CLIENT_AUTH_METHOD_LABELS[value],
+}))
const API_KEY_LOCATION_LABELS: Record<ApiKeyLocation, string> = {
header: 'Header',
@@ -93,6 +113,7 @@ export function CustomSourceManifestBuilder({
const { featureFlags } = useValues(featureFlagLogic)
const { currentOrganization } = useValues(organizationLogic)
const aiBuilderEnabled = isCustomSourceAiBuilderEnabled(featureFlags, currentOrganization)
+ const oauth2Enabled = !!featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_CUSTOM_SOURCE_OAUTH2]
const {
updateState,
updateTable,
@@ -187,7 +208,14 @@ export function CustomSourceManifestBuilder({
/>
</LemonField.Pure>
- <AuthSection state={manifestState} update={updateState} />
+ <AuthSection
+ state={manifestState}
+ update={updateState}
+ authOptions={visibleAuthTypes(oauth2Enabled, manifestState.auth_type).map((value) => ({
+ value,
+ label: AUTH_LABELS[value],
+ }))}
+ />
<HeadersSection
headers={manifestState.headers}
@@ -245,9 +273,11 @@ export function CustomSourceManifestBuilder({
function AuthSection({
state,
update,
+ authOptions,
}: {
state: ManifestState
update: (patch: Partial<ManifestState>) => void
+ authOptions: { value: AuthType; label: string }[]
}): JSX.Element {
return (
<div className="space-y-2">
@@ -255,7 +285,7 @@ function AuthSection({
<LemonSelect
value={state.auth_type}
onChange={(value) => update({ auth_type: value as AuthType })}
- options={AUTH_OPTIONS}
+ options={authOptions}
/>
</LemonField.Pure>
{state.auth_type === 'bearer' && (
@@ -317,6 +347,124 @@ function AuthSection({
</LemonField.Pure>
</div>
)}
+ {state.auth_type === 'oauth2' && <OAuth2AuthFields state={state} update={update} />}
+ </div>
+ )
+}
+
+function OAuth2AuthFields({
+ state,
+ update,
+}: {
+ state: ManifestState
+ update: (patch: Partial<ManifestState>) => void
+}): JSX.Element {
+ return (
+ <div className="space-y-2">
+ <p className="m-0 text-xs text-secondary">
+ Bring your own OAuth2 client. PostHog mints a short-lived access token from your token endpoint at sync
+ time and refreshes it automatically — no browser sign-in.
+ </p>
+ <div className="grid grid-cols-2 gap-2">
+ <LemonField.Pure label="Grant type">
+ <LemonSelect
+ value={state.oauth2_grant_type}
+ onChange={(value) => update({ oauth2_grant_type: value as OAuth2GrantType })}
+ options={OAUTH2_GRANT_OPTIONS}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Token URL">
+ <LemonInput
+ placeholder="https://auth.example.com/oauth2/token"
+ value={state.oauth2_token_url}
+ onChange={(value) => update({ oauth2_token_url: value })}
+ />
+ </LemonField.Pure>
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ <LemonField.Pure label="Client ID">
+ <LemonInput
+ autoComplete="off"
+ value={state.oauth2_client_id}
+ onChange={(value) => update({ oauth2_client_id: value })}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Client secret">
+ <LemonInput
+ type="password"
+ autoComplete="off"
+ value={state.oauth2_client_secret}
+ onChange={(value) => update({ oauth2_client_secret: value })}
+ />
+ </LemonField.Pure>
+ </div>
+ {state.oauth2_grant_type === 'refresh_token' && (
+ <LemonField.Pure label="Refresh token">
+ <LemonInput
+ type="password"
+ autoComplete="off"
+ value={state.oauth2_refresh_token}
+ onChange={(value) => update({ oauth2_refresh_token: value })}
+ />
+ <p className="m-0 mt-1 text-xs text-secondary">
+ A long-lived refresh token you obtained out-of-band, used to mint access tokens. Providers that
+ rotate (single-use) refresh tokens aren't supported yet — the sync would fail after the first
+ run.
+ </p>
+ </LemonField.Pure>
+ )}
+ <LemonField.Pure label="Scopes">
+ <LemonInput
+ placeholder="read:users read:orders"
+ value={state.oauth2_scopes}
+ onChange={(value) => update({ oauth2_scopes: value })}
+ />
+ <p className="m-0 mt-1 text-xs text-secondary">Space-separated, optional.</p>
+ </LemonField.Pure>
+ <details className="rounded border border-border p-3">
+ <summary className="cursor-pointer text-xs text-secondary">Advanced</summary>
+ <div className="mt-2 space-y-2">
+ <div className="grid grid-cols-2 gap-2">
+ <LemonField.Pure label="Send client credentials">
+ <LemonSelect
+ value={state.oauth2_client_auth_method}
+ onChange={(value) =>
+ update({ oauth2_client_auth_method: value as OAuth2ClientAuthMethod })
+ }
+ options={OAUTH2_CLIENT_AUTH_METHOD_OPTIONS}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Access token field">
+ <LemonInput
+ placeholder="access_token"
+ value={state.oauth2_access_token_name}
+ onChange={(value) => update({ oauth2_access_token_name: value })}
+ />
+ </LemonField.Pure>
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ <LemonField.Pure label="Expiry field">
+ <LemonInput
+ placeholder="expires_in"
+ value={state.oauth2_expires_in_name}
+ onChange={(value) => update({ oauth2_expires_in_name: value })}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Expiry datetime format">
+ <LemonInput
+ placeholder="%Y-%m-%dT%H:%M:%SZ"
+ value={state.oauth2_expiry_date_format}
+ onChange={(value) => update({ oauth2_expiry_date_format: value })}
+ />
+ </LemonField.Pure>
+ </div>
+ <p className="m-0 text-xs text-secondary">
+ Override the response field names only when the provider deviates from the OAuth2 defaults. Set
+ the expiry field and datetime format together when the token response carries an absolute expiry
+ timestamp (e.g. <code>expires_at</code>) instead of <code>expires_in</code> seconds.
+ </p>
+ </div>
+ </details>
</div>
)
}
diff --git a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts
index 451d127f2ce5..67d4bb3d2d5a 100644
--- a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts
@@ -7,6 +7,7 @@ import {
removeTableFromList,
TableForm,
updateTableInList,
+ visibleAuthTypes,
} from '../customSourceManifest'
const baseState = (): ManifestState => ({
@@ -18,6 +19,18 @@ const baseState = (): ManifestState => ({
auth_api_key_location: 'header',
auth_username: '',
auth_password: '',
+ oauth2_token_url: '',
+ oauth2_client_id: '',
+ oauth2_client_secret: '',
+ oauth2_grant_type: 'client_credentials',
+ oauth2_scopes: '',
+ oauth2_refresh_token: '',
+ oauth2_access_token_name: '',
+ oauth2_expires_in_name: '',
+ oauth2_expiry_date_format: '',
+ oauth2_client_auth_method: 'body',
+ oauth2_extra_token_request_params: {},
+ oauth2_token_request_headers: {},
headers: [],
tables: [
{
@@ -624,34 +637,169 @@ describe('datetime_format (incremental cursor)', () => {
})
describe('extractAuthSecrets', () => {
+ const noSecrets = {
+ auth_token: '',
+ auth_api_key: '',
+ auth_password: '',
+ auth_oauth2_client_secret: '',
+ auth_oauth2_refresh_token: '',
+ }
+
it('returns only the bearer token for bearer auth', () => {
const state = baseState()
state.auth_type = 'bearer'
state.auth_token = 'tok_123'
- expect(extractAuthSecrets(state)).toEqual({ auth_token: 'tok_123', auth_api_key: '', auth_password: '' })
+ expect(extractAuthSecrets(state)).toEqual({ ...noSecrets, auth_token: 'tok_123' })
})
it('returns only the api key for api_key auth', () => {
const state = baseState()
state.auth_type = 'api_key'
state.auth_api_key = 'sk_test'
- expect(extractAuthSecrets(state)).toEqual({ auth_token: '', auth_api_key: 'sk_test', auth_password: '' })
+ expect(extractAuthSecrets(state)).toEqual({ ...noSecrets, auth_api_key: 'sk_test' })
})
it('returns only the password for http_basic auth', () => {
const state = baseState()
state.auth_type = 'http_basic'
state.auth_password = 'hunter2'
- expect(extractAuthSecrets(state)).toEqual({ auth_token: '', auth_api_key: '', auth_password: 'hunter2' })
+ expect(extractAuthSecrets(state)).toEqual({ ...noSecrets, auth_password: 'hunter2' })
})
it('returns all-empty for none auth, ignoring stale credential state', () => {
const state = baseState()
state.auth_type = 'none'
- // All three stale so each ternary's false-arm is genuinely exercised.
+ // All stale so each ternary's false-arm is genuinely exercised.
state.auth_token = 'tok_123'
state.auth_api_key = 'sk_test'
state.auth_password = 'hunter2'
- expect(extractAuthSecrets(state)).toEqual({ auth_token: '', auth_api_key: '', auth_password: '' })
+ state.oauth2_client_secret = 'cs_123'
+ state.oauth2_refresh_token = 'rt_123'
+ expect(extractAuthSecrets(state)).toEqual(noSecrets)
+ })
+
+ it('returns the client secret for the client_credentials grant, but never a refresh token', () => {
+ const state = baseState()
+ state.auth_type = 'oauth2'
+ state.oauth2_grant_type = 'client_credentials'
+ state.oauth2_client_secret = 'cs_123'
+ // A stale refresh token must not leak: client_credentials has no refresh token.
+ state.oauth2_refresh_token = 'rt_stale'
+ expect(extractAuthSecrets(state)).toEqual({ ...noSecrets, auth_oauth2_client_secret: 'cs_123' })
+ })
+
+ it('returns both secrets for the refresh_token grant', () => {
+ const state = baseState()
+ state.auth_type = 'oauth2'
+ state.oauth2_grant_type = 'refresh_token'
+ state.oauth2_client_secret = 'cs_123'
+ state.oauth2_refresh_token = 'rt_123'
+ expect(extractAuthSecrets(state)).toEqual({
+ ...noSecrets,
+ auth_oauth2_client_secret: 'cs_123',
+ auth_oauth2_refresh_token: 'rt_123',
+ })
+ })
+})
+
+describe('visibleAuthTypes', () => {
+ it.each([
+ [false, 'bearer', false], // flag off, not oauth2 -> hidden
+ [false, 'oauth2', true], // flag off, already oauth2 -> kept visible so the select can't rewrite it
+ [true, 'bearer', true], // flag on -> visible
+ [true, 'oauth2', true], // flag on, already oauth2 -> visible
+ ] as const)('oauth2 visible? (enabled=%s, current=%s)', (enabled, current, visible) => {
+ expect(visibleAuthTypes(enabled, current).includes('oauth2')).toBe(visible)
+ })
+
+ it('never drops the non-oauth2 types', () => {
+ expect(visibleAuthTypes(false, 'bearer')).toEqual(['none', 'bearer', 'api_key', 'http_basic'])
+ })
+})
+
+describe('oauth2 manifest round-trip', () => {
+ const oauth2Manifest = JSON.stringify({
+ client: {
+ base_url: 'https://api.example.com',
+ auth: {
+ type: 'oauth2',
+ client_id: 'client-abc',
+ token_url: 'https://auth.example.com/oauth2/token',
+ grant_type: 'client_credentials',
+ scopes: 'read:users read:orders',
+ client_auth_method: 'basic',
+ access_token_name: 'token',
+ expires_in_name: 'expires_at',
+ expiry_date_format: '%Y-%m-%dT%H:%M:%SZ',
+ extra_token_request_params: { audience: 'https://api.example.com' },
+ token_request_headers: { 'X-Tenant': 'acme' },
+ },
+ },
+ resources: [
+ {
+ name: 'users',
+ primary_key: 'id',
+ endpoint: { path: '/users', data_selector: 'data', paginator: { type: 'single_page' } },
+ },
+ ],
+ })
+
+ it('parses non-secret oauth fields and leaves secrets empty', () => {
+ const state = parseManifestIntoState(oauth2Manifest)
+ expect(state.auth_type).toBe('oauth2')
+ expect(state.oauth2_client_id).toBe('client-abc')
+ expect(state.oauth2_token_url).toBe('https://auth.example.com/oauth2/token')
+ expect(state.oauth2_grant_type).toBe('client_credentials')
+ expect(state.oauth2_scopes).toBe('read:users read:orders')
+ expect(state.oauth2_client_auth_method).toBe('basic')
+ // Secrets are never in the manifest, so they parse back empty.
+ expect(state.oauth2_client_secret).toBe('')
+ expect(state.oauth2_refresh_token).toBe('')
+ })
+
+ it('round-trips the auth manifest without secrets or scope corruption', () => {
+ const rebuilt = buildManifest(parseManifestIntoState(oauth2Manifest)) as any
+ const auth = rebuilt.client.auth
+ expect(auth.type).toBe('oauth2')
+ expect(auth.client_id).toBe('client-abc')
+ expect(auth.token_url).toBe('https://auth.example.com/oauth2/token')
+ expect(auth.grant_type).toBe('client_credentials')
+ // Scopes stay a single space-separated string end-to-end — never split/rejoined.
+ expect(auth.scopes).toBe('read:users read:orders')
+ expect(auth.client_auth_method).toBe('basic')
+ expect(auth.access_token_name).toBe('token')
+ expect(auth.expires_in_name).toBe('expires_at')
+ expect(auth.expiry_date_format).toBe('%Y-%m-%dT%H:%M:%SZ')
+ // Advanced dict knobs with no builder UI survive verbatim (like passthrough_params).
+ expect(auth.extra_token_request_params).toEqual({ audience: 'https://api.example.com' })
+ expect(auth.token_request_headers).toEqual({ 'X-Tenant': 'acme' })
+ // Secrets never appear in the manifest.
+ expect(auth.client_secret).toBeUndefined()
+ expect(auth.refresh_token).toBeUndefined()
+ })
+
+ it('drops an inline client_secret rather than re-emitting it', () => {
+ // Even if a hand-authored manifest inlines the secret, parse drops it and build never
+ // re-emits it — the secret only ever travels via extractAuthSecrets / the secret field.
+ const withInlineSecret = JSON.parse(oauth2Manifest)
+ withInlineSecret.client.auth.client_secret = 'should-not-survive'
+ const rebuilt = buildManifest(parseManifestIntoState(JSON.stringify(withInlineSecret))) as any
+ expect(rebuilt.client.auth.client_secret).toBeUndefined()
+ })
+
+ it('omits client_auth_method when it is the default (body)', () => {
+ const bodyManifest = JSON.parse(oauth2Manifest)
+ bodyManifest.client.auth.client_auth_method = 'body'
+ const rebuilt = buildManifest(parseManifestIntoState(JSON.stringify(bodyManifest))) as any
+ expect(rebuilt.client.auth.client_auth_method).toBeUndefined()
+ })
+
+ it('coerces token-param values to strings and drops non-scalars to match the backend dict[str, str]', () => {
+ // A hand/AI-authored manifest with non-string values would otherwise round-trip verbatim and
+ // fail backend validation; normalize scalars to strings and drop nested objects in the builder.
+ const manifest = JSON.parse(oauth2Manifest)
+ manifest.client.auth.extra_token_request_params = { audience: 'x', retries: 3, nested: { a: 1 } }
+ const rebuilt = buildManifest(parseManifestIntoState(JSON.stringify(manifest))) as any
+ expect(rebuilt.client.auth.extra_token_request_params).toEqual({ audience: 'x', retries: '3' })
})
})
diff --git a/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts b/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts
index 63b724933bfe..64de49a47bb8 100644
--- a/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts
@@ -24,9 +24,30 @@ export function isCustomSourceAiBuilderEnabled(
// Each enum-like value set is declared once as an `as const` tuple; the union type
// and the runtime guard (via `isMember`) are derived from it, so the allowed values
// can't drift between the type, the parser, and the component's select options.
-export const AUTH_TYPES = ['none', 'bearer', 'api_key', 'http_basic'] as const
+export const AUTH_TYPES = ['none', 'bearer', 'api_key', 'http_basic', 'oauth2'] as const
export type AuthType = (typeof AUTH_TYPES)[number]
+// OAuth2 grants for customer-owned clients. `authorization_code` is out of scope
+// (needs an interactive consent flow), so only the two non-interactive grants exist;
+// the backend rejects any other grant at manifest validation.
+export const OAUTH2_GRANT_TYPES = ['client_credentials', 'refresh_token'] as const
+export type OAuth2GrantType = (typeof OAUTH2_GRANT_TYPES)[number]
+
+// Where the client credentials travel in the token request (RFC 6749 §2.3.1).
+export const OAUTH2_CLIENT_AUTH_METHODS = ['body', 'basic'] as const
+export type OAuth2ClientAuthMethod = (typeof OAUTH2_CLIENT_AUTH_METHODS)[number]
+
+/**
+ * The auth types the builder's picker should offer. OAuth2 is gated behind its own rollout
+ * flag — hidden unless the flag is on, but kept visible when the source *already* uses it, so
+ * an existing oauth2 source's type still renders and the select can't silently rewrite it to a
+ * different auth type if the flag is later turned off. Lives here (not the component) so the
+ * gating branch is unit-tested.
+ */
+export function visibleAuthTypes(oauth2Enabled: boolean, currentAuthType: AuthType): AuthType[] {
+ return AUTH_TYPES.filter((value) => value !== 'oauth2' || oauth2Enabled || currentAuthType === 'oauth2')
+}
+
// The backend treats 'query' and 'param' as synonymous (auth.py:41), so we
// only surface 'query' in the UI — the parser still accepts 'param' for
// manifests authored elsewhere.
@@ -131,14 +152,37 @@ export interface ManifestState {
auth_api_key_location: ApiKeyLocation
auth_username: string
auth_password: string
+ // OAuth2 (customer-owned client). The non-secret fields go into `client.auth` in the
+ // manifest; the secrets (`oauth2_client_secret`, `oauth2_refresh_token`) flow via
+ // `extractAuthSecrets` into separate `auth_oauth2_*` form fields, never the manifest.
+ oauth2_token_url: string
+ oauth2_client_id: string
+ oauth2_client_secret: string
+ oauth2_grant_type: OAuth2GrantType
+ oauth2_scopes: string
+ oauth2_refresh_token: string
+ // Advanced (scalar) knobs for the provider long tail — empty means "use the backend default".
+ oauth2_access_token_name: string
+ oauth2_expires_in_name: string
+ oauth2_expiry_date_format: string
+ oauth2_client_auth_method: OAuth2ClientAuthMethod
+ // Advanced dict knobs with no dedicated builder UI (e.g. Auth0's `audience`, custom token
+ // headers). Carried verbatim through parse → build, like `passthrough_params` for tables,
+ // so an AI-drafted or hand-authored manifest doesn't lose them when edited in the builder.
+ oauth2_extra_token_request_params: Record<string, string>
+ oauth2_token_request_headers: Record<string, string>
headers: HeaderEntry[]
tables: TableForm[]
}
+// Keys mirror the backend `auth_*` secret config field names exactly — they're written
+// straight to `payload.<key>` by the builder logic, so a rename here breaks redaction.
export interface AuthSecrets {
auth_token: string
auth_api_key: string
auth_password: string
+ auth_oauth2_client_secret: string
+ auth_oauth2_refresh_token: string
}
export function emptyHeader(): HeaderEntry {
@@ -239,6 +283,18 @@ export function defaultState(): ManifestState {
auth_api_key_location: 'header',
auth_username: '',
auth_password: '',
+ oauth2_token_url: '',
+ oauth2_client_id: '',
+ oauth2_client_secret: '',
+ oauth2_grant_type: 'client_credentials',
+ oauth2_scopes: '',
+ oauth2_refresh_token: '',
+ oauth2_access_token_name: '',
+ oauth2_expires_in_name: '',
+ oauth2_expiry_date_format: '',
+ oauth2_client_auth_method: 'body',
+ oauth2_extra_token_request_params: {},
+ oauth2_token_request_headers: {},
headers: [],
tables: [emptyTable()],
}
@@ -266,6 +322,40 @@ export function buildManifest(state: ManifestState): Record<string, unknown> {
}
case 'http_basic':
return { type: 'http_basic', username: state.auth_username }
+ case 'oauth2': {
+ // Only NON-secret oauth fields go into the manifest. client_secret and
+ // refresh_token flow via extractAuthSecrets into separate form fields.
+ const oauth: Record<string, unknown> = {
+ type: 'oauth2',
+ client_id: state.oauth2_client_id,
+ token_url: state.oauth2_token_url,
+ grant_type: state.oauth2_grant_type,
+ }
+ // Keep scopes a single space-separated string end-to-end — never split/rejoin.
+ if (state.oauth2_scopes.trim()) {
+ oauth.scopes = state.oauth2_scopes.trim()
+ }
+ // Advanced knobs: emit only when set so the common manifest stays minimal.
+ if (state.oauth2_access_token_name.trim()) {
+ oauth.access_token_name = state.oauth2_access_token_name.trim()
+ }
+ if (state.oauth2_expires_in_name.trim()) {
+ oauth.expires_in_name = state.oauth2_expires_in_name.trim()
+ }
+ if (state.oauth2_expiry_date_format.trim()) {
+ oauth.expiry_date_format = state.oauth2_expiry_date_format.trim()
+ }
+ if (state.oauth2_client_auth_method !== 'body') {
+ oauth.client_auth_method = state.oauth2_client_auth_method
+ }
+ if (Object.keys(state.oauth2_extra_token_request_params).length > 0) {
+ oauth.extra_token_request_params = state.oauth2_extra_token_request_params
+ }
+ if (Object.keys(state.oauth2_token_request_headers).length > 0) {
+ oauth.token_request_headers = state.oauth2_token_request_headers
+ }
+ return oauth
+ }
default:
return undefined
}
@@ -358,6 +448,13 @@ export function extractAuthSecrets(state: ManifestState): AuthSecrets {
auth_token: state.auth_type === 'bearer' ? state.auth_token : '',
auth_api_key: state.auth_type === 'api_key' ? state.auth_api_key : '',
auth_password: state.auth_type === 'http_basic' ? state.auth_password : '',
+ auth_oauth2_client_secret: state.auth_type === 'oauth2' ? state.oauth2_client_secret : '',
+ // The refresh token only applies to the refresh_token grant — keep it empty otherwise so
+ // switching auth type or grant never carries a stale secret through to the backend.
+ auth_oauth2_refresh_token:
+ state.auth_type === 'oauth2' && state.oauth2_grant_type === 'refresh_token'
+ ? state.oauth2_refresh_token
+ : '',
}
}
@@ -410,6 +507,22 @@ function asString(value: unknown, fallback = ''): string {
return typeof value === 'string' ? value : fallback
}
+// OAuth2 token-request params/headers are string-valued by definition (form body params and HTTP
+// header values). Coerce scalar values to string and drop non-scalars so the parsed state matches
+// the backend's `dict[str, str]` — a non-string value from a hand/AI-authored manifest is normalized
+// here instead of silently round-tripping into a backend validation error.
+function asStringRecord(value: unknown): Record<string, string> {
+ const result: Record<string, string> = {}
+ for (const [key, raw] of Object.entries(asObject(value))) {
+ if (typeof raw === 'string') {
+ result[key] = raw
+ } else if (typeof raw === 'number' || typeof raw === 'boolean') {
+ result[key] = String(raw)
+ }
+ }
+ return result
+}
+
export function parseManifestIntoState(rawJson: string | undefined): ManifestState {
if (!rawJson) {
return defaultState()
@@ -434,6 +547,14 @@ export function parseManifestIntoState(rawJson: string | undefined): ManifestSta
const apiKeyLocation: ApiKeyLocation = isMember(API_KEY_LOCATIONS, normalizedLocation)
? normalizedLocation
: 'header'
+ const oauth2GrantRaw = asString(auth.grant_type, 'client_credentials')
+ const oauth2GrantType: OAuth2GrantType = isMember(OAUTH2_GRANT_TYPES, oauth2GrantRaw)
+ ? oauth2GrantRaw
+ : 'client_credentials'
+ const oauth2AuthMethodRaw = asString(auth.client_auth_method, 'body')
+ const oauth2ClientAuthMethod: OAuth2ClientAuthMethod = isMember(OAUTH2_CLIENT_AUTH_METHODS, oauth2AuthMethodRaw)
+ ? oauth2AuthMethodRaw
+ : 'body'
const headerObj = asObject(client.headers)
const headers: HeaderEntry[] = Object.entries(headerObj).map(([key, value]) => ({
id: nextHeaderId(),
@@ -451,6 +572,20 @@ export function parseManifestIntoState(rawJson: string | undefined): ManifestSta
auth_api_key_location: apiKeyLocation,
auth_username: asString(auth.username),
auth_password: asString(auth.password),
+ // Secrets are never in the manifest — they live in separate config fields — so they
+ // parse back empty and the user re-enters them (or they were already redacted away).
+ oauth2_token_url: asString(auth.token_url),
+ oauth2_client_id: asString(auth.client_id),
+ oauth2_client_secret: '',
+ oauth2_grant_type: oauth2GrantType,
+ oauth2_scopes: asString(auth.scopes),
+ oauth2_refresh_token: '',
+ oauth2_access_token_name: asString(auth.access_token_name),
+ oauth2_expires_in_name: asString(auth.expires_in_name),
+ oauth2_expiry_date_format: asString(auth.expiry_date_format),
+ oauth2_client_auth_method: oauth2ClientAuthMethod,
+ oauth2_extra_token_request_params: asStringRecord(auth.extra_token_request_params),
+ oauth2_token_request_headers: asStringRecord(auth.token_request_headers),
headers,
tables,
}
diff --git a/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts b/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts
index be5ee23e35eb..b385087b4b85 100644
--- a/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts
@@ -215,9 +215,18 @@ export const customSourceManifestBuilderLogic = kea<customSourceManifestBuilderL
props.setValue(['payload', 'manifest_json'] as FieldName, values.manifestJson)
// Secrets go to their own fields so the backend redacts them generically;
// the manifest itself stays non-secret and round-trips to the config tab.
+ // Field names must match the backend SourceFieldInputConfig names exactly.
props.setValue(['payload', 'auth_token'] as FieldName, values.authSecrets.auth_token)
props.setValue(['payload', 'auth_api_key'] as FieldName, values.authSecrets.auth_api_key)
props.setValue(['payload', 'auth_password'] as FieldName, values.authSecrets.auth_password)
+ props.setValue(
+ ['payload', 'auth_oauth2_client_secret'] as FieldName,
+ values.authSecrets.auth_oauth2_client_secret
+ )
+ props.setValue(
+ ['payload', 'auth_oauth2_refresh_token'] as FieldName,
+ values.authSecrets.auth_oauth2_refresh_token
+ )
},
})),
// Every state mutation re-pushes the serialized manifest + secrets to the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/auth.py
index 3a9d69bb0801..3802856882b7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/auth.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/auth.py
@@ -1,10 +1,17 @@
+import json
from base64 import b64encode
-from typing import Literal, Optional
+from datetime import UTC, datetime, timedelta
+from typing import Any, Literal, Optional
-from requests import PreparedRequest
+from requests import PreparedRequest, Response
from requests.auth import AuthBase
+from urllib3.util.retry import Retry
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
TApiKeyLocation = Literal["header", "query", "param", "cookie"]
+OAuth2GrantType = Literal["client_credentials", "refresh_token"]
+OAuth2ClientAuthMethod = Literal["body", "basic"]
class AuthConfigBase(AuthBase):
@@ -80,6 +87,287 @@ class HttpBasicAuth(AuthConfigBase):
return (self.password,) if self.password else ()
+# Re-mint the access token this many seconds before its declared expiry, so a
+# token that's still valid at the check isn't rejected mid-flight by the upstream.
+# Mirrors Airbyte's OAuthAuthenticator and SalesforceAuth's own clock skew handling.
+_TOKEN_EXPIRY_BUFFER = timedelta(seconds=60)
+# When the token response declares no usable expiry, assume a conservative lifetime
+# so a long-running sync still re-mints rather than caching a dead token forever.
+_DEFAULT_TOKEN_TTL = timedelta(hours=1)
+# Token exchanges run on the worker (sync) or the API request thread (create-time
+# probe), so keep them tightly bounded — a stalled token endpoint must not hang either.
+_TOKEN_CONNECT_TIMEOUT = 10
+_TOKEN_READ_TIMEOUT = 30
+# The customer configures token_url, so a hostile one could return an unbounded 2xx body; the exchange
+# runs on shared workers, so cap what we buffer before parsing. A token response is a few KB — 256 KiB is
+# generous headroom without risking a worker OOM.
+_MAX_TOKEN_RESPONSE_BYTES = 256 * 1024
+
+
+# Stable marker appended to every permanent OAuth2 token error message. At sync time the
+# pipeline classifies non-retryable errors by substring-matching the stringified exception
+# (see CustomSource.get_non_retryable_errors), and the permanent cases here have no single
+# shared phrase to match on — they range over OAuth error codes (unauthorized_client,
+# invalid_scope …), bare "HTTP 3xx from the OAuth2 token endpoint" with no code at all, and
+# malformed-response messages, while transient 429/5xx token errors share the very same
+# "from the OAuth2 token endpoint" phrasing. This marker is the one stable substring that is
+# present on permanent token failures and absent on retryable ones.
+OAUTH2_PERMANENT_ERROR_MARKER = "[oauth2_token_config_error]"
+
+
+class OAuth2AuthRequestError(Exception):
+ """A token exchange against the customer's OAuth2 token endpoint failed.
+
+ Carries only the provider's standard ``error`` / ``error_description`` — never
+ the raw response body, which could echo the posted ``client_secret`` back into
+ a user-facing error or log. ``is_permanent`` distinguishes a config error that
+ retrying can't fix (``invalid_client`` / ``invalid_grant`` and other 4xx) from
+ a transient failure (429 / 5xx) the caller may retry.
+
+ When ``is_permanent`` is set, the message embeds :data:`OAUTH2_PERMANENT_ERROR_MARKER`
+ so the sync-time non-retryable classifier can reliably recognise every permanent case
+ (not just the handful that carry a known OAuth error code) by a single stable substring.
+ """
+
+ def __init__(self, message: str, *, error_code: Optional[str] = None, is_permanent: bool = False) -> None:
+ if is_permanent and OAUTH2_PERMANENT_ERROR_MARKER not in message:
+ message = f"{message} {OAUTH2_PERMANENT_ERROR_MARKER}"
+ super().__init__(message)
+ self.error_code = error_code
+ self.is_permanent = is_permanent
+
+
+class OAuth2Auth(BearerTokenAuth):
+ """OAuth2 auth for customer-owned clients (``client_credentials`` / ``refresh_token``).
+
+ The customer brings their own OAuth2 client (``client_id`` / ``client_secret`` /
+ ``token_url``); the worker mints a short-lived access token at request time, caches
+ it in memory for the run, and re-mints on expiry — the same lazy, in-process
+ refresh as :class:`SalesforceAuth`, but config-driven (no PostHog-registered app
+ and no interactive consent flow). ``authorization_code`` is out of scope and is
+ rejected at manifest validation, so only the two non-interactive grants reach here.
+ """
+
+ def __init__(
+ self,
+ token_url: Optional[str] = None,
+ client_id: Optional[str] = None,
+ client_secret: Optional[str] = None,
+ grant_type: OAuth2GrantType = "client_credentials",
+ scopes: Optional[str] = None,
+ refresh_token: Optional[str] = None,
+ access_token: Optional[str] = None,
+ # --- Extensibility knobs (all optional, all non-secret) for the provider long tail. ---
+ access_token_name: str = "access_token",
+ expires_in_name: str = "expires_in",
+ expiry_date_format: Optional[str] = None,
+ extra_token_request_params: Optional[dict[str, str]] = None,
+ token_request_headers: Optional[dict[str, str]] = None,
+ client_auth_method: OAuth2ClientAuthMethod = "body",
+ ) -> None:
+ super().__init__(token=access_token)
+ self.token_url = token_url
+ self.client_id = client_id
+ self.client_secret = client_secret
+ self.grant_type = grant_type
+ self.scopes = scopes
+ self.refresh_token = refresh_token
+ self.access_token_name = access_token_name
+ self.expires_in_name = expires_in_name
+ self.expiry_date_format = expiry_date_format
+ self.extra_token_request_params = extra_token_request_params
+ self.token_request_headers = token_request_headers
+ self.client_auth_method = client_auth_method
+ # None => mint on the first request. A pre-supplied access_token (rare; never
+ # set for custom sources today) has no known expiry, so it too re-mints first.
+ self.token_expiry: Optional[datetime] = None
+ # When the current token was minted — used to cap the refresh buffer at half the
+ # token's lifetime so a very short-lived token isn't treated as expired the instant
+ # it's minted (which would re-mint on every request).
+ self._minted_at: Optional[datetime] = None
+
+ def __call__(self, request: PreparedRequest) -> PreparedRequest:
+ if self.token is None or self._is_token_expired():
+ self._obtain_token()
+ # The minted token must stay on the `Authorization` header. At sync time the tracked
+ # session fixes its value-based redaction set at construction — before this lazy mint —
+ # so the minted token isn't in it; it's redacted only by the header-name denylist. Moving
+ # it to a custom-named header would silently lose that backstop (see secret_values()).
+ request.headers["Authorization"] = f"Bearer {self.token}"
+ return request
+
+ def _is_token_expired(self) -> bool:
+ if self.token_expiry is None:
+ return True
+ # Refresh slightly before the declared expiry to avoid a mid-flight rejection, but cap
+ # the buffer at half the token's lifetime: a token whose whole TTL is <= the buffer would
+ # otherwise read as already-expired the moment it's minted, re-minting on every request.
+ lifetime = self.token_expiry - self._minted_at if self._minted_at else _TOKEN_EXPIRY_BUFFER * 2
+ buffer = min(_TOKEN_EXPIRY_BUFFER, lifetime / 2)
+ return datetime.now(UTC) >= (self.token_expiry - buffer)
+
+ def secret_values(self) -> tuple[str, ...]:
+ # MUST override the base (which redacts only the access token): the
+ # client_secret and refresh_token are equally sensitive, and the
+ # dynamically-minted access token is included so it's masked wherever it
+ # surfaces (an error URL, a sampled body) — the redaction contract.
+ return tuple(value for value in (self.client_secret, self.token, self.refresh_token) if value)
+
+ def _build_token_request_body(self) -> dict[str, str]:
+ # Seed with the caller's extras first so the required OAuth2 params set below always win. The extras
+ # are for provider-specific knobs (e.g. an `audience`); they must not be able to override the
+ # grant_type, client_id/secret, or refresh_token this auth engine derives from its config.
+ body: dict[str, str] = dict(self.extra_token_request_params or {})
+ body["grant_type"] = self.grant_type
+ if self.grant_type == "refresh_token":
+ if not self.refresh_token:
+ raise OAuth2AuthRequestError(
+ "A refresh_token is required for the refresh_token grant", is_permanent=True
+ )
+ body["refresh_token"] = self.refresh_token
+ if self.scopes:
+ body["scope"] = self.scopes
+ # RFC 6749 §2.3.1 permits the client credentials in the body or as HTTP Basic.
+ # In "body" mode they travel in the form body; "basic" mode sends them in the
+ # Authorization header instead (see _obtain_token).
+ if self.client_auth_method == "body":
+ if self.client_id:
+ body["client_id"] = self.client_id
+ if self.client_secret:
+ body["client_secret"] = self.client_secret
+ return body
+
+ def _obtain_token(self, timeout: Optional[tuple[float, float]] = None) -> None:
+ if not self.token_url:
+ raise OAuth2AuthRequestError("A token_url is required to obtain an OAuth2 access token", is_permanent=True)
+ body = self._build_token_request_body()
+ basic_auth = (self.client_id or "", self.client_secret or "") if self.client_auth_method == "basic" else None
+ # capture=False: the response body carries the minted access_token, which the
+ # name-based sample scrubbers can't recognise — keep the exchange out of HTTP
+ # samples entirely. allow_redirects=False pins the credential to the validated
+ # token host (a 3xx must not bounce the client_secret elsewhere). retry=Retry(0)
+ # so 429/5xx aren't silently retried here — we classify and let the caller decide.
+ session = make_tracked_session(
+ redact_values=self.secret_values(),
+ allow_redirects=False,
+ capture=False,
+ retry=Retry(total=0),
+ )
+ # `timeout` lets the create-time pre-mint pass a tighter budget than the sync default:
+ # the pre-mint runs inline on the API request thread, so it must stay within the same
+ # bound as the data probe rather than blocking for the full sync-time read timeout.
+ # stream=True so the body isn't buffered until we read it under a cap (see _read_capped_token_payload).
+ response = session.post(
+ self.token_url,
+ data=body,
+ auth=basic_auth,
+ headers=self.token_request_headers or None,
+ timeout=timeout or (_TOKEN_CONNECT_TIMEOUT, _TOKEN_READ_TIMEOUT),
+ stream=True,
+ )
+ payload = _read_capped_token_payload(response)
+ if 200 <= response.status_code < 300:
+ self._apply_token_response(payload)
+ return
+ error_code, description = _extract_token_error(payload)
+ message = _format_token_error(response.status_code, error_code, description)
+ # A 4xx other than 429 (invalid_client / invalid_grant / unauthorized_client …) is a
+ # permanent config error; a 3xx is too — the session pins allow_redirects=False, so an
+ # unfollowed redirect means token_url is misconfigured and retrying can't fix it. Only
+ # 429 and 5xx are transient and worth a caller/Temporal retry.
+ is_permanent = 300 <= response.status_code < 500 and response.status_code != 429
+ raise OAuth2AuthRequestError(message, error_code=error_code, is_permanent=is_permanent)
+
+ def _apply_token_response(self, payload: Optional[dict[str, Any]]) -> None:
+ if payload is None:
+ raise OAuth2AuthRequestError(
+ "The OAuth2 token endpoint returned a non-JSON or unexpected response", is_permanent=True
+ )
+ token = payload.get(self.access_token_name)
+ if not isinstance(token, str) or not token:
+ raise OAuth2AuthRequestError(
+ f"The OAuth2 token response did not contain a string {self.access_token_name!r} field",
+ is_permanent=True,
+ )
+ self.token = token
+ self._minted_at = datetime.now(UTC)
+ self.token_expiry = self._parse_token_expiry(payload)
+
+ def _parse_token_expiry(self, payload: dict[str, Any]) -> datetime:
+ now = datetime.now(UTC)
+ raw = payload.get(self.expires_in_name)
+ if self.expiry_date_format and isinstance(raw, str):
+ # The provider returns an absolute datetime string (e.g. Square's expires_at)
+ # rather than a TTL in seconds; parse it with the declared format.
+ try:
+ parsed = datetime.strptime(raw, self.expiry_date_format)
+ except ValueError:
+ return now + _DEFAULT_TOKEN_TTL
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+ if isinstance(raw, bool):
+ # bool is an int subclass — a stray `true` is not a TTL.
+ return now + _DEFAULT_TOKEN_TTL
+ if isinstance(raw, (int, float)):
+ return now + timedelta(seconds=int(raw))
+ if isinstance(raw, str) and raw.strip().isdigit():
+ return now + timedelta(seconds=int(raw.strip()))
+ # No usable expiry hint — assume a conservative TTL so a long sync still re-mints.
+ return now + _DEFAULT_TOKEN_TTL
+
+
+def _read_capped_token_payload(response: Response) -> Optional[dict[str, Any]]:
+ """Read the token response body under a size cap, then JSON-parse it.
+
+ The request is made with ``stream=True``, so the body isn't materialised until this read. We read one
+ byte past the cap to detect an oversized body without buffering the whole thing — a hostile ``token_url``
+ (the customer configures it) could otherwise return an unbounded 2xx body and OOM a shared worker.
+ Returns ``None`` for a body that isn't a JSON object; callers decide whether that's an error.
+ """
+ raw = response.raw.read(_MAX_TOKEN_RESPONSE_BYTES + 1, decode_content=True)
+ if len(raw) > _MAX_TOKEN_RESPONSE_BYTES:
+ raise OAuth2AuthRequestError("The OAuth2 token endpoint returned an oversized response", is_permanent=True)
+ try:
+ payload = json.loads(raw)
+ except ValueError:
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+def _extract_token_error(payload: Optional[dict[str, Any]]) -> tuple[Optional[str], str]:
+ """Pull the standard OAuth2 ``error`` / ``error_description`` from a failed token response.
+
+ Reads only those two fields — never the raw body, which could echo the posted
+ ``client_secret`` back. Returns ``(None, "")`` for a non-JSON or unexpected body.
+ """
+ if payload is None:
+ return None, ""
+ error_code = payload.get("error")
+ description = payload.get("error_description")
+ return (
+ error_code if isinstance(error_code, str) else None,
+ description if isinstance(description, str) else "",
+ )
+
+
+def _format_token_error(status_code: int, error_code: Optional[str], description: str) -> str:
+ parts = [f"HTTP {status_code} from the OAuth2 token endpoint"]
+ if error_code:
+ parts.append(error_code)
+ if description:
+ parts.append(description)
+ return ": ".join(parts)
+
+
+def strip_oauth2_permanent_marker(text: str) -> str:
+ """Drop the internal permanent-error marker from a message before showing it to a user.
+
+ :data:`OAUTH2_PERMANENT_ERROR_MARKER` is a sync-time classifier hint, not user-facing
+ copy — strip it (and the space that precedes it) wherever a token-error message is
+ surfaced at create or preview time.
+ """
+ return text.replace(f" {OAUTH2_PERMANENT_ERROR_MARKER}", "").replace(OAUTH2_PERMANENT_ERROR_MARKER, "")
+
+
def auth_secret_values(auth: Optional[AuthBase]) -> tuple[str, ...]:
"""Secret credential strings carried by an auth object, for log redaction.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py
index df7b881e010d..b43a398ad4b4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py
@@ -8,7 +8,7 @@ from typing import Any, NamedTuple, Optional, cast
from requests import Response
-from .auth import APIKeyAuth, AuthConfigBase, BearerTokenAuth, HttpBasicAuth
+from .auth import APIKeyAuth, AuthConfigBase, BearerTokenAuth, HttpBasicAuth, OAuth2Auth
from .exceptions import IgnoreResponseException
from .jsonpath_utils import find_values
from .paginators import (
@@ -51,6 +51,7 @@ AUTH_MAP: dict[AuthType, type[AuthConfigBase]] = {
"bearer": BearerTokenAuth,
"api_key": APIKeyAuth,
"http_basic": HttpBasicAuth,
+ "oauth2": OAuth2Auth,
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_auth.py
new file mode 100644
index 000000000000..334d9f3cc7a0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_auth.py
@@ -0,0 +1,348 @@
+import json
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ _TOKEN_CONNECT_TIMEOUT,
+ _TOKEN_READ_TIMEOUT,
+ OAuth2Auth,
+ OAuth2AuthRequestError,
+)
+
+AUTH_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth"
+
+
+def _token_response(status_code: int = 200, payload: Optional[dict[str, Any]] = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ # The exchange reads a capped `response.raw.read(...)` then json.loads — seed the raw body to match.
+ response.raw.read.return_value = json.dumps(payload if payload is not None else {}).encode()
+ return response
+
+
+def _apply_auth(auth: OAuth2Auth) -> Optional[str]:
+ """Run the auth against a prepared request and return the Authorization header it set."""
+ request = MagicMock()
+ request.headers = {}
+ auth(request)
+ return request.headers.get("Authorization")
+
+
+class TestOAuth2Auth(SimpleTestCase):
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_client_credentials_sets_bearer_and_caches(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-123", "expires_in": 3600}
+ )
+ auth = OAuth2Auth(
+ token_url="https://auth.example.com/token",
+ client_id="cid",
+ client_secret="csecret",
+ grant_type="client_credentials",
+ )
+ assert _apply_auth(auth) == "Bearer minted-123"
+ body = mock_session.return_value.post.call_args.kwargs["data"]
+ assert body["grant_type"] == "client_credentials"
+ assert body["client_id"] == "cid"
+ assert body["client_secret"] == "csecret"
+ # The token is cached for the run — a second request mints nothing new.
+ assert _apply_auth(auth) == "Bearer minted-123"
+ assert mock_session.return_value.post.call_count == 1
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_refresh_token_grant_body_and_no_in_memory_rotation(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "minted-456", "expires_in": 3600, "refresh_token": "refresh-rotated"}
+ )
+ auth = OAuth2Auth(
+ token_url="https://auth.example.com/token",
+ client_id="cid",
+ client_secret="csecret",
+ grant_type="refresh_token",
+ refresh_token="refresh-orig",
+ )
+ assert _apply_auth(auth) == "Bearer minted-456"
+ body = mock_session.return_value.post.call_args.kwargs["data"]
+ assert body["grant_type"] == "refresh_token"
+ assert body["refresh_token"] == "refresh-orig"
+ # The auth object never rotates its in-memory refresh token, even when the response
+ # returns a new one — rotation writeback is a Phase 2 sync-activity concern, not the
+ # auth object's. Mutating it here would silently diverge from the persisted value.
+ assert auth.refresh_token == "refresh-orig"
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_remints_when_expired_and_reuses_when_fresh(self, mock_session):
+ mock_session.return_value.post.side_effect = [
+ _token_response(payload={"access_token": "first", "expires_in": 3600}),
+ _token_response(payload={"access_token": "second", "expires_in": 3600}),
+ ]
+ auth = OAuth2Auth(token_url="https://auth.example.com/token", client_id="cid", client_secret="cs")
+ assert _apply_auth(auth) == "Bearer first"
+ # Force the cached token past expiry — the next request must re-mint.
+ auth.token_expiry = datetime.now(UTC) - timedelta(seconds=1)
+ assert _apply_auth(auth) == "Bearer second"
+ # Now fresh again — a third request reuses without a third mint.
+ assert _apply_auth(auth) == "Bearer second"
+ assert mock_session.return_value.post.call_count == 2
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_expiry_buffer_remints_before_declared_expiry(self, mock_session):
+ mock_session.return_value.post.side_effect = [
+ _token_response(payload={"access_token": "first", "expires_in": 3600}),
+ _token_response(payload={"access_token": "second", "expires_in": 3600}),
+ ]
+ auth = OAuth2Auth(token_url="https://auth.example.com/token", client_id="cid", client_secret="cs")
+ assert _apply_auth(auth) == "Bearer first"
+ # A long-lived (1h) token now 30s from expiry — inside the 60s refresh buffer, so re-mint.
+ # _minted_at is set alongside token_expiry so the buffer isn't clamped down to a tiny TTL.
+ auth._minted_at = datetime.now(UTC) - timedelta(hours=1)
+ auth.token_expiry = datetime.now(UTC) + timedelta(seconds=30)
+ assert _apply_auth(auth) == "Bearer second"
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_short_lived_token_is_not_reminted_every_request(self, mock_session):
+ # A genuinely short-lived token (TTL <= the 60s buffer) must not read as expired the
+ # instant it's minted — the buffer is capped at half the lifetime, so it stays usable.
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "short", "expires_in": 20}
+ )
+ auth = OAuth2Auth(token_url="https://auth.example.com/token", client_id="cid", client_secret="cs")
+ assert _apply_auth(auth) == "Bearer short"
+ # Immediately after minting it's still fresh (not re-minted) despite TTL < buffer.
+ assert _apply_auth(auth) == "Bearer short"
+ assert mock_session.return_value.post.call_count == 1
+
+ def test_secret_values_includes_minted_token(self):
+ auth = OAuth2Auth(client_secret="csecret", refresh_token="refresh-x")
+ # Before minting: the static secrets only.
+ assert set(auth.secret_values()) == {"csecret", "refresh-x"}
+ # After minting, the dynamically-obtained access token joins the redaction set —
+ # otherwise it could leak from an error URL or sample that surfaces later.
+ auth.token = "minted-token"
+ assert set(auth.secret_values()) == {"csecret", "refresh-x", "minted-token"}
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_token_exchange_disables_capture_and_redacts_secret(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response(payload={"access_token": "t", "expires_in": 60})
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="topsecret")
+ _apply_auth(auth)
+ kwargs = mock_session.call_args.kwargs
+ # The response body carries the minted token, which the name-based scrubbers can't
+ # recognise — the exchange must be excluded from sample capture and pinned no-redirect.
+ assert kwargs["capture"] is False
+ assert kwargs["allow_redirects"] is False
+ assert "topsecret" in kwargs["redact_values"]
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_basic_client_auth_method_uses_http_basic_not_body(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response(payload={"access_token": "t", "expires_in": 60})
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs", client_auth_method="basic")
+ _apply_auth(auth)
+ call = mock_session.return_value.post.call_args
+ assert call.kwargs["auth"] == ("cid", "cs")
+ # In basic mode the credentials must NOT also be duplicated into the form body.
+ assert "client_secret" not in call.kwargs["data"]
+ assert "client_id" not in call.kwargs["data"]
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_non_standard_token_field_scopes_and_extra_params(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response(payload={"my_token": "abc", "expires_in": 60})
+ auth = OAuth2Auth(
+ token_url="https://a/t",
+ client_id="cid",
+ client_secret="cs",
+ scopes="read write",
+ access_token_name="my_token",
+ extra_token_request_params={"audience": "https://api.example.com"},
+ )
+ # access_token_name reads the token from a non-standard response field.
+ assert _apply_auth(auth) == "Bearer abc"
+ body = mock_session.return_value.post.call_args.kwargs["data"]
+ # scopes stay a single space-separated string; extra params reach the body (the Auth0 case).
+ assert body["scope"] == "read write"
+ assert body["audience"] == "https://api.example.com"
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_extra_params_cannot_override_required_token_params(self, mock_session):
+ # extra_token_request_params is for provider-specific knobs, not for clobbering the grant_type /
+ # client_id / refresh_token this engine derives from its config (which would let a manifest smuggle
+ # a different grant past validation). Non-conflicting extras still pass through.
+ mock_session.return_value.post.return_value = _token_response(payload={"access_token": "t", "expires_in": 60})
+ auth = OAuth2Auth(
+ token_url="https://a/t",
+ client_id="real-cid",
+ client_secret="cs",
+ grant_type="client_credentials",
+ extra_token_request_params={"grant_type": "authorization_code", "client_id": "attacker", "audience": "aud"},
+ )
+
+ _apply_auth(auth)
+
+ body = mock_session.return_value.post.call_args.kwargs["data"]
+ assert body["grant_type"] == "client_credentials"
+ assert body["client_id"] == "real-cid"
+ assert body["audience"] == "aud"
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_absolute_datetime_expiry_field(self, mock_session):
+ # The Square case: the provider returns an absolute `expires_at` datetime, not seconds.
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "t", "expires_at": "2999-01-01T00:00:00Z"}
+ )
+ auth = OAuth2Auth(
+ token_url="https://a/t",
+ client_id="cid",
+ client_secret="cs",
+ expires_in_name="expires_at",
+ expiry_date_format="%Y-%m-%dT%H:%M:%SZ",
+ )
+ _apply_auth(auth)
+ assert auth.token_expiry == datetime(2999, 1, 1, tzinfo=UTC)
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_malformed_absolute_expiry_falls_back_to_default_ttl(self, mock_session):
+ # A configured expiry_date_format with an unparseable value must not propagate strptime's
+ # ValueError (which would fail the whole sync) — it falls back to the conservative default.
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "t", "expires_at": "not-a-date"}
+ )
+ auth = OAuth2Auth(
+ token_url="https://a/t",
+ client_id="cid",
+ client_secret="cs",
+ expires_in_name="expires_at",
+ expiry_date_format="%Y-%m-%dT%H:%M:%SZ",
+ )
+ _apply_auth(auth)
+ assert auth.token_expiry is not None
+ assert auth.token_expiry > datetime.now(UTC) + timedelta(minutes=50)
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_numeric_string_expires_in(self, mock_session):
+ # Some providers send expires_in as a JSON string; the digit-string branch parses it
+ # (7200s here, distinguishable from the 1h default that an unparsed value would yield).
+ mock_session.return_value.post.return_value = _token_response(
+ payload={"access_token": "t", "expires_in": "7200"}
+ )
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+ _apply_auth(auth)
+ assert auth.token_expiry is not None
+ assert auth.token_expiry > datetime.now(UTC) + timedelta(minutes=100)
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_missing_expiry_field_uses_default_ttl(self, mock_session):
+ # No expiry hint at all → the conservative 1h default so a long sync still re-mints.
+ mock_session.return_value.post.return_value = _token_response(payload={"access_token": "t"})
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+ _apply_auth(auth)
+ now = datetime.now(UTC)
+ assert auth.token_expiry is not None
+ assert now + timedelta(minutes=50) < auth.token_expiry < now + timedelta(minutes=70)
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_token_request_headers_forwarded(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response(payload={"access_token": "t", "expires_in": 60})
+ auth = OAuth2Auth(
+ token_url="https://a/t",
+ client_id="cid",
+ client_secret="cs",
+ token_request_headers={"X-Tenant": "acme"},
+ )
+ _apply_auth(auth)
+ assert mock_session.return_value.post.call_args.kwargs["headers"] == {"X-Tenant": "acme"}
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_obtain_token_default_and_explicit_timeout(self, mock_session):
+ # The sync path uses the generous default; the create-time pre-mint passes a tighter budget
+ # so a stalled token endpoint can't pin the inline API request thread for the full read.
+ mock_session.return_value.post.return_value = _token_response(payload={"access_token": "t", "expires_in": 60})
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+ _apply_auth(auth)
+ assert mock_session.return_value.post.call_args.kwargs["timeout"] == (
+ _TOKEN_CONNECT_TIMEOUT,
+ _TOKEN_READ_TIMEOUT,
+ )
+ auth._obtain_token(timeout=(3, 7))
+ assert mock_session.return_value.post.call_args.kwargs["timeout"] == (3, 7)
+
+ @parameterized.expand(
+ [
+ ("invalid_client_401", 401, "invalid_client", True),
+ ("invalid_grant_400", 400, "invalid_grant", True),
+ # An unfollowed 3xx means token_url is misconfigured — permanent, not a transient retry.
+ ("redirect_302", 302, None, True),
+ ("rate_limited_429", 429, "slow_down", False),
+ ("server_error_503", 503, None, False),
+ ]
+ )
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_token_error_classification(self, _name, status_code, error_code, expected_permanent, mock_session):
+ payload = {"error": error_code} if error_code else {}
+ response = _token_response(status_code=status_code, payload=payload)
+ response.text = "RAW BODY THAT MIGHT CONTAIN topsecret"
+ mock_session.return_value.post.return_value = response
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="topsecret")
+ with self.assertRaises(OAuth2AuthRequestError) as ctx:
+ auth._obtain_token()
+ assert ctx.exception.is_permanent is expected_permanent
+ if error_code:
+ assert error_code in str(ctx.exception)
+ # The raw body (and any secret it might echo) is never surfaced in the error.
+ assert "topsecret" not in str(ctx.exception)
+ assert "RAW BODY" not in str(ctx.exception)
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_missing_access_token_field_raises_permanent(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response(payload={"expires_in": 60})
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+ with self.assertRaises(OAuth2AuthRequestError) as ctx:
+ auth._obtain_token()
+ assert ctx.exception.is_permanent
+
+ @parameterized.expand(
+ [
+ # The token endpoint returned a 2xx but the body isn't JSON the client can parse — a
+ # config error against the wrong URL, not something a retry fixes.
+ ("non_json_body", "non_json", None),
+ # A 2xx whose top-level JSON is a list/array rather than the expected object — same.
+ ("array_body", None, [{"access_token": "t"}]),
+ ]
+ )
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_malformed_token_response_raises_permanent(self, _name, json_side_effect, json_return, mock_session):
+ response = _token_response(status_code=200)
+ if json_side_effect == "non_json":
+ response.raw.read.return_value = b"<html>not json</html>"
+ else:
+ response.raw.read.return_value = json.dumps(json_return).encode()
+ mock_session.return_value.post.return_value = response
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+ with self.assertRaises(OAuth2AuthRequestError) as ctx:
+ auth._obtain_token()
+ assert ctx.exception.is_permanent is True
+
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_oversized_token_response_raises_permanent(self, mock_session):
+ # A hostile token_url returning a huge 2xx body must not be buffered whole (worker OOM); the read is
+ # capped and an oversized body fails permanently.
+ response = _token_response(status_code=200)
+ response.raw.read.return_value = b"x" * (256 * 1024 + 1)
+ mock_session.return_value.post.return_value = response
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+
+ with self.assertRaises(OAuth2AuthRequestError) as ctx:
+ auth._obtain_token()
+
+ assert ctx.exception.is_permanent is True
+ assert "oversized" in str(ctx.exception)
+
+ def test_refresh_grant_without_refresh_token_raises(self):
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs", grant_type="refresh_token")
+ with self.assertRaises(OAuth2AuthRequestError):
+ auth._obtain_token()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_config_setup.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_config_setup.py
index 645bf68693f6..cf0f0eab71b2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_config_setup.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_config_setup.py
@@ -6,6 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
APIKeyAuth,
BearerTokenAuth,
HttpBasicAuth,
+ OAuth2Auth,
auth_secret_values,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
@@ -74,6 +75,28 @@ class TestCreateAuth:
auth = create_auth({"type": "http_basic", "username": "user", "password": "pass"})
assert isinstance(auth, HttpBasicAuth)
+ def test_oauth2_from_dict(self) -> None:
+ # create_auth unpacks the dict generically, so the oauth-specific fields (and the
+ # extensibility knobs) flow into OAuth2Auth with no create_auth changes.
+ auth = create_auth(
+ {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/token",
+ "client_secret": "csecret",
+ "grant_type": "client_credentials",
+ "scopes": "read",
+ "client_auth_method": "basic",
+ }
+ )
+ assert isinstance(auth, OAuth2Auth)
+ assert auth.client_id == "cid"
+ assert auth.token_url == "https://auth.example.com/token"
+ assert auth.client_secret == "csecret"
+ assert auth.grant_type == "client_credentials"
+ assert auth.scopes == "read"
+ assert auth.client_auth_method == "basic"
+
def test_none_returns_none(self) -> None:
assert create_auth(None) is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
index 5930c8a41fa6..1e2dcdc6f901 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
@@ -4,7 +4,16 @@ from typing import Any, Literal, Optional, TypedDict
from requests import Session
-from .auth import APIKeyAuth, AuthConfigBase, BearerTokenAuth, HttpBasicAuth, TApiKeyLocation
+from .auth import (
+ APIKeyAuth,
+ AuthConfigBase,
+ BearerTokenAuth,
+ HttpBasicAuth,
+ OAuth2Auth,
+ OAuth2ClientAuthMethod,
+ OAuth2GrantType,
+ TApiKeyLocation,
+)
from .jsonpath_utils import TJsonPath, compile_path
from .paginators import (
BasePaginator,
@@ -87,7 +96,7 @@ PaginatorConfig = (
)
-AuthType = Literal["bearer", "api_key", "http_basic"]
+AuthType = Literal["bearer", "api_key", "http_basic", "oauth2"]
class AuthTypeConfig(TypedDict, total=True):
@@ -110,15 +119,36 @@ class HttpBasicAuthConfig(AuthTypeConfig, total=True):
password: str
+class OAuth2AuthConfig(AuthTypeConfig, total=False):
+ # Mirrors OAuth2Auth.__init__. Every field is optional so the engine's generic
+ # create_auth(auth_class(**exclude_keys(config, {"type"}))) unpacking works; the
+ # non-secret fields live in the manifest, the secrets are injected at sync time.
+ token_url: str
+ client_id: str
+ client_secret: str
+ grant_type: Optional[OAuth2GrantType]
+ scopes: Optional[str]
+ refresh_token: str
+ access_token: str
+ access_token_name: Optional[str]
+ expires_in_name: Optional[str]
+ expiry_date_format: Optional[str]
+ extra_token_request_params: Optional[dict[str, str]]
+ token_request_headers: Optional[dict[str, str]]
+ client_auth_method: Optional[OAuth2ClientAuthMethod]
+
+
AuthConfig = (
AuthConfigBase
| AuthType
| BearerTokenAuthConfig
| ApiKeyAuthConfig
| HttpBasicAuthConfig
+ | OAuth2AuthConfig
| BearerTokenAuth
| APIKeyAuth
| HttpBasicAuth
+ | OAuth2Auth
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
index b54b18208782..a2fc3af70e9b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
@@ -40,7 +40,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resources,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import auth_secret_values
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ OAUTH2_PERMANENT_ERROR_MARKER,
+ OAuth2Auth,
+ OAuth2AuthRequestError,
+ auth_secret_values,
+ strip_oauth2_permanent_marker,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
build_resource_dependency_graph,
create_auth,
@@ -61,7 +67,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType, Inc
# Credential keys that must NOT appear inline in the manifest — they belong in
# the dedicated secret `auth_*` config fields so the API layer can redact them.
-INLINE_SECRET_KEYS = ("token", "api_key", "password")
+INLINE_SECRET_KEYS = ("token", "api_key", "password", "client_secret", "refresh_token", "access_token")
logger = structlog.get_logger(__name__)
@@ -118,10 +124,27 @@ class _ManifestAuth(BaseModel):
# engine's `create_auth` with an unexpected-kwarg TypeError at sync time.
model_config = ConfigDict(extra="forbid")
- type: Literal["bearer", "api_key", "http_basic"]
+ type: Literal["bearer", "api_key", "http_basic", "oauth2"]
name: str | None = None
location: Literal["header", "query", "param", "cookie"] | None = None
username: str | None = None
+ # OAuth2 (non-secret) fields. The customer brings their own client: client_id /
+ # token_url and the extensibility knobs live in the manifest, while client_secret /
+ # refresh_token are injected from the secret auth_oauth2_* config fields at sync time.
+ # `authorization_code` is out of scope (needs an interactive consent flow), so the
+ # grant Literal admits only the two non-interactive grants — a manifest declaring any
+ # other grant fails validation here. Every field is optional so the non-oauth2 types
+ # are unaffected; the after-validator enforces what oauth2 actually requires.
+ client_id: str | None = None
+ token_url: str | None = None
+ grant_type: Literal["client_credentials", "refresh_token"] | None = None
+ scopes: str | None = None
+ access_token_name: str | None = None
+ expires_in_name: str | None = None
+ expiry_date_format: str | None = None
+ extra_token_request_params: dict[str, str] | None = None
+ token_request_headers: dict[str, str] | None = None
+ client_auth_method: Literal["body", "basic"] | None = None
@model_validator(mode="before")
@classmethod
@@ -130,12 +153,34 @@ class _ManifestAuth(BaseModel):
# the manifest — the manifest field is non-secret and round-trips to the client.
if isinstance(data, dict):
inline = [key for key in INLINE_SECRET_KEYS if data.get(key)]
+ # `extra_token_request_params` / `token_request_headers` are forwarded verbatim to the token
+ # endpoint but live in the non-secret manifest, so a secret stashed in them would round-trip
+ # to anyone who can read the source. Scan their keys too — case-insensitively, since header
+ # names like `Authorization` are arbitrarily cased.
+ for nested_key in ("extra_token_request_params", "token_request_headers"):
+ nested = data.get(nested_key)
+ if isinstance(nested, dict):
+ lowered = {str(key).lower(): value for key, value in nested.items()}
+ inline += [
+ f"{nested_key}.{key}" for key in (*INLINE_SECRET_KEYS, "authorization") if lowered.get(key)
+ ]
if inline:
raise ValueError(
f"Credentials ({', '.join(inline)}) must not be embedded — use the dedicated auth fields"
)
return data
+ @model_validator(mode="after")
+ def _require_oauth2_fields(self) -> "_ManifestAuth":
+ # client_id + token_url are the minimum a customer-owned OAuth2 client needs;
+ # without them the token exchange can't run. (client_secret is a separate
+ # secret field, so it isn't required here.)
+ if self.type == "oauth2":
+ missing = [field for field in ("client_id", "token_url") if not getattr(self, field)]
+ if missing:
+ raise ValueError(f"OAuth2 auth requires {' and '.join(missing)} in the manifest")
+ return self
+
class _ManifestClient(BaseModel):
base_url: str = Field(min_length=1)
@@ -355,6 +400,17 @@ def validate_manifest_urls(manifest: dict[str, Any], team_id: int) -> tuple[bool
if not ok:
return False, f"Invalid base_url: {err}"
+ # The OAuth2 token endpoint is a second customer-controlled host that receives the
+ # client_secret. Vet it like base_url: https-on-Cloud + internal-host rejection.
+ # Defense-in-depth (Smokescreen already guards egress); the load-bearing control
+ # against repointing token_url to exfiltrate the secret is the re-entry gate, which
+ # sees token_url via manifest_request_hosts (same extraction, shared helper).
+ token_url = _manifest_oauth2_token_url(manifest.get("client"))
+ if token_url is not None:
+ ok, err = _check_url(token_url, team_id)
+ if not ok:
+ return False, f"Invalid token_url: {err}"
+
base_host = _url_hostname(base_url)
for resource in manifest["resources"]:
# Resolve exactly as the engine will (so a whitespace/case-disguised absolute path
@@ -422,6 +478,23 @@ def _endpoint_request_url(base_url: str, endpoint: Any) -> str | None:
return resolve_request_url(base_url, resolved)
+def _manifest_oauth2_token_url(client: Any) -> str | None:
+ """The oauth2 ``token_url`` for a parsed manifest's ``client``, or ``None`` if absent /
+ non-oauth2 / non-string.
+
+ Single source for the two places that must agree on it — :func:`validate_manifest_urls`
+ (vets the host) and :func:`manifest_request_hosts` (feeds the credential re-entry gate).
+ Keeping them in lockstep matters for security: if the re-entry gate ever stopped tracking
+ ``token_url`` while the URL vetting still did, an editor could repoint it past the gate.
+ """
+ auth = client.get("auth") if isinstance(client, dict) else None
+ if isinstance(auth, dict) and auth.get("type") == "oauth2":
+ token_url = auth.get("token_url")
+ if isinstance(token_url, str):
+ return token_url
+ return None
+
+
def manifest_request_hosts(manifest_json: Any) -> frozenset[str]:
"""Hostnames a stored manifest will send requests — and the credential — to.
@@ -456,6 +529,15 @@ def manifest_request_hosts(manifest_json: Any) -> frozenset[str]:
if resolved is not None:
urls.append(resolved)
+ # The OAuth2 token endpoint receives the stored client_secret, so it's a request
+ # destination the re-entry gate must track: an editor who can't read the secret
+ # must not be able to repoint token_url at a host they control while keeping the
+ # secret. It's a literal URL (not a path template), so add its host directly —
+ # don't run the path-resolution logic on it.
+ token_url = _manifest_oauth2_token_url(client)
+ if token_url is not None:
+ urls.append(token_url)
+
# `_url_hostname` returns an already-lowercased host.
hosts = {host for url in urls if (host := _url_hostname(url))}
return frozenset(hosts)
@@ -560,7 +642,7 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
placeholder="",
secret=False,
),
- # One of the three is used per sync, selected by the manifest's
+ # One credential is used per sync, selected by the manifest's
# client.auth.type. All secret so the generic API layer redacts them.
SourceFieldInputConfig(
name="auth_token",
@@ -586,6 +668,27 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
placeholder="",
secret=True,
),
+ # OAuth2 (auth.type == "oauth2"): the customer's own client secret and,
+ # for the refresh_token grant, their pre-obtained refresh token. Both
+ # secret so the generic API layer redacts them and the re-entry gate
+ # covers them. The non-secret oauth fields (client_id / token_url / …)
+ # live in manifest_json.
+ SourceFieldInputConfig(
+ name="auth_oauth2_client_secret",
+ label="OAuth2 client secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="auth_oauth2_refresh_token",
+ label="OAuth2 refresh token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
],
),
)
@@ -598,6 +701,16 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
# in an edit while the table's sync stayed scheduled). Permanent until the config is
# fixed — match the stable suffix, not the variable resource name in the message.
"not found in config": "A table in this sync points to a resource that no longer exists in the source's manifest. Re-add the resource to the manifest, or remove the table from the sync, then try again.",
+ # The OAuth2 token endpoint rejected the client credentials or the grant. Both are
+ # permanent until the config changes — retrying the sync can't fix them. The two
+ # codes below get pointed, code-specific copy; every other permanent token failure
+ # (unauthorized_client / invalid_scope / a bare 3xx redirect / a malformed token
+ # response / a missing token_url) is caught by the stable marker OAuth2AuthRequestError
+ # embeds whenever is_permanent is set — so no permanent token error retries until the
+ # activity budget is exhausted. Transient (429 / 5xx) token errors carry no marker.
+ "invalid_client": "The OAuth2 token endpoint rejected the client credentials (invalid_client). Check the configured client_id, client secret, and token URL.",
+ "invalid_grant": "The OAuth2 token endpoint rejected the grant (invalid_grant) — a refresh token may have expired or been revoked. Re-enter the OAuth2 credentials.",
+ OAUTH2_PERMANENT_ERROR_MARKER: "The OAuth2 token endpoint rejected the request and the configuration must change before the sync can succeed. Check the configured OAuth2 credentials, token URL, grant type, and scopes.",
}
def _assemble_manifest(self, config: CustomSourceConfig) -> dict[str, Any]:
@@ -660,6 +773,38 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
except (ValueError, TypeError) as exc:
return False, f"Invalid auth configuration: {exc}"
+ # OAuth2 mints its access token lazily on the first request, so pre-mint it now —
+ # a bad client_secret / token_url then fails with a pointed "the OAuth2 token
+ # endpoint rejected the request: …" instead of a misleading "resource unreachable"
+ # on the first data probe. Minting before the probe session is built also lets the
+ # freshly-minted access token join that session's redaction set. A transient
+ # (429 / 5xx) token error must not block creation — the first real sync retries —
+ # so only a permanent error (invalid_client / invalid_grant / other 4xx) is surfaced.
+ if isinstance(probe_auth, OAuth2Auth):
+ try:
+ # Bound the inline token exchange to the same budget as the data probe — this runs
+ # on the API request thread, so a stalled token endpoint must fail fast (well within
+ # the request's idle timeout) rather than block for the generous sync-time read.
+ probe_auth._obtain_token(timeout=(PROBE_CONNECT_TIMEOUT, PROBE_READ_TIMEOUT))
+ except OAuth2AuthRequestError as exc:
+ if exc.is_permanent:
+ # Strip the internal sync-time classifier marker — it's not user-facing copy.
+ return False, _redact_secrets(
+ f"The OAuth2 token endpoint rejected the request: {strip_oauth2_permanent_marker(str(exc))}",
+ auth_secret_values(probe_auth),
+ )
+ # Transient (429 / 5xx): don't block creation — the first real sync retries the
+ # token exchange. Skip the data probe too: it has no minted token to authenticate
+ # with, so requests would re-invoke the auth (re-running the failing mint) and turn
+ # this into a misleading "could not reach <data resource>" failure.
+ return True, None
+ except Exception as exc:
+ # Redact the credential defensively — a transport-layer exception shouldn't carry
+ # the secret, but the redaction discipline is cheap and uniform here.
+ return False, _redact_secrets(
+ f"Could not reach the OAuth2 token endpoint: {exc}", auth_secret_values(probe_auth)
+ )
+
# The probe runs inline on the request thread, so keep it cheap and
# bounded: no retries (don't multiply outbound volume at create time),
# no redirects (Smokescreen re-resolves each hop; keep the credential
@@ -717,7 +862,10 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
f"Resource {resource['name']!r}: the upstream API rejected the request with "
f"HTTP {response.status_code} from {url} — check the configured auth credentials."
)
- snippet = _read_capped_text(response)
+ # Redact the credential from the echoed body before surfacing it: an upstream
+ # could reflect the sent credential (e.g. an OAuth2 bearer token minted above) in
+ # its 401/403 error, and the snippet would otherwise leak it into a user message.
+ snippet = _redact_secrets(_read_capped_text(response), auth_secret_values(probe_auth))
if snippet:
message += f" The upstream responded: {snippet}"
return False, message
@@ -929,7 +1077,12 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
try:
rows = _collect_preview_rows(resource, max_rows)
except Exception as exc:
- return PreviewResult(rows=[], row_count=0, columns=[], error=_redact_secrets(str(exc), secret_values))
+ return PreviewResult(
+ rows=[],
+ row_count=0,
+ columns=[],
+ error=_redact_secrets(strip_oauth2_permanent_marker(str(exc)), secret_values),
+ )
return PreviewResult(rows=rows, row_count=len(rows), columns=_infer_columns(rows), error=None)
@@ -1157,6 +1310,14 @@ def _inject_auth_secrets(manifest: dict[str, Any], config: CustomSourceConfig) -
auth["api_key"] = config.auth_api_key
elif auth_type == "http_basic" and config.auth_password:
auth["password"] = config.auth_password
+ elif auth_type == "oauth2":
+ # The non-secret oauth fields (client_id / token_url / grant_type / knobs) are
+ # already in the manifest; inject only the secrets. client_credentials needs just
+ # the client_secret; the refresh_token grant also needs the refresh token.
+ if config.auth_oauth2_client_secret:
+ auth["client_secret"] = config.auth_oauth2_client_secret
+ if config.auth_oauth2_refresh_token:
+ auth["refresh_token"] = config.auth_oauth2_refresh_token
def _incremental_field_type(raw: Any) -> IncrementalFieldType:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py
index d5fb29fc5c4a..db7b40d6cb2f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py
@@ -1,10 +1,11 @@
import io
import gzip
import json
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any, cast
from urllib.parse import quote
+from freezegun import freeze_time
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
@@ -15,9 +16,12 @@ from requests import Response
from urllib3.response import HTTPResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ OAUTH2_PERMANENT_ERROR_MARKER,
APIKeyAuth,
BearerTokenAuth,
HttpBasicAuth,
+ OAuth2Auth,
+ OAuth2AuthRequestError,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.custom.source import (
MAX_MANIFEST_RESOURCES,
@@ -44,6 +48,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
from products.warehouse_sources.backend.types import IncrementalFieldType
+AUTH_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth"
+
def validate_manifest(manifest: Any) -> None:
# Full-validation composite (structure + graph). Production runs the two
@@ -178,6 +184,54 @@ class TestValidateManifest(SimpleTestCase):
("token", {"type": "bearer", "token": "leaked"}),
("api_key", {"type": "api_key", "api_key": "leaked"}),
("password", {"type": "http_basic", "username": "alice", "password": "leaked"}),
+ (
+ "client_secret",
+ {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/t",
+ "client_secret": "leaked",
+ },
+ ),
+ (
+ "refresh_token",
+ {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/t",
+ "grant_type": "refresh_token",
+ "refresh_token": "leaked",
+ },
+ ),
+ (
+ "access_token",
+ {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/t",
+ "access_token": "leaked",
+ },
+ ),
+ # The OAuth2 token-request knobs are forwarded to the token endpoint but stored in the
+ # non-secret manifest, so a secret hidden in them must be rejected too.
+ (
+ "extra_token_request_params.client_secret",
+ {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/t",
+ "extra_token_request_params": {"client_secret": "leaked"},
+ },
+ ),
+ (
+ "token_request_headers.Authorization",
+ {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/t",
+ "token_request_headers": {"Authorization": "Bearer leaked"},
+ },
+ ),
]
)
def test_rejects_inline_credentials(self, _name, auth):
@@ -189,6 +243,42 @@ class TestValidateManifest(SimpleTestCase):
validate_manifest(manifest)
assert "must not be embedded" in str(ctx.exception)
+ def test_accepts_valid_oauth2_manifest(self):
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/token",
+ "grant_type": "client_credentials",
+ }
+ validate_manifest(manifest)
+
+ @parameterized.expand(
+ [
+ ("missing_client_id", {"type": "oauth2", "token_url": "https://auth.example.com/t"}),
+ ("missing_token_url", {"type": "oauth2", "client_id": "cid"}),
+ ]
+ )
+ def test_rejects_oauth2_missing_required_fields(self, _name, auth):
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = auth
+ with self.assertRaises(ManifestValidationError) as ctx:
+ validate_manifest(manifest)
+ assert "OAuth2 auth requires" in str(ctx.exception)
+
+ def test_rejects_oauth2_authorization_code_grant(self):
+ # authorization_code needs an interactive consent flow — out of scope for headless syncs.
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/t",
+ "grant_type": "authorization_code",
+ }
+ with self.assertRaises(ManifestValidationError) as ctx:
+ validate_manifest(manifest)
+ assert "grant_type" in str(ctx.exception)
+
class TestValidateManifestUrls(SimpleTestCase):
@parameterized.expand(
@@ -247,6 +337,46 @@ class TestValidateManifestUrls(SimpleTestCase):
ok, err = validate_manifest_urls(manifest, team_id=999)
assert ok, err
+ @parameterized.expand(
+ [
+ ("https_loopback", "https://127.0.0.1/oauth2/token"),
+ ("https_imds", "https://169.254.169.254/token"),
+ ("http_public", "http://auth.example.com/token"),
+ ]
+ )
+ @override_settings(CLOUD_DEPLOYMENT="US")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.custom.source._is_host_safe",
+ side_effect=lambda host, team_id: (
+ host not in {"127.0.0.1", "169.254.169.254"},
+ None if host not in {"127.0.0.1", "169.254.169.254"} else "blocked",
+ ),
+ )
+ def test_rejects_unsafe_or_http_oauth2_token_url(self, _name: str, token_url: str, _mock):
+ # The token endpoint is vetted like base_url — internal/private hosts and plaintext
+ # http on Cloud are rejected (defense-in-depth alongside the Smokescreen egress proxy).
+ # base_url's host is allowed by the stub so the token_url check is the one under test.
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {"type": "oauth2", "client_id": "cid", "token_url": token_url}
+ ok, err = validate_manifest_urls(manifest, team_id=999)
+ assert not ok
+ assert "token_url" in (err or "")
+
+ @override_settings(CLOUD_DEPLOYMENT="US")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.custom.source._is_host_safe",
+ side_effect=lambda host, team_id: (True, None),
+ )
+ def test_accepts_safe_https_oauth2_token_url(self, _mock):
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/oauth2/token",
+ }
+ ok, err = validate_manifest_urls(manifest, team_id=999)
+ assert ok, err
+
class TestCustomSourceAssembleManifest(SimpleTestCase):
def test_rejects_invalid_json(self):
@@ -294,6 +424,44 @@ class TestCustomSourceAssembleManifest(SimpleTestCase):
assembled = source._assemble_manifest(config)
assert "token" not in assembled["client"]["auth"]
+ def test_injects_oauth2_secrets_and_preserves_manifest_fields(self):
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/token",
+ "grant_type": "refresh_token",
+ "scopes": "read:users",
+ }
+ source = CustomSource()
+ config = CustomSourceConfig(
+ manifest_json=json.dumps(manifest),
+ auth_oauth2_client_secret="cs_secret",
+ auth_oauth2_refresh_token="rt_secret",
+ )
+ auth = source._assemble_manifest(config)["client"]["auth"]
+ # Secrets injected from the config fields...
+ assert auth["client_secret"] == "cs_secret"
+ assert auth["refresh_token"] == "rt_secret"
+ # ...and the non-secret manifest fields left intact.
+ assert auth["client_id"] == "cid"
+ assert auth["token_url"] == "https://auth.example.com/token"
+ assert auth["grant_type"] == "refresh_token"
+ assert auth["scopes"] == "read:users"
+
+ def test_oauth2_leaves_secrets_absent_when_not_provided(self):
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/token",
+ }
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ auth = source._assemble_manifest(config)["client"]["auth"]
+ assert "client_secret" not in auth
+ assert "refresh_token" not in auth
+
class TestCustomSourceGetSchemas(SimpleTestCase):
def test_returns_one_schema_per_resource(self):
@@ -346,6 +514,16 @@ class TestCustomSourceGetSchemas(SimpleTestCase):
assert schema.incremental_fields[0]["field_type"] == expected
+def _oauth2_manifest() -> dict:
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {
+ "type": "oauth2",
+ "client_id": "cid",
+ "token_url": "https://auth.example.com/oauth2/token",
+ }
+ return manifest
+
+
class TestCustomSourceValidateCredentials(SimpleTestCase):
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")
def test_returns_true_on_2xx(self, mock_session):
@@ -358,6 +536,78 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):
assert ok, err
assert err is None
+ @patch.object(
+ OAuth2Auth,
+ "_obtain_token",
+ side_effect=OAuth2AuthRequestError(
+ "HTTP 401 from the OAuth2 token endpoint: invalid_client: bad creds",
+ error_code="invalid_client",
+ is_permanent=True,
+ ),
+ )
+ def test_oauth2_probe_permanent_token_error_blocks_with_clear_message(self, _mock_mint):
+ # A bad client_secret / token_url must fail at create time with a pointed token-endpoint
+ # message — not the generic "resource unreachable" of the data probe.
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_oauth2_manifest()), auth_oauth2_client_secret="cs")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert not ok
+ assert "OAuth2 token endpoint rejected" in (err or "")
+ assert "invalid_client" in (err or "")
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")
+ @patch.object(
+ OAuth2Auth,
+ "_obtain_token",
+ side_effect=OAuth2AuthRequestError("HTTP 503 from the OAuth2 token endpoint", is_permanent=False),
+ )
+ def test_oauth2_probe_transient_token_error_does_not_block(self, _mock_mint, mock_session):
+ # A 429 / 5xx at the token endpoint during the create-time probe is transient — it must
+ # not block creation; the first real sync retries it. The data probe is skipped entirely
+ # (no minted token to authenticate with), so the probe session is never even built — assert
+ # that, not a mocked 200 that would hide the real fall-through behavior.
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_oauth2_manifest()), auth_oauth2_client_secret="cs")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok, err
+ mock_session.assert_not_called()
+
+ @freeze_time("2025-01-01T00:00:00Z")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_oauth2_minted_token_joins_probe_redaction(self, mock_session):
+ # The pre-mint runs before the probe session is built, so the freshly-minted access token
+ # (and the static client_secret) are both registered for redaction on the data probe.
+ mock_session.return_value.request.return_value = MagicMock(status_code=200)
+
+ def fake_mint(self_auth, timeout=None):
+ self_auth.token = "minted-xyz"
+ self_auth.token_expiry = datetime.now(UTC) + timedelta(hours=1)
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_oauth2_manifest()), auth_oauth2_client_secret="cs_secret")
+ with patch.object(OAuth2Auth, "_obtain_token", autospec=True, side_effect=fake_mint):
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok, err
+ redact = mock_session.call_args.kwargs["redact_values"]
+ assert "cs_secret" in redact
+ assert "minted-xyz" in redact
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_probe_body_snippet_redacts_echoed_credential(self, mock_session):
+ # An upstream that echoes the sent credential in its 401/403 body must not leak it into the
+ # user-facing error — the snippet is run through _redact_secrets before being surfaced.
+ response = MagicMock(status_code=401)
+ response.headers = {}
+ response.raw.read.return_value = b"unauthorized: token sk_secret_value is invalid"
+ mock_session.return_value.request.return_value = response
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_minimal_manifest()), auth_token="sk_secret_value")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert not ok
+ assert "sk_secret_value" not in (err or "")
+ assert "***" in (err or "")
+
@parameterized.expand([401, 403])
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")
def test_returns_false_on_auth_rejection(self, status_code, mock_session):
@@ -752,6 +1002,35 @@ class TestManifestRequestHosts(SimpleTestCase):
def test_unparseable_returns_empty(self, _name, raw):
assert manifest_request_hosts(raw) == frozenset()
+ def test_oauth2_token_url_host_is_tracked(self):
+ # The token endpoint receives the stored client_secret, so its host must be in the
+ # re-entry set — otherwise an editor who can't read the secret could repoint token_url
+ # at a host they control while keeping the secret, exfiltrating it past the gate.
+ manifest = json.dumps(
+ {
+ "client": {
+ "base_url": "https://api.example.com",
+ "auth": {"type": "oauth2", "client_id": "cid", "token_url": "https://auth.other.net/oauth2/token"},
+ },
+ "resources": [{"name": "r", "endpoint": {"path": "/users"}}],
+ }
+ )
+ assert manifest_request_hosts(manifest) == frozenset({"api.example.com", "auth.other.net"})
+
+ def test_non_oauth2_auth_token_url_is_ignored(self):
+ # A stray token_url on a non-oauth2 auth is inert (no credential goes there), so it
+ # must not register a host and trigger spurious re-entry prompts.
+ manifest = json.dumps(
+ {
+ "client": {
+ "base_url": "https://api.example.com",
+ "auth": {"type": "bearer", "token_url": "https://auth.other.net/token"},
+ },
+ "resources": [{"name": "r", "endpoint": {"path": "/users"}}],
+ }
+ )
+ assert manifest_request_hosts(manifest) == frozenset({"api.example.com"})
+
class TestCustomSourceSourceForPipeline(SimpleTestCase):
def test_invalid_manifest_raises_non_retryable(self):
@@ -892,6 +1171,18 @@ class TestCustomSourceNonRetryableErrors(SimpleTestCase):
assert "not found in config" in str(ctx.exception)
assert "not found in config" in CustomSource().get_non_retryable_errors()
+ @parameterized.expand(["invalid_client", "invalid_grant"])
+ def test_oauth2_permanent_errors_are_classified_non_retryable(self, error_code):
+ # A permanent OAuth2 token rejection (invalid_client / invalid_grant) surfaces the
+ # standard error code in OAuth2Auth's failure message, and the classifier matches that
+ # substring so the job fails fast instead of burning its whole retry budget.
+ non_retryable = CustomSource().get_non_retryable_errors()
+ assert error_code in non_retryable
+ message = OAuth2AuthRequestError(
+ f"HTTP 401 from the OAuth2 token endpoint: {error_code}: nope", error_code=error_code, is_permanent=True
+ )
+ assert any(key in str(message) for key in non_retryable)
+
def _fanout_manifest() -> dict:
"""A parent (`forms`) + fan-out child (`responses`) that binds the parent's
@@ -1872,3 +2163,97 @@ class TestCustomSourcePreviewResource(SimpleTestCase):
result = source.preview_resource(config, team_id=999, resource_name="users")
assert "topsecret-token" not in json.dumps(result._asdict())
+
+
+def _classify_non_retryable(error: Exception) -> bool:
+ """Replicate the pipeline's sync-time non-retryable check (substring match on str(error))."""
+ non_retryable_errors = CustomSource().get_non_retryable_errors()
+ return any(key in str(error) for key in non_retryable_errors)
+
+
+class TestCustomSourceOAuth2NonRetryableClassification(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # A token-endpoint failure that carries no standard OAuth error code (a bare 4xx body or
+ # an unfollowed 3xx redirect) used to slip past the old invalid_client/invalid_grant-only
+ # match and retry until the activity budget was exhausted. Drive it through the real raise.
+ ("redirect_302", 302, {}),
+ ("bare_400_no_error_code", 400, {}),
+ # OAuth error codes other than invalid_client/invalid_grant — also permanent, also missed
+ # before. Run them through the real _extract_token_error path.
+ ("unauthorized_client", 400, {"error": "unauthorized_client"}),
+ ("unsupported_grant_type", 400, {"error": "unsupported_grant_type"}),
+ ("invalid_scope", 400, {"error": "invalid_scope"}),
+ ("invalid_request", 400, {"error": "invalid_request"}),
+ ]
+ )
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_permanent_token_status_errors_classified_non_retryable(self, _name, status_code, payload, mock_session):
+ response = MagicMock(status_code=status_code)
+ response.raw.read.return_value = json.dumps(payload).encode()
+ mock_session.return_value.post.return_value = response
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+ with self.assertRaises(OAuth2AuthRequestError) as ctx:
+ auth._obtain_token()
+ assert ctx.exception.is_permanent
+ assert _classify_non_retryable(ctx.exception), str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ # Malformed/unexpected token responses raise permanent errors whose messages share no
+ # phrase with the status-code path — the marker is what makes them all classifiable.
+ ("non_json_body", "non_json"),
+ ("non_dict_body", [1, 2, 3]),
+ ("missing_access_token", {"expires_in": 60}),
+ ]
+ )
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_permanent_token_response_errors_classified_non_retryable(self, _name, body, mock_session):
+ response = MagicMock(status_code=200)
+ if body == "non_json":
+ response.raw.read.return_value = b"not json"
+ else:
+ response.raw.read.return_value = json.dumps(body).encode()
+ mock_session.return_value.post.return_value = response
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+ with self.assertRaises(OAuth2AuthRequestError) as ctx:
+ auth._obtain_token()
+ assert ctx.exception.is_permanent
+ assert _classify_non_retryable(ctx.exception), str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ # The original two codes still match (their dedicated copy is retained).
+ ("invalid_client", 401, {"error": "invalid_client"}),
+ ("invalid_grant", 400, {"error": "invalid_grant"}),
+ ]
+ )
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_known_oauth_codes_still_classified_non_retryable(self, _name, status_code, payload, mock_session):
+ response = MagicMock(status_code=status_code)
+ response.raw.read.return_value = json.dumps(payload).encode()
+ mock_session.return_value.post.return_value = response
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+ with self.assertRaises(OAuth2AuthRequestError) as ctx:
+ auth._obtain_token()
+ assert _classify_non_retryable(ctx.exception), str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ # Transient (429 / 5xx) token errors must stay retryable — the marker is absent, so they
+ # must NOT match. Guards the fix from over-matching the shared token-endpoint phrasing.
+ ("rate_limited_429", 429, {"error": "slow_down"}),
+ ("server_error_503", 503, {}),
+ ]
+ )
+ @patch(f"{AUTH_MODULE}.make_tracked_session")
+ def test_transient_token_errors_stay_retryable(self, _name, status_code, payload, mock_session):
+ response = MagicMock(status_code=status_code)
+ response.raw.read.return_value = json.dumps(payload).encode()
+ mock_session.return_value.post.return_value = response
+ auth = OAuth2Auth(token_url="https://a/t", client_id="cid", client_secret="cs")
+ with self.assertRaises(OAuth2AuthRequestError) as ctx:
+ auth._obtain_token()
+ assert not ctx.exception.is_permanent
+ assert OAUTH2_PERMANENT_ERROR_MARKER not in str(ctx.exception)
+ assert not _classify_non_retryable(ctx.exception), str(ctx.exception)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 80061b8c9a09..dd97ed07eb3f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -875,6 +875,8 @@ class CustomSourceConfig(config.Config):
auth_token: str | None = None
auth_api_key: str | None = None
auth_password: str | None = None
+ auth_oauth2_client_secret: str | None = None
+ auth_oauth2_refresh_token: str | None = None
@config.config