From a75ee39f99f96aaea3fc9f0d5d5d81830ff64ca0 Mon Sep 17 00:00:00 2001 From: Dave Borowitz Date: Thu, 3 Dec 2026 14:11:21 -0800 Subject: [PATCH] fix(auth): invalidate cached ADC credentials and clients on file change 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). --- .../_session_templates.py | 3 + .../managed_spark_connect/client/proxy.py | 84 +- google/cloud/managed_spark_connect/session.py | 178 ++-- tests/unit/test_dataproc.py | 800 ++++++++++++++++++ 4 files changed, 1010 insertions(+), 55 deletions(-) diff --git a/google/cloud/managed_spark_connect/_session_templates.py b/google/cloud/managed_spark_connect/_session_templates.py index f5f1e28d..661a26e9 100644 --- a/google/cloud/managed_spark_connect/_session_templates.py +++ b/google/cloud/managed_spark_connect/_session_templates.py @@ -84,6 +84,7 @@ def fetch_session_template( *, project_id: Optional[str], region: Optional[str], + on_error: Optional[Callable[[Exception], None]] = None, ) -> Optional[SessionTemplate]: """Fetch a ``SessionTemplate`` best-effort, returning ``None`` on error.""" if not template_name: @@ -95,6 +96,8 @@ def fetch_session_template( request = GetSessionTemplateRequest(name=qualified_name) return get_client().get_session_template(request) except Exception as e: + if on_error is not None: + on_error(e) logger.debug( "Could not read session template %s: %s", qualified_name, e ) diff --git a/google/cloud/managed_spark_connect/client/proxy.py b/google/cloud/managed_spark_connect/client/proxy.py index ef671f6d..3011065f 100755 --- a/google/cloud/managed_spark_connect/client/proxy.py +++ b/google/cloud/managed_spark_connect/client/proxy.py @@ -70,12 +70,73 @@ _DEFAULT_SILENCE_LIMIT_S = 150.0 +def file_stat_stamp(path): + """Return a lightweight stat fingerprint for ``path``, or ``None`` if absent.""" + if not path: + return None + try: + st = os.stat(path) + except OSError: + return None + return (st.st_mtime_ns, st.st_ctime_ns, st.st_size, st.st_ino, st.st_dev) + + +def _default_adc_file_path(): + """Return the credentials file path consulted by ``google.auth.default()``. + + Pure Python (environment variables and path joins only); never spawns a + subprocess. + """ + explicit = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") or "" + if explicit: + return explicit + try: + from google.auth import _cloud_sdk + + return _cloud_sdk.get_application_default_credentials_path() + except Exception: + pass + config_dir = os.environ.get("CLOUDSDK_CONFIG") + if not config_dir: + if os.name == "nt": + appdata = os.environ.get("APPDATA") + if appdata: + config_dir = os.path.join(appdata, "gcloud") + else: + config_dir = os.path.join( + os.environ.get("SystemDrive", "C:"), "\\", "gcloud" + ) + else: + config_dir = os.path.join( + os.path.expanduser("~"), ".config", "gcloud" + ) + return os.path.join(config_dir, "application_default_credentials.json") + + +def adc_file_stamp(): + """Return ``(abs_path, file_stat_stamp)`` for the current default ADC file.""" + adc_path = _default_adc_file_path() + return (os.path.abspath(adc_path), file_stat_stamp(adc_path)) + + def clear_credentials_cache(): """Clear process-wide cached Application Default Credentials.""" with _AUTH_LOCK: _CREDENTIALS_CACHE.clear() +def _evict_credentials(creds): + """Remove cached entries pointing to ``creds`` without disturbing newer loads.""" + with _AUTH_LOCK: + stale_keys = [ + key + for key, (_, loaded) in _CREDENTIALS_CACHE.items() + if loaded[0] is creds + ] + for key in stale_keys: + del _CREDENTIALS_CACHE[key] + + def get_default_credentials(scopes=None): """Obtain Application Default Credentials with Cloud Platform scopes.""" scopes_tuple = tuple(scopes) if scopes is not None else _DEFAULT_SCOPES @@ -87,16 +148,21 @@ def get_default_credentials(scopes=None): os.environ.get("CLOUDSDK_CONFIG"), os.environ.get("APPDATA"), os.environ.get("GOOGLE_CLOUD_PROJECT"), + os.environ.get("GOOGLE_CLOUD_QUOTA_PROJECT"), os.environ.get("GCLOUD_PROJECT"), os.environ.get("DEVSHELL_PROJECT_ID"), os.environ.get("HOME"), ) with _AUTH_LOCK: - cached = _CREDENTIALS_CACHE.get(cache_key) - if cached is None: - cached = auth_default(scopes=list(scopes_tuple)) - _CREDENTIALS_CACHE[cache_key] = cached - return cached + # Stat before reading so a concurrent credential file rewrite is never + # tagged with a newer post-read fingerprint. + adc_stamp = adc_file_stamp() + entry = _CREDENTIALS_CACHE.get(cache_key) + if entry is not None and entry[0] == adc_stamp: + return entry[1] + loaded = auth_default(scopes=list(scopes_tuple)) + _CREDENTIALS_CACHE[cache_key] = (adc_stamp, loaded) + return loaded def _expiry_wall_ns(creds): @@ -130,7 +196,7 @@ def get_refreshed_credentials(recorder=NOOP_RECORDER, scopes=None): try: creds.refresh(googleauthrequests.Request()) except Exception: - _CREDENTIALS_CACHE.clear() + _evict_credentials(creds) raise if recorder.enabled: refreshed_attrs = ( @@ -250,6 +316,7 @@ def connect_tcp_bridge(hostname, recorder=NOOP_RECORDER, conn_number=None): """ path = "tcp-over-websocket-bridge/35218cb7-1201-4940-89e8-48d8f03fed96" with recorder.span("proxy.ws_connect", conn=conn_number, host=hostname): + creds = None try: creds = get_refreshed_credentials(recorder=recorder) @@ -280,12 +347,15 @@ def connect_tcp_bridge(hostname, recorder=NOOP_RECORDER, conn_number=None): ping_timeout=60, ) except Exception as exc: + http_status = _http_status_of(exc) + if http_status == 401 and creds is not None: + _evict_credentials(creds) if recorder.enabled: recorder.event( "proxy.ws_connect_failed", conn=conn_number, error_type=type(exc).__name__, - http_status=_http_status_of(exc), + http_status=http_status, ) raise diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index 7e537633..e1a9bbf8 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -59,9 +59,11 @@ MethodNotImplemented, NotFound, PermissionDenied, + ServiceUnavailable, + Unauthorized, ) from google.api_core.future.polling import POLLING_PREDICATE -from google.auth.exceptions import DefaultCredentialsError +from google.auth.exceptions import DefaultCredentialsError, GoogleAuthError from google.cloud import dataproc_v1 from google.cloud.managed_spark_connect.client import ManagedSparkChannelBuilder from google.cloud.managed_spark_connect.client.core import ( @@ -69,7 +71,9 @@ _OutageLog, ) from google.cloud.managed_spark_connect.client.proxy import ( + adc_file_stamp, clear_credentials_cache, + file_stat_stamp, get_default_credentials, ) from google.cloud.managed_spark_connect.client.reattach_patch import ( @@ -345,7 +349,7 @@ def fetch(): _CLIENT_CACHE_LOCK = threading.RLock() -_CLIENT_CACHE: Dict[Tuple[Any, ...], SessionControllerClient] = {} +_CLIENT_CACHE: Dict[Tuple[Any, ...], Tuple[Any, Any]] = {} #: Set to a true value to run the execution progress handler outside a #: notebook / interactive shell. A test hook, deliberately undocumented. @@ -418,32 +422,71 @@ def _get_client_option(client_options: Any, name: str) -> Any: return getattr(client_options, name, None) -def clear_dataproc_caches() -> None: +def _has_uncacheable_client_cert_options( + client_options: Optional[ClientOptions], +) -> bool: + return ( + _get_client_option(client_options, "client_cert_source") is not None + or _get_client_option(client_options, "client_encrypted_cert_source") + is not None + ) + + +def _clear_auth_and_client_caches() -> None: """Clear process-wide cached Application Default Credentials and Dataproc clients.""" clear_credentials_cache() with _CLIENT_CACHE_LOCK: _CLIENT_CACHE.clear() + + +def _is_auth_error(exc: BaseException) -> bool: + """Return True if ``exc`` (or its cause chain) indicates an auth/credential failure.""" + seen = set() + cur: Optional[BaseException] = exc + while cur is not None and id(cur) not in seen: + seen.add(id(cur)) + # Unauthenticated subclasses Unauthorized, so this covers both gRPC and REST 401. + if isinstance(cur, (GoogleAuthError, Unauthorized)): + return True + if isinstance(cur, ServiceUnavailable): + msg = str(cur).lower() + if ( + "getting metadata from plugin failed" in msg + or "reauthentication is needed" in msg + ): + return True + cur = cur.__cause__ or cur.__context__ + return False + + +def _maybe_evict_auth_caches(exc: BaseException) -> None: + """Evict cached credentials and Dataproc clients after an auth failure.""" + if _is_auth_error(exc): + _clear_auth_and_client_caches() + + +def clear_dataproc_caches() -> None: + """Clear process-wide cached Application Default Credentials and Dataproc clients.""" + _clear_auth_and_client_caches() invalidate_s8s_session_active() -def _create_session_controller_client( +def _create_dataproc_client( + client_cls: Any, client_options: Optional[ClientOptions] = None, -) -> SessionControllerClient: - """Create or return a cached Dataproc SessionControllerClient instance.""" - client_cls = dataproc_v1.SessionControllerClient +) -> Any: + """Create or return a cached Dataproc control-plane client instance.""" resolved_transport = _resolve_dataproc_transport() transport_kwargs: Dict[str, Any] = ( {"transport": resolved_transport} if resolved_transport != "grpc" else {} ) - if ( - _get_client_option(client_options, "client_cert_source") is not None - or _get_client_option(client_options, "client_encrypted_cert_source") - is not None - ): + if _has_uncacheable_client_cert_options(client_options): return client_cls(client_options=client_options, **transport_kwargs) scopes = _get_client_option(client_options, "scopes") + credentials_file = _get_client_option(client_options, "credentials_file") + api_key = _get_client_option(client_options, "api_key") cache_key = ( client_cls, resolved_transport, @@ -451,13 +494,14 @@ def _create_session_controller_client( _get_client_option(client_options, "quota_project_id"), _get_client_option(client_options, "universe_domain"), _get_client_option(client_options, "api_audience"), - _get_client_option(client_options, "credentials_file"), - _get_client_option(client_options, "api_key"), + credentials_file, + api_key, tuple(scopes) if scopes is not None else None, os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"), os.environ.get("CLOUDSDK_CONFIG"), os.environ.get("APPDATA"), os.environ.get("GOOGLE_CLOUD_PROJECT"), + os.environ.get("GOOGLE_CLOUD_QUOTA_PROJECT"), os.environ.get("GCLOUD_PROJECT"), os.environ.get("DEVSHELL_PROJECT_ID"), os.environ.get("HOME"), @@ -467,23 +511,47 @@ def _create_session_controller_client( for k in ("credentials_file", "api_key", "scopes", "quota_project_id") ) with _CLIENT_CACHE_LOCK: - client = _CLIENT_CACHE.get(cache_key) - if client is None: - if has_custom_creds: - client = client_cls( - client_options=client_options, **transport_kwargs + entry = _CLIENT_CACHE.get(cache_key) + if has_custom_creds: + if credentials_file: + stamp = ( + os.path.abspath(credentials_file), + file_stat_stamp(credentials_file), ) + elif api_key: + stamp = None else: - creds, _ = get_default_credentials() - client = client_cls( - client_options=client_options, - credentials=creds, - **transport_kwargs, - ) - _CLIENT_CACHE[cache_key] = client + # Options like quota_project_id or scopes still load ADC from disk. + stamp = adc_file_stamp() + if entry is not None and entry[0] == stamp: + return entry[1] + client = client_cls( + client_options=client_options, **transport_kwargs + ) + _CLIENT_CACHE[cache_key] = (stamp, client) + return client + creds, _ = get_default_credentials() + if entry is not None and entry[0] is creds: + return entry[1] + client = client_cls( + client_options=client_options, + credentials=creds, + **transport_kwargs, + ) + _CLIENT_CACHE[cache_key] = (creds, client) return client +def _create_session_controller_client( + client_options: Optional[ClientOptions] = None, +) -> SessionControllerClient: + """Create or return a cached Dataproc SessionControllerClient instance.""" + return _create_dataproc_client( + dataproc_v1.SessionControllerClient, + client_options=client_options, + ) + + def _is_valid_label_value(value: str) -> bool: """ Validates if a string complies with Google Cloud label value format. @@ -1063,32 +1131,27 @@ def progressBarLeave(self, leave: bool = True): @property def session_controller_client(self) -> SessionControllerClient: """Get or create a SessionControllerClient instance.""" - if self._session_controller_client is None: - self._session_controller_client = ( - _create_session_controller_client( - client_options=self._client_options - ) - ) - return self._session_controller_client + if self._session_controller_client is not None: + return self._session_controller_client + client = _create_session_controller_client( + client_options=self._client_options + ) + if _has_uncacheable_client_cert_options(self._client_options): + self._session_controller_client = client + return client @property def session_template_controller_client(self): """Get or create a SessionTemplateControllerClient instance.""" - from google.cloud.dataproc_v1 import ( - SessionTemplateControllerClient, + if self._session_template_controller_client is not None: + return self._session_template_controller_client + client = _create_dataproc_client( + dataproc_v1.SessionTemplateControllerClient, + client_options=self._client_options, ) - - if self._session_template_controller_client is None: - resolved_transport = _resolve_dataproc_transport() - kwargs: Dict[str, Any] = { - "client_options": self._client_options - } - if resolved_transport != "grpc": - kwargs["transport"] = resolved_transport - self._session_template_controller_client = ( - SessionTemplateControllerClient(**kwargs) - ) - return self._session_template_controller_client + if _has_uncacheable_client_cert_options(self._client_options): + self._session_template_controller_client = client + return client def projectId(self, project_id): self._project_id = project_id @@ -1484,6 +1547,7 @@ def create_session_pbar(): "Error while creating Managed Spark Session" ) from e except DefaultCredentialsError as e: + _maybe_evict_auth_caches(e) ManagedSparkSession._active_s8s_session_id = None ManagedSparkSession._active_session_uses_custom_id = False raise ManagedSparkConnectException( @@ -1494,6 +1558,7 @@ def create_session_pbar(): ManagedSparkSession._active_session_uses_custom_id = False raise except Exception as e: + _maybe_evict_auth_caches(e) ManagedSparkSession._active_s8s_session_id = None ManagedSparkSession._active_session_uses_custom_id = False raise RuntimeError( @@ -1678,6 +1743,7 @@ def _poll_for_session_endpoint( except ManagedSparkConnectException: raise except Exception as e: + _maybe_evict_auth_caches(e) logger.warning( f"Error while polling for Spark Connect endpoint: {e}" ) @@ -2079,6 +2145,7 @@ def _get_session_template(self, template_name: str): template_name, project_id=self._project_id, region=self._region, + on_error=_maybe_evict_auth_caches, ) def _check_python_version_compatibility(self, runtime_version): @@ -2153,6 +2220,7 @@ def _resolve_created_session_template_runtime( GetSessionRequest(name=session_name) ) except Exception as e: + _maybe_evict_auth_caches(e) logger.debug( f"Could not inspect created session {session_name}: {e}" ) @@ -2311,6 +2379,7 @@ def _get_session_by_id(self, session_id: str) -> Optional[Session]: ) return None except Exception as e: + _maybe_evict_auth_caches(e) logger.error(f"Error checking session {session_id}: {e}") return None @@ -2325,6 +2394,9 @@ def _delete_session(self, session_name: str): logger.debug(f"Deleted session: {session_name}") except NotFound: logger.debug(f"Session already deleted: {session_name}") + except Exception as e: + _maybe_evict_auth_caches(e) + raise def _wait_for_termination(self, session_name: str, timeout: int = 180): """Wait for a session to finish terminating.""" @@ -2356,6 +2428,9 @@ def _wait_for_termination(self, session_name: str, timeout: int = 180): except NotFound: # Session was deleted return + except Exception as e: + _maybe_evict_auth_caches(e) + raise logger.warning( f"Timeout waiting for session {session_name} to terminate" @@ -3201,6 +3276,9 @@ def terminate_s8s_session( logger.debug( f"{active_s8s_session_id} Managed Spark Session already terminated manually or automatically due to TTL" ) + except Exception as e: + _maybe_evict_auth_caches(e) + raise if state is not None and state == Session.State.FAILED: raise RuntimeError("Managed Spark Session termination failed") @@ -3354,6 +3432,9 @@ def get_active_s8s_session_response( _record_liveness(key, False, _describe_inactive_session(session_name)) logger.debug("%s Managed Spark Session deleted: %s", session_name, e) return None + except Exception as e: + _maybe_evict_auth_caches(e) + raise state = get_session_response.state if state == Session.State.ACTIVE: _record_liveness(key, True) @@ -3393,7 +3474,8 @@ def _dead_session_detail( detail = _describe_inactive_session(session_name) _record_liveness(key, False, detail) return detail - except Exception: + except Exception as e: + _maybe_evict_auth_caches(e) logger.debug( "Could not check Managed Spark Session %s", session_name, diff --git a/tests/unit/test_dataproc.py b/tests/unit/test_dataproc.py index e89e274f..50fbb3c1 100644 --- a/tests/unit/test_dataproc.py +++ b/tests/unit/test_dataproc.py @@ -20,7 +20,15 @@ import pytest from google.api_core.client_options import ClientOptions +from google.api_core.exceptions import ( + NotFound, + PermissionDenied, + ServiceUnavailable, + Unauthenticated, + Unauthorized, +) from google.auth import credentials as google_auth_credentials +from google.auth.exceptions import DefaultCredentialsError, RefreshError from google.cloud.managed_spark_connect import session as session_mod from google.cloud.managed_spark_connect.client import proxy as proxy_mod from google.cloud.managed_spark_connect.instrumentation import ( @@ -505,3 +513,795 @@ def __init__(self, **kwargs): _ = rest_builder.session_template_controller_client assert session_calls[-1]["transport"] == "rest" assert template_calls[-1]["transport"] == "rest" + + +def test_adc_file_changes_invalidate_credentials_and_client_caches( + monkeypatch, tmp_path +): + config_dir = tmp_path / "gcloud" + config_dir.mkdir() + adc_file = config_dir / "application_default_credentials.json" + adc_file.write_text('{"refresh_token": "tok-1"}') + monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False) + monkeypatch.setenv("CLOUDSDK_CONFIG", str(config_dir)) + + loaded_creds = [] + + def fake_default(scopes=None): + creds = _FakeRealCredentials( + valid=True, token=f"t-{len(loaded_creds) + 1}" + ) + loaded_creds.append(creds) + return creds, "proj" + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + self.client_options = client_options + self.credentials = credentials + + monkeypatch.setattr(proxy_mod.googleauth, "default", fake_default) + _set_client_cls(monkeypatch, FakeClient) + + opts = ClientOptions(api_endpoint="us-central1-dataproc.googleapis.com") + c1 = session_mod._create_session_controller_client(client_options=opts) + assert ( + session_mod._create_session_controller_client(client_options=opts) is c1 + ) + assert len(loaded_creds) == 1 + + # Simulate `gcloud auth application-default login` replacing the ADC file. + tmp_adc = config_dir / "adc.tmp" + tmp_adc.write_text('{"refresh_token": "tok-2-reauthed"}') + os.replace(tmp_adc, adc_file) + + c2 = session_mod._create_session_controller_client(client_options=opts) + assert c2 is not c1 + assert c2.credentials is loaded_creds[1] + assert len(loaded_creds) == 2 + + # Unchanged file stays cached. + assert ( + session_mod._create_session_controller_client(client_options=opts) is c2 + ) + assert len(loaded_creds) == 2 + + # Deleting the ADC file (e.g. `gcloud auth application-default revoke`) + # also invalidates both caches. + adc_file.unlink() + c3 = session_mod._create_session_controller_client(client_options=opts) + assert c3 is not c2 + assert c3.credentials is loaded_creds[2] + assert len(loaded_creds) == 3 + + +def test_explicit_google_application_credentials_file_change_invalidates_cache( + monkeypatch, tmp_path +): + cred_file = tmp_path / "sa-key.json" + cred_file.write_text('{"key": "v1"}') + monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", str(cred_file)) + + loaded = [] + + def fake_default(scopes=None): + creds = _FakeRealCredentials(valid=True, token=f"t-{len(loaded) + 1}") + loaded.append(creds) + return creds, "proj" + + monkeypatch.setattr(proxy_mod.googleauth, "default", fake_default) + + c1, _ = proxy_mod.get_default_credentials() + assert proxy_mod.get_default_credentials()[0] is c1 + + tmp_cred = tmp_path / "sa-key.new.json" + tmp_cred.write_text('{"key": "v2-rotated"}') + os.replace(tmp_cred, cred_file) + + c2, _ = proxy_mod.get_default_credentials() + assert c2 is not c1 + assert len(loaded) == 2 + + +def test_custom_credentials_file_change_invalidates_client_cache( + monkeypatch, tmp_path +): + key_file = tmp_path / "custom-key.json" + key_file.write_text('{"key": "v1"}') + + created = [] + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + self.client_options = client_options + self.credentials = credentials + created.append(self) + + _set_client_cls(monkeypatch, FakeClient) + opts = ClientOptions( + api_endpoint="us-central1-dataproc.googleapis.com", + credentials_file=str(key_file), + ) + + c1 = session_mod._create_session_controller_client(client_options=opts) + assert ( + session_mod._create_session_controller_client(client_options=opts) is c1 + ) + assert len(created) == 1 + + tmp_key = tmp_path / "custom-key.new.json" + tmp_key.write_text('{"key": "v2-updated"}') + os.replace(tmp_key, key_file) + + c2 = session_mod._create_session_controller_client(client_options=opts) + assert c2 is not c1 + assert len(created) == 2 + + +def test_client_cache_rebuilds_when_credentials_cache_cleared_or_refresh_fails( + monkeypatch, +): + creds_list = [ + _FakeRealCredentials(valid=False, token=None), + _FakeRealCredentials(valid=True, token="tok-2"), + _FakeRealCredentials(valid=True, token="tok-3"), + ] + creds_iter = iter(creds_list) + + def failing_refresh(_request): + raise RefreshError("Reauthentication is needed") + + creds_list[0].refresh = failing_refresh + + monkeypatch.setattr( + proxy_mod.googleauth, + "default", + lambda scopes=None: (next(creds_iter), "p"), + ) + monkeypatch.setattr(proxy_mod, "googleauthrequests", mock.Mock()) + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + self.credentials = credentials + + _set_client_cls(monkeypatch, FakeClient) + opts = ClientOptions(api_endpoint="us-central1-dataproc.googleapis.com") + + c1 = session_mod._create_session_controller_client(client_options=opts) + assert c1.credentials is creds_list[0] + + # A refresh failure in proxy.get_refreshed_credentials() clears + # _CREDENTIALS_CACHE, which must also force _CLIENT_CACHE to rebuild. + with pytest.raises(RefreshError): + proxy_mod.get_refreshed_credentials() + + c2 = session_mod._create_session_controller_client(client_options=opts) + assert c2 is not c1 + assert c2.credentials is creds_list[1] + + # Direct clear_credentials_cache() also forces _CLIENT_CACHE to rebuild. + proxy_mod.clear_credentials_cache() + c3 = session_mod._create_session_controller_client(client_options=opts) + assert c3 is not c2 + assert c3.credentials is creds_list[2] + + +def test_builder_session_controller_client_tracks_reauth_and_preserves_injection( + monkeypatch, +): + creds_iter = iter( + [ + _FakeRealCredentials(valid=True, token="tok-1"), + _FakeRealCredentials(valid=True, token="tok-2"), + ] + ) + monkeypatch.setattr( + proxy_mod.googleauth, + "default", + lambda scopes=None: (next(creds_iter), "p"), + ) + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + self.credentials = credentials + + _set_client_cls(monkeypatch, FakeClient) + builder = session_mod.ManagedSparkSession.builder.location("us-central1") + + c1 = builder.session_controller_client + assert builder.session_controller_client is c1 + + session_mod.clear_dataproc_caches() + c2 = builder.session_controller_client + assert c2 is not c1 + + # Explicit injection on builder._session_controller_client still wins. + injected = mock.Mock() + builder._session_controller_client = injected + assert builder.session_controller_client is injected + + +def test_is_auth_error_classification(): + assert session_mod._is_auth_error( + RefreshError("Reauthentication is needed") + ) + assert session_mod._is_auth_error(DefaultCredentialsError("missing adc")) + assert session_mod._is_auth_error(Unauthenticated("401")) + assert session_mod._is_auth_error(Unauthorized("401 REST")) + assert session_mod._is_auth_error( + ServiceUnavailable( + "Getting metadata from plugin failed with error: " + "Reauthentication is needed. Please run `gcloud auth application-default login`." + ) + ) + wrapped = RuntimeError("outer") + wrapped.__cause__ = ServiceUnavailable( + "Getting metadata from plugin failed with error: expired" + ) + assert session_mod._is_auth_error(wrapped) + + assert not session_mod._is_auth_error( + ServiceUnavailable("503 Dataproc backend temporarily unavailable") + ) + assert not session_mod._is_auth_error(NotFound("session not found")) + assert not session_mod._is_auth_error(PermissionDenied("403 forbidden")) + assert not session_mod._is_auth_error(RuntimeError("unrelated")) + + +@pytest.mark.parametrize( + "auth_exc", + [ + ServiceUnavailable( + "Getting metadata from plugin failed with error: " + "Reauthentication is needed." + ), + RefreshError("Reauthentication is needed."), + Unauthenticated("Invalid Credentials"), + Unauthorized("Request had invalid authentication credentials."), + ], +) +def test_control_plane_auth_errors_evict_caches_and_recover( + monkeypatch, auth_exc +): + creds_calls = [] + + def fake_default(scopes=None): + creds = _FakeRealCredentials( + valid=True, token=f"tok-{len(creds_calls) + 1}" + ) + creds_calls.append(creds) + return creds, "proj" + + monkeypatch.setattr(proxy_mod.googleauth, "default", fake_default) + + created_clients = [] + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + self.credentials = credentials + self.idx = len(created_clients) + created_clients.append(self) + + def get_session(self, request): + if self.idx == 0: + raise auth_exc + raise NotFound("not found") + + _set_client_cls(monkeypatch, FakeClient) + opts = ClientOptions(api_endpoint="us-central1-dataproc.googleapis.com") + session_name = "projects/p/locations/us-central1/sessions/s1" + + # First call hits auth failure -> evicts both caches. + with pytest.raises(type(auth_exc)): + session_mod.get_active_s8s_session_response(session_name, opts) + assert len(created_clients) == 1 + assert len(creds_calls) == 1 + + # Next call builds a fresh client with freshly loaded credentials. + assert ( + session_mod.get_active_s8s_session_response(session_name, opts) is None + ) + assert len(created_clients) == 2 + assert len(creds_calls) == 2 + assert created_clients[1].credentials is creds_calls[1] + + +def test_builder_get_session_by_id_evicts_caches_on_auth_error(monkeypatch): + creds_calls = [] + + def fake_default(scopes=None): + creds = _FakeRealCredentials( + valid=True, token=f"tok-{len(creds_calls) + 1}" + ) + creds_calls.append(creds) + return creds, "proj" + + monkeypatch.setattr(proxy_mod.googleauth, "default", fake_default) + + created_clients = [] + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + self.credentials = credentials + self.idx = len(created_clients) + created_clients.append(self) + + def get_session(self, request): + if self.idx == 0: + raise ServiceUnavailable( + "Getting metadata from plugin failed with error: " + "Reauthentication is needed." + ) + raise NotFound("gone") + + _set_client_cls(monkeypatch, FakeClient) + + builder = ( + session_mod.ManagedSparkSession.builder.projectId("p") + .location("us-central1") + .sessionId("my-session") + ) + assert builder._get_session_by_id("my-session") is None + assert len(created_clients) == 1 + + # Auth error evicted both caches, so subsequent access reloads creds + client. + assert builder._get_session_by_id("my-session") is None + assert len(created_clients) == 2 + assert len(creds_calls) == 2 + + +def test_non_auth_service_unavailable_keeps_caches_warm(monkeypatch): + fake_creds = _FakeRealCredentials(valid=True, token="tok") + monkeypatch.setattr( + proxy_mod.googleauth, "default", lambda scopes=None: (fake_creds, "p") + ) + + created = [] + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + created.append(self) + + def get_session(self, request): + raise ServiceUnavailable("503 transient backend error") + + _set_client_cls(monkeypatch, FakeClient) + opts = ClientOptions(api_endpoint="us-central1-dataproc.googleapis.com") + session_name = "projects/p/locations/us-central1/sessions/s1" + + with pytest.raises(ServiceUnavailable): + session_mod.get_active_s8s_session_response(session_name, opts) + with pytest.raises(ServiceUnavailable): + session_mod.get_active_s8s_session_response(session_name, opts) + + assert len(created) == 1 + + +def test_connect_tcp_bridge_clears_credentials_cache_on_401(monkeypatch): + creds = _FakeRealCredentials(valid=True, token="stale-token") + monkeypatch.setattr( + proxy_mod.googleauth, "default", lambda scopes=None: (creds, "p") + ) + + class _FakeHttpError(Exception): + + def __init__(self, status_code): + super().__init__(f"HTTP {status_code}") + self.response = mock.Mock(status_code=status_code) + + monkeypatch.setattr( + proxy_mod.websocketclient, + "connect", + mock.Mock(side_effect=_FakeHttpError(503)), + ) + with pytest.raises(_FakeHttpError): + proxy_mod.connect_tcp_bridge("backend.example.com") + assert proxy_mod._CREDENTIALS_CACHE != {} + + monkeypatch.setattr( + proxy_mod.websocketclient, + "connect", + mock.Mock(side_effect=_FakeHttpError(401)), + ) + with pytest.raises(_FakeHttpError): + proxy_mod.connect_tcp_bridge("backend.example.com") + assert proxy_mod._CREDENTIALS_CACHE == {} + + +def test_create_terminate_and_dead_detail_evict_caches_on_auth_error( + monkeypatch, +): + creds_calls = [] + + def fake_default(scopes=None): + creds = _FakeRealCredentials( + valid=True, token=f"tok-{len(creds_calls) + 1}" + ) + creds_calls.append(creds) + return creds, "proj" + + monkeypatch.setattr(proxy_mod.googleauth, "default", fake_default) + auth_err = ServiceUnavailable( + "Getting metadata from plugin failed with error: " + "Reauthentication is needed." + ) + + created = [] + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + self.credentials = credentials + created.append(self) + + def create_session(self, request): + raise auth_err + + def terminate_session(self, request): + raise auth_err + + def get_session(self, request): + raise auth_err + + _set_client_cls(monkeypatch, FakeClient) + opts = ClientOptions(api_endpoint="us-central1-dataproc.googleapis.com") + + # 1. Builder.__create evicts caches on auth error. + builder = ( + session_mod.ManagedSparkSession.builder.projectId("p") + .location("us-central1") + .showProgressBar(False) + ) + with pytest.raises(RuntimeError, match="Error while creating"): + builder.getOrCreate() + assert proxy_mod._CREDENTIALS_CACHE == {} + assert session_mod._CLIENT_CACHE == {} + + # 2. terminate_s8s_session evicts caches on auth error. + with pytest.raises(ServiceUnavailable): + session_mod.terminate_s8s_session("p", "us-central1", "s1", opts) + assert proxy_mod._CREDENTIALS_CACHE == {} + assert session_mod._CLIENT_CACHE == {} + + # 3. _dead_session_detail evicts caches on auth error (use a distinct + # session name because terminate_s8s_session marked s1 as terminated). + assert ( + session_mod._dead_session_detail( + "projects/p/locations/us-central1/sessions/s2", opts + ) + is None + ) + assert proxy_mod._CREDENTIALS_CACHE == {} + assert session_mod._CLIENT_CACHE == {} + assert len(created) == 3 + assert len(creds_calls) == 3 + + +def test_quota_project_client_option_invalidates_when_adc_file_changes( + monkeypatch, tmp_path +): + config_dir = tmp_path / "gcloud" + config_dir.mkdir() + adc_file = config_dir / "application_default_credentials.json" + adc_file.write_text('{"refresh_token": "tok-1"}') + monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False) + monkeypatch.setenv("CLOUDSDK_CONFIG", str(config_dir)) + + created = [] + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + created.append(self) + + _set_client_cls(monkeypatch, FakeClient) + opts = ClientOptions( + api_endpoint="us-central1-dataproc.googleapis.com", + quota_project_id="my-quota-proj", + ) + + c1 = session_mod._create_session_controller_client(client_options=opts) + assert ( + session_mod._create_session_controller_client(client_options=opts) is c1 + ) + + tmp_adc = config_dir / "adc.tmp" + tmp_adc.write_text('{"refresh_token": "tok-2-reauthed"}') + os.replace(tmp_adc, adc_file) + + c2 = session_mod._create_session_controller_client(client_options=opts) + assert c2 is not c1 + assert len(created) == 2 + + +def test_builder_memoizes_uncacheable_client_cert_source(monkeypatch): + created = [] + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + created.append(self) + + _set_client_cls(monkeypatch, FakeClient) + opts = ClientOptions( + api_endpoint="us-central1-dataproc.googleapis.com", + client_cert_source=lambda: (b"cert", b"key"), + ) + builder = session_mod.ManagedSparkSession.builder + builder._client_options = opts + c1 = builder.session_controller_client + c2 = builder.session_controller_client + assert c1 is c2 + assert len(created) == 1 + + +def test_quota_project_env_var_invalidates_credentials_and_client_caches( + monkeypatch, +): + loaded = [] + + def fake_default(scopes=None): + creds = _FakeRealCredentials(valid=True, token=f"tok-{len(loaded) + 1}") + loaded.append(creds) + return creds, "proj" + + monkeypatch.setattr(proxy_mod.googleauth, "default", fake_default) + + created = [] + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + self.credentials = credentials + created.append(self) + + _set_client_cls(monkeypatch, FakeClient) + opts = ClientOptions(api_endpoint="us-central1-dataproc.googleapis.com") + + monkeypatch.setenv("GOOGLE_CLOUD_QUOTA_PROJECT", "quota-proj-1") + c1 = session_mod._create_session_controller_client(client_options=opts) + assert ( + session_mod._create_session_controller_client(client_options=opts) is c1 + ) + + monkeypatch.setenv("GOOGLE_CLOUD_QUOTA_PROJECT", "quota-proj-2") + c2 = session_mod._create_session_controller_client(client_options=opts) + assert c2 is not c1 + assert c2.credentials is not c1.credentials + assert len(loaded) == 2 + assert len(created) == 2 + + +def test_custom_credentials_file_relative_path_and_empty_string_invalidation( + monkeypatch, tmp_path +): + dir_a = tmp_path / "a" + dir_b = tmp_path / "b" + dir_a.mkdir() + dir_b.mkdir() + (dir_a / "key.json").write_text('{"key": "a"}') + (dir_b / "key.json").write_text('{"key": "b"}') + + created = [] + + class FakeClient: + + def __init__(self, client_options=None, credentials=None): + created.append(self) + + _set_client_cls(monkeypatch, FakeClient) + rel_opts = ClientOptions( + api_endpoint="us-central1-dataproc.googleapis.com", + credentials_file="key.json", + ) + + monkeypatch.chdir(dir_a) + c1 = session_mod._create_session_controller_client(client_options=rel_opts) + monkeypatch.chdir(dir_b) + c2 = session_mod._create_session_controller_client(client_options=rel_opts) + assert c2 is not c1 + + # Empty string credentials_file="" falls back to ADC in Dataproc clients, + # so it must track default ADC file changes rather than caching forever. + config_dir = tmp_path / "gcloud" + config_dir.mkdir() + adc_file = config_dir / "application_default_credentials.json" + adc_file.write_text('{"refresh_token": "tok-1"}') + monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False) + monkeypatch.setenv("CLOUDSDK_CONFIG", str(config_dir)) + + empty_opts = ClientOptions( + api_endpoint="us-central1-dataproc.googleapis.com", + credentials_file="", + ) + c3 = session_mod._create_session_controller_client( + client_options=empty_opts + ) + tmp_adc = config_dir / "adc.tmp" + tmp_adc.write_text('{"refresh_token": "tok-2-updated"}') + os.replace(tmp_adc, adc_file) + c4 = session_mod._create_session_controller_client( + client_options=empty_opts + ) + assert c4 is not c3 + + +def test_connect_tcp_bridge_401_does_not_evict_concurrently_rotated_credentials( + monkeypatch, +): + old_creds = _FakeRealCredentials(valid=True, token="stale-token") + fresh_creds = _FakeRealCredentials(valid=True, token="fresh-token") + creds_iter = iter([old_creds, fresh_creds]) + monkeypatch.setattr( + proxy_mod.googleauth, + "default", + lambda scopes=None: (next(creds_iter), "p"), + ) + + class _FakeHttpError(Exception): + + def __init__(self, status_code): + super().__init__(f"HTTP {status_code}") + self.response = mock.Mock(status_code=status_code) + + def connect_with_concurrent_rotation(*args, **kwargs): + # Simulate another thread clearing and reloading fresher credentials + # while this handshake was in flight with old_creds. + proxy_mod.clear_credentials_cache() + loaded_fresh, _ = proxy_mod.get_default_credentials() + assert loaded_fresh is fresh_creds + raise _FakeHttpError(401) + + monkeypatch.setattr( + proxy_mod.websocketclient, + "connect", + connect_with_concurrent_rotation, + ) + with pytest.raises(_FakeHttpError): + proxy_mod.connect_tcp_bridge("backend.example.com") + + # The stale 401 must not wipe out the concurrently loaded fresh credentials. + cached_creds, _ = proxy_mod.get_default_credentials() + assert cached_creds is fresh_creds + + +def test_builder_session_template_controller_client_tracks_reauth_and_preserves_injection( + monkeypatch, tmp_path +): + config_dir = tmp_path / "gcloud" + config_dir.mkdir() + adc_file = config_dir / "application_default_credentials.json" + adc_file.write_text('{"refresh_token": "tok-1"}') + monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False) + monkeypatch.setenv("CLOUDSDK_CONFIG", str(config_dir)) + + creds_list = [ + _FakeRealCredentials(valid=True, token="tok-1"), + _FakeRealCredentials(valid=True, token="tok-2"), + _FakeRealCredentials(valid=True, token="tok-3"), + ] + creds_iter = iter(creds_list) + monkeypatch.setattr( + proxy_mod.googleauth, + "default", + lambda scopes=None: (next(creds_iter), "p"), + ) + + class FakeSessionClient: + + def __init__(self, client_options=None, credentials=None, **kwargs): + self.credentials = credentials + + class FakeTemplateClient: + + def __init__(self, client_options=None, credentials=None, **kwargs): + self.credentials = credentials + + _set_client_cls(monkeypatch, FakeSessionClient) + monkeypatch.setattr( + session_mod.dataproc_v1, + "SessionTemplateControllerClient", + FakeTemplateClient, + ) + builder = session_mod.ManagedSparkSession.builder.location("us-central1") + + sc1 = builder.session_controller_client + tc1 = builder.session_template_controller_client + assert builder.session_template_controller_client is tc1 + assert tc1.credentials is sc1.credentials is creds_list[0] + + # Rewriting ADC on disk invalidates the template client on the same Builder. + tmp_adc = config_dir / "adc.tmp" + tmp_adc.write_text('{"refresh_token": "tok-2-reauthed"}') + os.replace(tmp_adc, adc_file) + tc2 = builder.session_template_controller_client + assert tc2 is not tc1 + assert tc2.credentials is creds_list[1] + + # clear_dataproc_caches() also invalidates the template client. + session_mod.clear_dataproc_caches() + tc3 = builder.session_template_controller_client + assert tc3 is not tc2 + assert tc3.credentials is creds_list[2] + + # Explicit injection on builder._session_template_controller_client still wins. + injected = mock.Mock() + builder._session_template_controller_client = injected + assert builder.session_template_controller_client is injected + + # Uncacheable client_cert_source still memoizes on the Builder. + cert_created = [] + + class RecordingTemplateClient: + + def __init__(self, client_options=None, credentials=None, **kwargs): + cert_created.append(self) + + monkeypatch.setattr( + session_mod.dataproc_v1, + "SessionTemplateControllerClient", + RecordingTemplateClient, + ) + cert_builder = session_mod.ManagedSparkSession.builder + cert_builder._client_options = ClientOptions( + api_endpoint="us-central1-dataproc.googleapis.com", + client_cert_source=lambda: (b"cert", b"key"), + ) + assert ( + cert_builder.session_template_controller_client + is cert_builder.session_template_controller_client + ) + assert len(cert_created) == 1 + + +def test_builder_get_session_template_evicts_caches_on_auth_error(monkeypatch): + creds_calls = [] + + def fake_default(scopes=None): + creds = _FakeRealCredentials( + valid=True, token=f"tok-{len(creds_calls) + 1}" + ) + creds_calls.append(creds) + return creds, "proj" + + monkeypatch.setattr(proxy_mod.googleauth, "default", fake_default) + + sentinel_template = mock.Mock(name="session_template") + created_clients = [] + + class FakeTemplateClient: + + def __init__(self, client_options=None, credentials=None, **kwargs): + self.credentials = credentials + self.idx = len(created_clients) + created_clients.append(self) + + def get_session_template(self, request): + if self.idx == 0: + raise Unauthorized("401 expired") + return sentinel_template + + monkeypatch.setattr( + session_mod.dataproc_v1, + "SessionTemplateControllerClient", + FakeTemplateClient, + ) + builder = session_mod.ManagedSparkSession.builder.projectId("p").location( + "us-central1" + ) + + assert builder._get_session_template("my-tpl") is None + assert proxy_mod._CREDENTIALS_CACHE == {} + assert session_mod._CLIENT_CACHE == {} + + # Subsequent call on the same Builder reloads credentials + template client. + assert builder._get_session_template("my-tpl") is sentinel_template + assert len(created_clients) == 2 + assert len(creds_calls) == 2 + assert created_clients[1].credentials is creds_calls[1]