Skip to content

fix(auth): invalidate cached ADC credentials and clients on file change or auth error - #248

Merged
dborowitz merged 1 commit into
mainfrom
dborowitz-adc-cache-invalidation
Dec 4, 2026
Merged

dborowitz merged 1 commit into
mainfrom
dborowitz-adc-cache-invalidation

Conversation

@dborowitz

@dborowitz dborowitz commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Automatically invalidates cached Application Default Credentials (_CREDENTIALS_CACHE) and Dataproc control-plane clients (_CLIENT_CACHE) when the underlying credentials file or GOOGLE_CLOUD_QUOTA_PROJECT changes, or when an auth/credential refresh error occurs—fixing a regression from #211 where re-running gcloud auth application-default login in a terminal did not take effect in an already-running notebook kernel without restarting the kernel.

Problem

#211 added process-wide caching for google.auth.default() (_CREDENTIALS_CACHE in client/proxy.py) and SessionControllerClient (_CLIENT_CACHE in session.py) keyed on client options and environment variables. In long-lived interactive sessions (such as JupyterLab):

  1. Once cached credentials expire (for example, after RAPT/reauth expiry), SessionControllerClient and SessionTemplateControllerClient RPCs fail inside gRPC's AuthMetadataPlugin (503 ServiceUnavailable: Getting metadata from plugin failed with error: Reauthentication is needed...) or REST's AuthorizedSession (RefreshError / 401 Unauthorized), bypassing get_refreshed_credentials().
  2. Running gcloud auth application-default login updates ~/.config/gcloud/application_default_credentials.json on disk, but neither _CREDENTIALS_CACHE nor _CLIENT_CACHE noticed the file change—and even when get_refreshed_credentials() evicted _CREDENTIALS_CACHE, _CLIENT_CACHE and Builder._session_template_controller_client still pinned the stale credentials/clients.

Changes

  • Proactive file-stat & env-var invalidation (client/proxy.py, session.py):
    • Added pure-Python file_stat_stamp() ((st_mtime_ns, st_ctime_ns, st_size, st_ino, st_dev)) and adc_file_stamp() helpers (using GOOGLE_APPLICATION_CREDENTIALS or google.auth._cloud_sdk.get_application_default_credentials_path(), with zero subprocesses) and stored (adc_stamp, (creds, project)) in _CREDENTIALS_CACHE, statting before read so concurrent rewrites are never tagged with a post-read stamp.
    • Included GOOGLE_CLOUD_QUOTA_PROJECT in both _CREDENTIALS_CACHE and _CLIENT_CACHE cache keys.
    • Unified SessionControllerClient and SessionTemplateControllerClient creation in _create_dataproc_client(), validating default-ADC entries in _CLIENT_CACHE by credential object identity (entry_creds is creds)—automatically staying in sync with _CREDENTIALS_CACHE reloads and clears—and validating custom ClientOptions entries (credentials_file via abspath + stat stamp, quota_project_id, scopes, falling back to adc_file_stamp() when credentials_file == "").
    • Updated Builder.session_controller_client and Builder.session_template_controller_client not to pin cacheable clients on self while preserving explicit test injection and per-builder memoization for uncacheable client_cert_source / client_encrypted_cert_source options.
  • Reactive auth-error eviction (session.py, _session_templates.py, client/proxy.py):
    • Added _is_auth_error() / _maybe_evict_auth_caches() to clear _CREDENTIALS_CACHE and _CLIENT_CACHE when a Dataproc control-plane RPC fails with GoogleAuthError, Unauthorized (covering both gRPC Unauthenticated and REST HTTP 401), or a gRPC auth-metadata-plugin ServiceUnavailable (Getting metadata from plugin failed / Reauthentication is needed), without churning caches on transient non-auth 503s.
    • Wired _maybe_evict_auth_caches() into all SessionControllerClient control-plane error paths and into Builder._get_session_template() via an on_error hook on _session_templates.fetch_session_template().
    • Added _evict_credentials(creds) so refresh failures and WebSocket TCP bridge HTTP 401 errors in connect_tcp_bridge() evict only cache entries referencing the failed credentials instance (without wiping concurrently rotated credentials).
  • Unit tests (tests/unit/test_dataproc.py):
    • Added tests covering ADC file updates/deletion (CLOUDSDK_CONFIG, GOOGLE_APPLICATION_CREDENTIALS, relative/empty credentials_file, quota_project_id, GOOGLE_CLOUD_QUOTA_PROJECT), cross-cache rebuild when _CREDENTIALS_CACHE is cleared or refresh fails, Builder.session_controller_client and Builder.session_template_controller_client reauth tracking and injection/cert-source memoization, _is_auth_error() classification (including REST Unauthorized), reactive eviction on gRPC/REST auth errors and _get_session_template() vs. non-auth 503s, and concurrent WebSocket 401 cache eviction.

Verification

  • pyink --check on modified Python files: passed
  • pytest -q -p no:cacheprovider tests/unit/test_dataproc.py tests/unit/test_session_templates.py: 43 passed, 25 subtests passed

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces robust credential and client caching mechanisms, including cache invalidation when Application Default Credentials (ADC) or custom credential files are modified on disk. It also adds automatic cache eviction upon encountering authentication errors during API calls, backed by comprehensive unit tests. The feedback recommends using os.path.expanduser in file_stat_stamp and adc_file_stamp to correctly resolve and track credential file paths that contain user directory shortcuts (like ~).

…ge or auth error

PR #211 introduced process-wide caching for Application Default Credentials
(_CREDENTIALS_CACHE in client/proxy.py) and Dataproc SessionControllerClient
(_CLIENT_CACHE in session.py) keyed only on client options and environment
variables. In long-lived notebook kernels, re-authenticating on disk with
`gcloud auth application-default login` after RAPT or refresh-token expiry left
both caches pinned to the stale pre-reauth credentials until kernel restart or
a manual `clear_dataproc_caches()` call.

Two complementary fixes:
1. Proactive file-stat invalidation: track `(abs_path, (st_mtime_ns,
   st_ctime_ns, st_size, st_ino, st_dev))` for the active ADC file
   (`GOOGLE_APPLICATION_CREDENTIALS` or the gcloud ADC path, resolved purely in
   Python with no subprocesses) and include `GOOGLE_CLOUD_QUOTA_PROJECT` in
   cache keys. Unify `SessionControllerClient` and
   `SessionTemplateControllerClient` through `_create_dataproc_client()`,
   validating `_CLIENT_CACHE` entries by credential object identity
   (`entry_creds is creds`) for default ADC or by file/ADC stat fingerprint
   for custom `ClientOptions` (`credentials_file`, `quota_project_id`,
   `scopes`). Replacing or deleting the credentials file on disk now
   invalidates both caches automatically on the next call.
2. Reactive auth-error eviction: evict both `_CREDENTIALS_CACHE` and
   `_CLIENT_CACHE` when a Dataproc control-plane RPC (including best-effort
   `GetSessionTemplate`) fails with `GoogleAuthError`, `Unauthorized`
   (covering both gRPC `Unauthenticated` and REST HTTP 401), or a gRPC auth
   metadata plugin `ServiceUnavailable` ("Getting metadata from plugin failed"
   / "Reauthentication is needed"), and evict the failed credentials entry
   when a token refresh or WebSocket TCP bridge handshake fails with HTTP 401.
   Also avoid pinning cached `SessionControllerClient` or
   `SessionTemplateControllerClient` instances onto `Builder` (while
   preserving explicit test injection and per-builder memoization for
   uncacheable `client_cert_source` options).
@dborowitz
dborowitz force-pushed the dborowitz-adc-cache-invalidation branch from a2bf81b to a75ee39 Compare December 4, 2026 21:03
@dborowitz
dborowitz merged commit 0dd0726 into main Dec 4, 2026
29 checks passed
@dborowitz
dborowitz deleted the dborowitz-adc-cache-invalidation branch December 4, 2026 21:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants