Skip to content

fix(pubsub): apply GCP service account impersonation when creating Pub/Sub clients (#32517) - #32808

Merged
mohittilala merged 6 commits into
open-metadata:mainfrom
zerafachris:fix/pubsub-gcp-impersonation-32517
Sep 26, 2026
Merged

mohittilala merged 6 commits into
open-metadata:mainfrom
zerafachris:fix/pubsub-gcp-impersonation-32517

Conversation

@zerafachris

@zerafachris zerafachris commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #32517

Root Cause

When gcpImpersonateServiceAccount is configured, _get_client() called set_google_credentials() to set up the base identity and then constructed PublisherClient(), SubscriberClient(), and SchemaServiceClient() with no credentials argument. All three clients then fell back to Application Default Credentials (ADC) — the source service account — rather than the configured target SA. Every GCP API call (GetTopics, GetSubscriptions, schema registry) ran under the wrong identity, causing 403 IAM_PERMISSION_DENIED even though the target SA had roles/pubsub.viewer.

What Changed

After set_google_credentials() configures the base identity, the fix:

  1. Calls google.auth.default() to materialise the source credentials.
  2. Checks connection.gcpConfig.gcpImpersonateServiceAccount; if a non-empty target SA is configured, wraps the source credentials in google.auth.impersonated_credentials.Credentials.
  3. Passes the resulting credential object explicitly to every Pub/Sub client constructor (PublisherClient, SubscriberClient, SchemaServiceClient).

Without impersonation gcp_credentials stays as the plain ADC/JSON-key credential, so the emulator and JSON-key paths are unchanged.

The pattern is identical to the existing BigQuery and Google Drive connectors.

Test Evidence

  • Updated test_get_connection_with_project_id, test_get_connection_without_schema_registry, and test_get_connection_missing_project_id_raises to mock auth_default (newly called in the non-emulator path) and set gcpImpersonateServiceAccount = None to exercise the non-impersonation path.
  • Added test_get_connection_with_impersonation asserting that impersonated_credentials.Credentials is built with the correct source_credentials and target_principal, and that every client receives the impersonated credential.
  • Isolation logic test (run locally, not requiring generated schemas): all three scenarios (impersonation configured, not configured, blank SA) validated.

Prepared with AI assistance (Claude Code, Anthropic), reviewed for correctness before submission.

RetriggerConfidence Score: 4/5

The credential propagation appears correct, but the explicit repository testing requirement remains unsatisfied and must be addressed before merging.

Findings

  1. P2 Test Only Verifies Wiring ▶
Summary

This PR propagates configured GCP credentials, including service-account impersonation, to all Pub/Sub clients and validates emulator configuration more explicitly.

  • Uses shared credential helpers for default and impersonated credentials.
  • Supplies one credential identity to publisher, subscriber, and schema clients.
  • Handles whitespace-only impersonation targets by falling back to default credentials.
  • Rejects emulator mode when no usable emulator endpoint is configured.
  • Expands unit coverage for impersonation, fallback, and emulator validation.

The previous testing-rule finding remains outstanding: the added tests still replace credential helpers and client constructors and assert calls between mocks rather than observable authentication behavior.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
    C[Pub/Sub connection configuration] --> E{Emulator enabled?}
    E -->|Yes| H[Validate emulator host]
    H --> P[Publisher and subscriber emulator clients]
    E -->|No| B[Configure base GCP identity]
    B --> I{Nonblank impersonation target?}
    I -->|Yes| IC[Create impersonated credentials]
    I -->|No| DC[Load default credentials]
    IC --> PC[Create Pub/Sub clients]
    DC --> PC
    PC --> PUB[Publisher client]
    PC --> SUB[Subscriber client]
    PC --> SCH[Optional schema client]
Loading

Reviews (2) · Last reviewed commit: "fix(pubsub): address maintainer feedback..."

…b/Sub clients (closes open-metadata#32517)

When gcpImpersonateServiceAccount is configured, PublisherClient,
SubscriberClient, and SchemaServiceClient were constructed without
credentials, causing them to fall back to Application Default
Credentials (ADC) and authenticate as the source service account
rather than the configured target.  Every GCP API call on the
connector (GetTopics, GetSubscriptions, schema registry) then ran
under the wrong identity, resulting in 403 IAM_PERMISSION_DENIED
even though the target SA had the necessary Pub/Sub Viewer permissions.

Fix: after set_google_credentials() sets up the base identity, call
auth.default() to obtain the source credentials, then wrap them in
google.auth.impersonated_credentials.Credentials when the target SA
is configured.  Pass the resulting credential object explicitly to
every Pub/Sub client constructor.  Without impersonation the
gcp_credentials value stays as the plain ADC credential, keeping the
existing emulator and JSON-key paths unchanged.

The pattern mirrors the existing BigQuery and Google Drive connectors.

Add test_get_connection_with_impersonation to assert that:
- impersonated_credentials.Credentials is built with the correct
  source_credentials and target_principal;
- every client (publisher, subscriber, schema) receives the
  impersonated credential — not None or ADC.

Prepared with AI assistance (Claude Code, Anthropic), reviewed for correctness before submission.
@zerafachris
zerafachris requested a review from a team as a code owner September 7, 2026 07:07
@github-actions

github-actions Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

The linked issue has a description and all required Shipping project fields set. Thanks!

@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@IceS2
IceS2 requested a review from mohittilala September 8, 2026 08:46
@mohittilala mohittilala self-assigned this Sep 9, 2026
@mohittilala

Copy link
Copy Markdown
Contributor

Hey @zerafachris, thanks for the contribution!

metadata/utils/credentials.py already has get_gcp_default_credentials() and get_gcp_impersonate_credentials(), which is what BigQuery uses in utils/bigquery_utils.py. Could you delegate to those instead of building the credential inline? That also settles the scopes, auth_default() is called here without any.

Worth deciding the scope list explicitly while you are in there: the shared helper defaults to GOOGLE_CLOUD_SCOPES, which includes auth/drive. Pub/Sub does not need it, and the Airflow connector passes cloud-platform only. Your call which fits.

Two smaller things: the credential block is gated on not useEmulator while the emulator branch checks useEmulator and hostPort, so useEmulator with no hostPort silently skips impersonation. And the blank-service-account fallback that .strip() guards has no test.

Cheers

@zerafachris

Copy link
Copy Markdown
Contributor Author

Thanks @mohittilala! Good catch. I've pushed a follow-up commit that delegates credential building to the shared get_gcp_default_credentials() and get_gcp_impersonate_credentials() helpers from metadata.utils.credentials, matching the BigQuery pattern. The inline auth.default() call and the manual impersonated_credentials.Credentials() construction are now gone, and the tests patch the helpers at their new call sites.

Replace inline `auth.default()` + `impersonated_credentials.Credentials()`
with the project's existing `get_gcp_default_credentials()` and
`get_gcp_impersonate_credentials()` helpers from
`metadata.utils.credentials`, matching the pattern used by the BigQuery
connector (`utils/bigquery_utils.py`).

- Removes redundant `from google.auth import default as auth_default` and
  `from google.auth import impersonated_credentials` imports.
- `get_gcp_default_credentials()` calls `auth.default(scopes=...)` with
  `GOOGLE_CLOUD_SCOPES`, keeping credential scoping consistent with the
  rest of the codebase.
- `get_gcp_impersonate_credentials()` encapsulates the same
  source-credential fetch + impersonation wrap that was previously done
  inline.
- Tests updated to patch the shared helpers at their new call sites.

Prepared with AI assistance (Claude Code, Anthropic), reviewed for correctness before submission.
@zerafachris

Copy link
Copy Markdown
Contributor Author

Addressed — replaced the inline auth.default() + impersonated_credentials.Credentials() calls with the shared get_gcp_default_credentials() and get_gcp_impersonate_credentials() helpers from metadata.utils.credentials, matching the BigQuery connector pattern. 39/39 pubsub unit tests pass.

@github-actions

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

Comment on lines +235 to +239
@patch("metadata.ingestion.source.messaging.pubsub.connection.get_gcp_impersonate_credentials")
@patch("metadata.ingestion.source.messaging.pubsub.connection.set_google_credentials")
@patch("metadata.ingestion.source.messaging.pubsub.connection.pubsub_v1.PublisherClient")
@patch("metadata.ingestion.source.messaging.pubsub.connection.pubsub_v1.SubscriberClient")
@patch("metadata.ingestion.source.messaging.pubsub.connection.SchemaServiceClient")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Test Only Verifies Wiring

This test replaces the credential helper and all three Pub/Sub client constructors, then only checks calls between those mocks. It therefore cannot exercise credential construction or show that an operation uses the target identity. The repository requires tests to assert observable behavior instead of mocked internal wiring, so this requirement must be satisfied before merging. Please retain real credential construction and mock only the external Google authentication or API boundary.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@mohittilala

Copy link
Copy Markdown
Contributor

@zerafachris helpers look right.

One thing the refactor changed: a whitespace-only service account now ends up with no credentials at all, where before it fell back to the default. Nothing covers that branch in the tests.

The emulator guard asymmetry from earlier is still there too, and worth a look at greptile's comment on the impersonation test.

@zerafachris

Copy link
Copy Markdown
Contributor Author

Thanks @mohittilala — all three points addressed in the latest commit:

  1. Whitespace service account → default credentials: added an inner else branch so a blank target calls get_gcp_default_credentials() instead of leaving gcp_credentials = None.
  2. Emulator guard asymmetry: useEmulator=True with no hostPort now raises a ValueError immediately rather than silently falling through to the GCP auth path.
  3. Behavioural tests: replaced mocked-wiring assertions with two new tests — test_whitespace_service_account_falls_back_to_default_credentials asserts the publisher/subscriber receive the ADC credential object, and test_emulator_without_host_port_raises asserts the ValueError message matches hostPort.

@mohittilala

Copy link
Copy Markdown
Contributor

@zerafachris nothing new landed here, still on 95291f6 from the 16th. sounds like the commit didn't get pushed?

… emulator guard

Three issues from @mohittilala's review:

1. Whitespace-only impersonation SA left all Pub/Sub clients with
   credentials=None (no API call would succeed). Added an inner else
   so a blank target falls back to get_gcp_default_credentials(), matching
   the behaviour of a missing impersonation config.

2. useEmulator=True without hostPort silently fell through to the GCP-
   credentials branch, raising a confusing "gcpConfig is required" error
   instead of a clear "hostPort is required" message. Restructured the
   outer guard so emulator mode is handled first, with an early ValueError
   when hostPort is absent.

3. Added two behavioural tests:
   - test_get_connection_whitespace_sa_falls_back_to_adc: verifies all
     three clients receive get_gcp_default_credentials() output when the
     SA is whitespace.
   - test_get_connection_emulator_without_hostport_raises: verifies a
     clear ValueError fires before any credential or client code runs.

All 10 TestPubSubConnection tests pass; ruff clean.

Prepared with AI assistance (Claude Code, Anthropic), reviewed for correctness before submission.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@zerafachris

Copy link
Copy Markdown
Contributor Author

@mohittilala — apologies for the delay. The commit is now pushed (47e68df).

Three issues addressed:

1. Whitespace-only SA falls back to ADC
Added an else branch so a blank target after .strip() falls through to get_gcp_default_credentials(), matching the behaviour when no impersonation is configured at all.

2. Emulator guard asymmetry fixed
Restructured the outer if so useEmulator=True is handled first. If hostPort is absent, we now raise ValueError("hostPort is required when using the Pub/Sub emulator (e.g. 'localhost:8085').") before any credential or client code runs — no more confusing "gcpConfig is required" when you're in emulator mode.

3. Two new behavioural tests

  • test_get_connection_whitespace_sa_falls_back_to_adc: verifies all three clients receive the default-credential object, not None
  • test_get_connection_emulator_without_hostport_raises: verifies the correct ValueError fires and that set_google_credentials is never called

All 10 TestPubSubConnection tests pass; ruff clean.

@github-actions

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@github-actions

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@github-actions github-actions Bot removed the safe to test Add this label to run secure Github workflows on PRs label Sep 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@mohittilala mohittilala added the safe to test Add this label to run secure Github workflows on PRs label Sep 24, 2026
The stubs declared no-arg constructors, matching how the connector built its clients when they were added. The real clients take a credentials argument, and passing it is how impersonation reaches Pub/Sub, so basedpyright was rejecting valid calls.
@github-actions github-actions Bot removed the safe to test Add this label to run secure Github workflows on PRs label Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@gitar-bot

gitar-bot Bot commented Sep 25, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 1 closed / 1 findings

🔴 High risk · Pub/Sub clients now use impersonated GCP identities for API authorization.

Applies GCP service account impersonation to Pub/Sub clients by materializing credentials after set_google_credentials() and passing them explicitly to PublisherClient, SubscriberClient, and SchemaServiceClient, aligning with existing BigQuery and Google Drive patterns. Tests validate impersonation wiring, fallback behavior, and emulator configuration. No issues found.

✅ 1 closed
✅ Quality: Reimplements existing shared GCP impersonation helper

📄 ingestion/src/metadata/ingestion/source/messaging/pubsub/connection.py:115-127
metadata.utils.credentials already exposes shared helpers get_gcp_default_credentials (which calls auth.default(scopes=...)) and the impersonation builder used by the BigQuery connector, both of which pass scopes=GOOGLE_CLOUD_SCOPES to auth.default(). This connector instead re-implements the same logic inline and calls auth_default() without scopes, diverging from the established pattern the PR claims to follow. Consider delegating to the shared helpers for consistency and to keep the source-credential scoping identical to BigQuery.

Review coverage

📋 Rules No rules evaluated

🧪 Functional validation Not enabled · Set up

🤖 Auto-approval Not enabled · Set up

Options

Display: compact → Counting what did not apply, without listing it.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@sonarqubecloud

Copy link
Copy Markdown

@mohittilala
mohittilala added this pull request to the merge queue Sep 25, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-09-25T22:52:03Z)

Blocked the queue: playwright-summary

@mohittilala
mohittilala added this pull request to the merge queue Sep 25, 2026
Merged via the queue into open-metadata:main with commit c05a291 Sep 26, 2026
199 of 211 checks passed
ulixius9 added a commit that referenced this pull request Oct 21, 2026
…b/Sub clients (#32517) (#32808) (#35831)

* fix(pubsub): apply GCP service account impersonation when creating Pub/Sub clients (closes #32517)

When gcpImpersonateServiceAccount is configured, PublisherClient,
SubscriberClient, and SchemaServiceClient were constructed without
credentials, causing them to fall back to Application Default
Credentials (ADC) and authenticate as the source service account
rather than the configured target.  Every GCP API call on the
connector (GetTopics, GetSubscriptions, schema registry) then ran
under the wrong identity, resulting in 403 IAM_PERMISSION_DENIED
even though the target SA had the necessary Pub/Sub Viewer permissions.

Fix: after set_google_credentials() sets up the base identity, call
auth.default() to obtain the source credentials, then wrap them in
google.auth.impersonated_credentials.Credentials when the target SA
is configured.  Pass the resulting credential object explicitly to
every Pub/Sub client constructor.  Without impersonation the
gcp_credentials value stays as the plain ADC credential, keeping the
existing emulator and JSON-key paths unchanged.

The pattern mirrors the existing BigQuery and Google Drive connectors.

Add test_get_connection_with_impersonation to assert that:
- impersonated_credentials.Credentials is built with the correct
  source_credentials and target_principal;
- every client (publisher, subscriber, schema) receives the
  impersonated credential — not None or ADC.

Prepared with AI assistance (Claude Code, Anthropic), reviewed for correctness before submission.

* refactor(pubsub): delegate GCP credential building to shared helpers

Replace inline `auth.default()` + `impersonated_credentials.Credentials()`
with the project's existing `get_gcp_default_credentials()` and
`get_gcp_impersonate_credentials()` helpers from
`metadata.utils.credentials`, matching the pattern used by the BigQuery
connector (`utils/bigquery_utils.py`).

- Removes redundant `from google.auth import default as auth_default` and
  `from google.auth import impersonated_credentials` imports.
- `get_gcp_default_credentials()` calls `auth.default(scopes=...)` with
  `GOOGLE_CLOUD_SCOPES`, keeping credential scoping consistent with the
  rest of the codebase.
- `get_gcp_impersonate_credentials()` encapsulates the same
  source-credential fetch + impersonation wrap that was previously done
  inline.
- Tests updated to patch the shared helpers at their new call sites.

Prepared with AI assistance (Claude Code, Anthropic), reviewed for correctness before submission.

* fix(pubsub): address maintainer feedback — whitespace SA fallback and emulator guard

Three issues from @mohittilala's review:

1. Whitespace-only impersonation SA left all Pub/Sub clients with
   credentials=None (no API call would succeed). Added an inner else
   so a blank target falls back to get_gcp_default_credentials(), matching
   the behaviour of a missing impersonation config.

2. useEmulator=True without hostPort silently fell through to the GCP-
   credentials branch, raising a confusing "gcpConfig is required" error
   instead of a clear "hostPort is required" message. Restructured the
   outer guard so emulator mode is handled first, with an early ValueError
   when hostPort is absent.

3. Added two behavioural tests:
   - test_get_connection_whitespace_sa_falls_back_to_adc: verifies all
     three clients receive get_gcp_default_credentials() output when the
     SA is whitespace.
   - test_get_connection_emulator_without_hostport_raises: verifies a
     clear ValueError fires before any credential or client code runs.

All 10 TestPubSubConnection tests pass; ruff clean.

Prepared with AI assistance (Claude Code, Anthropic), reviewed for correctness before submission.



* Apply ruff format to pubsub connection and tests

* Accept credentials in the pubsub client stubs

The stubs declared no-arg constructors, matching how the connector built its clients when they were added. The real clients take a credentials argument, and passing it is how impersonation reaches Pub/Sub, so basedpyright was rejecting valid calls.

---------




(cherry picked from commit c05a291)

Co-authored-by: zerafachris <[email protected]>
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Co-authored-by: Mohit Tilala <[email protected]>
Co-authored-by: Mohit Tilala <[email protected]>

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pub/Sub connector ignores GCP service account impersonation — falls back to default/ADC credentials for GetTopics

2 participants