diff --git a/packages/genkit/pyproject.toml b/packages/genkit/pyproject.toml index 5437ff79..fffa3dab 100644 --- a/packages/genkit/pyproject.toml +++ b/packages/genkit/pyproject.toml @@ -122,8 +122,9 @@ DEP002 = [ "genkit-vertexai", ] # Standard library on Python 3.14+; imported behind a version check. -DEP001 = ["annotationlib"] -DEP003 = ["pydantic_core"] +# google-auth is optional and supplied by plugins' [google-cloud] extras (DEP001 bare, DEP003 in workspace). +DEP001 = ["annotationlib", "google"] +DEP003 = ["pydantic_core", "google"] [tool.hatch.build.targets.wheel] packages = ["src/genkit"] diff --git a/packages/genkit/src/genkit/_core/_google_cloud.py b/packages/genkit/src/genkit/_core/_google_cloud.py new file mode 100644 index 00000000..27a6f151 --- /dev/null +++ b/packages/genkit/src/genkit/_core/_google_cloud.py @@ -0,0 +1,193 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Shared Google Cloud backend configuration and ADC helpers for Genkit plugins. + +Plugins such as ``OpenAICompatible(backend=GoogleCloud(...))`` and +``Anthropic(backend=GoogleCloud(...))`` share one :class:`GoogleCloud` config +object and one ADC loading path, while keeping ``google-auth`` as an optional +dependency installed via each plugin's ``[google-cloud]`` extra. +""" + +import asyncio +import os +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +from genkit._core._error import GenkitError + +_CLOUD_PLATFORM_SCOPES: tuple[str, ...] = ('https://www.googleapis.com/auth/cloud-platform',) +_LOGIN_FIX = ( + 'run `gcloud auth application-default login` on your machine, ' + 'or give the service account roles/aiplatform.user when running on Google Cloud' +) + + +@dataclass(frozen=True, kw_only=True) +class GoogleCloud: + """Route a Genkit model plugin through Google Cloud using application default credentials. + + Pass a ``GoogleCloud(...)`` instance as ``backend=`` to supported plugins + such as ``OpenAICompatible(backend=GoogleCloud(...))`` or + ``Anthropic(backend=GoogleCloud(...))``. Plugins re-export this class so + one instance can be shared across multiple plugins in the same app without + import collisions. Requests authenticate with application default + credentials and bill the Google Cloud project, so no provider API key is + needed. + + Example: + ```python + from genkit import Genkit + from genkit_openai import GoogleCloud, OpenAICompatible + + gcp = GoogleCloud(project='bistro-prod') + garden = OpenAICompatible(backend=gcp) + ai = Genkit(plugins=[garden]) + ``` + + Attributes: + project: Google Cloud project ID. Defaults to ``GCLOUD_PROJECT``, then + ``GOOGLE_CLOUD_PROJECT``, then the credentials' project. + location: Google Cloud location (for example ``'us-central1'`` or + ``'global'``). Defaults to ``GOOGLE_CLOUD_LOCATION``, then each + plugin's own default location. + """ + + project: str | None = None + location: str | None = None + + +def resolve_google_cloud_project(config: GoogleCloud) -> str | None: + """Resolve the project from ``config`` or environment variables; ``None`` means fall back to ADC.""" + return config.project or os.environ.get('GCLOUD_PROJECT') or os.environ.get('GOOGLE_CLOUD_PROJECT') or None + + +def resolve_google_cloud_location(config: GoogleCloud, *, default: str) -> str: + """Resolve the location from ``config``, ``GOOGLE_CLOUD_LOCATION``, or ``default``.""" + return config.location or os.environ.get('GOOGLE_CLOUD_LOCATION') or default + + +def require_google_auth(*, caller: str, extra: str) -> None: + """Fail at setup, on the user's line, when ``google-auth`` isn't installed. + + Args: + caller: Plugin constructor expression shown in the error, e.g. + ``'OpenAICompatible(backend=GoogleCloud())'``. + extra: Package extra install spec, e.g. ``'genkit-openai[google-cloud]'``. + + Raises: + ImportError: ``google-auth`` isn't installed. + """ + # Optional dependency: supplied by each plugin's [google-cloud] extra. + try: + import google.auth # noqa: F401, PLC0415 + except ModuleNotFoundError as e: + raise ImportError(f"{caller} needs the google-cloud extra: uv add '{extra}'") from e + + +def _auth_errors() -> tuple[type[Exception], type[Exception]]: + # Optional dependency, checked by require_google_auth at setup. + from google.auth.exceptions import DefaultCredentialsError, RefreshError # noqa: PLC0415 + + return DefaultCredentialsError, RefreshError + + +def _missing_credentials(caller: str, e: Exception) -> GenkitError: + return GenkitError( + status='FAILED_PRECONDITION', + message=f'{caller} found no Google Cloud credentials: {_LOGIN_FIX}', + cause=e, + ) + + +def _stale_credentials(caller: str, e: Exception) -> GenkitError: + return GenkitError( + status='FAILED_PRECONDITION', + message=f'{caller} could not refresh Google Cloud credentials: {_LOGIN_FIX}', + cause=e, + ) + + +def load_google_adc( + *, + caller: str, + scopes: Sequence[str] = _CLOUD_PLATFORM_SCOPES, +) -> tuple[Any, str | None]: # noqa: ANN401 - google.auth credentials are untyped + """Load and refresh application default credentials, returning ``(credentials, project)``. + + Blocking: may contact the metadata server, so callers in async paths should + run it via ``asyncio.to_thread``. Refreshing here ensures a missing or stale + login fails on the first call with an actionable ``FAILED_PRECONDITION`` + error instead of surfacing later as an unmapped ``google.auth`` error. + + Args: + caller: Plugin constructor expression shown in error messages. + scopes: OAuth scopes to request (defaults to ``cloud-platform``). + + Raises: + GenkitError: ``FAILED_PRECONDITION`` when there are no credentials, or + they need a fresh login. + """ + # Optional dependency, checked by require_google_auth at setup. + import google.auth # noqa: PLC0415 + from google.auth.transport.requests import Request # noqa: PLC0415 + + default_error, refresh_error = _auth_errors() + try: + credentials, project = google.auth.default(scopes=list(scopes)) + except default_error as e: + raise _missing_credentials(caller, e) from e + try: + credentials.refresh(Request()) + except refresh_error as e: + raise _stale_credentials(caller, e) from e + return credentials, project + + +class GoogleAdcToken: + """Async bearer token callable backed by Google ADC, refreshed in a thread when expired. + + Useful for SDK clients (such as ``AsyncOpenAI(api_key=...)``) that accept + an async callable returning the current bearer token before each request. + """ + + def __init__( + self, + credentials: Any, # noqa: ANN401 - google.auth credentials are untyped + *, + caller: str, + ) -> None: + """Hold credentials already refreshed by :func:`load_google_adc`.""" + self._credentials = credentials + self._caller = caller + + async def __call__(self) -> str: + """Return a valid bearer token, refreshing in a thread if expired. + + Raises: + GenkitError: ``FAILED_PRECONDITION`` when the refresh is rejected. + """ + if not self._credentials.valid: + # Optional dependency, checked by require_google_auth at setup. + from google.auth.transport.requests import Request # noqa: PLC0415 + + _, refresh_error = _auth_errors() + try: + await asyncio.to_thread(self._credentials.refresh, Request()) + except refresh_error as e: + raise _stale_credentials(self._caller, e) from e + return self._credentials.token diff --git a/packages/genkit/src/genkit/plugin_api/__init__.py b/packages/genkit/src/genkit/plugin_api/__init__.py index 12b677ce..a0d3ad73 100644 --- a/packages/genkit/src/genkit/plugin_api/__init__.py +++ b/packages/genkit/src/genkit/plugin_api/__init__.py @@ -25,6 +25,14 @@ from genkit._core._dap import DynamicActionProvider from genkit._core._environment import is_dev_environment from genkit._core._error import StatusName, provider_error +from genkit._core._google_cloud import ( + GoogleAdcToken, + GoogleCloud, + load_google_adc, + require_google_auth, + resolve_google_cloud_location, + resolve_google_cloud_project, +) from genkit._core._loop_cache import loop_local_client from genkit._core._plugin import Plugin from genkit._core._schema import to_json_schema @@ -43,6 +51,13 @@ 'StrEnum', # Provider failures 'provider_error', + # Google Cloud backend helpers + 'GoogleCloud', + 'GoogleAdcToken', + 'load_google_adc', + 'require_google_auth', + 'resolve_google_cloud_location', + 'resolve_google_cloud_project', # HTTP / version stamping 'GENKIT_USER_AGENT', # Loop-local caching diff --git a/packages/genkit/tests/genkit/core/google_cloud_test.py b/packages/genkit/tests/genkit/core/google_cloud_test.py new file mode 100644 index 00000000..8adc50d5 --- /dev/null +++ b/packages/genkit/tests/genkit/core/google_cloud_test.py @@ -0,0 +1,224 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Tests for shared GoogleCloud config and ADC helpers in genkit core.""" + +import builtins +import sys +import types +from dataclasses import FrozenInstanceError +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest + +import genkit +import genkit.plugin_api +from genkit import GenkitError +from genkit.plugin_api import ( + GoogleAdcToken, + GoogleCloud, + load_google_adc, + require_google_auth, + resolve_google_cloud_location, + resolve_google_cloud_project, +) + +_ENV = ('GCLOUD_PROJECT', 'GOOGLE_CLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION') + + +@pytest.fixture(autouse=True) +def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + for name in _ENV: + monkeypatch.delenv(name, raising=False) + + +class _FakeDefaultCredentialsError(Exception): + pass + + +class _FakeRefreshError(Exception): + pass + + +@pytest.fixture +def fake_google_auth(monkeypatch: pytest.MonkeyPatch) -> MagicMock: + """Install a lightweight fake google.auth hierarchy so tests don't depend on google-auth.""" + google_mod = types.ModuleType('google') + auth_mod = types.ModuleType('google.auth') + exceptions_mod = types.ModuleType('google.auth.exceptions') + transport_mod = types.ModuleType('google.auth.transport') + requests_mod = types.ModuleType('google.auth.transport.requests') + + default_mock = MagicMock(name='google.auth.default') + auth_mod.default = default_mock # type: ignore[attr-defined] + exceptions_mod.DefaultCredentialsError = _FakeDefaultCredentialsError # type: ignore[attr-defined] + exceptions_mod.RefreshError = _FakeRefreshError # type: ignore[attr-defined] + requests_mod.Request = MagicMock(name='google.auth.transport.requests.Request') # type: ignore[attr-defined] + + google_mod.auth = auth_mod # type: ignore[attr-defined] + auth_mod.exceptions = exceptions_mod # type: ignore[attr-defined] + auth_mod.transport = transport_mod # type: ignore[attr-defined] + transport_mod.requests = requests_mod # type: ignore[attr-defined] + + for mod_name, mod in [ + ('google', google_mod), + ('google.auth', auth_mod), + ('google.auth.exceptions', exceptions_mod), + ('google.auth.transport', transport_mod), + ('google.auth.transport.requests', requests_mod), + ]: + monkeypatch.setitem(sys.modules, mod_name, mod) + return default_mock + + +def test_google_cloud_export_boundary() -> None: + """GoogleCloud and the ADC helpers live in genkit.plugin_api, not top-level genkit.""" + for name in ( + 'GoogleCloud', + 'GoogleAdcToken', + 'load_google_adc', + 'require_google_auth', + 'resolve_google_cloud_location', + 'resolve_google_cloud_project', + ): + assert name in genkit.plugin_api.__all__ + assert name not in genkit.__all__ + assert not hasattr(genkit, name) + + +def test_google_cloud_is_frozen_and_keyword_only() -> None: + """GoogleCloud rejects positional args and mutation.""" + cfg = GoogleCloud(project='bistro-prod', location='us-central1') + + assert cfg.project == 'bistro-prod' + assert cfg.location == 'us-central1' + with pytest.raises(FrozenInstanceError): + cfg.project = 'other' # type: ignore[misc] + with pytest.raises(TypeError): + GoogleCloud('bistro-prod') # type: ignore[misc] + + +def test_resolve_google_cloud_project_precedence(monkeypatch: pytest.MonkeyPatch) -> None: + """project= wins over GCLOUD_PROJECT, which wins over GOOGLE_CLOUD_PROJECT, else None.""" + assert resolve_google_cloud_project(GoogleCloud()) is None + + monkeypatch.setenv('GOOGLE_CLOUD_PROJECT', 'from-google-cloud') + assert resolve_google_cloud_project(GoogleCloud()) == 'from-google-cloud' + + monkeypatch.setenv('GCLOUD_PROJECT', 'from-gcloud') + assert resolve_google_cloud_project(GoogleCloud()) == 'from-gcloud' + + assert resolve_google_cloud_project(GoogleCloud(project='explicit')) == 'explicit' + + +def test_resolve_google_cloud_location_precedence(monkeypatch: pytest.MonkeyPatch) -> None: + """location= wins over GOOGLE_CLOUD_LOCATION, which wins over the plugin's default.""" + assert resolve_google_cloud_location(GoogleCloud(), default='us-central1') == 'us-central1' + assert resolve_google_cloud_location(GoogleCloud(), default='global') == 'global' + + monkeypatch.setenv('GOOGLE_CLOUD_LOCATION', 'europe-west4') + assert resolve_google_cloud_location(GoogleCloud(), default='us-central1') == 'europe-west4' + + assert resolve_google_cloud_location(GoogleCloud(location='us-east5'), default='us-central1') == 'us-east5' + + +def test_require_google_auth_names_caller_and_extra() -> None: + """Missing google-auth raises ImportError naming the plugin caller and uv add command.""" + real_import = builtins.__import__ + + def _no_google_auth(name: str, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + if name == 'google.auth' or name.startswith('google.auth.'): + raise ModuleNotFoundError(name=name) + return real_import(name, *args, **kwargs) + + with ( + patch('builtins.__import__', _no_google_auth), + pytest.raises( + ImportError, + match=( + r'DemoPlugin\(backend=GoogleCloud\(\)\) needs the google-cloud extra: ' + r"uv add 'genkit-demo\[google-cloud\]'" + ), + ), + ): + require_google_auth(caller='DemoPlugin(backend=GoogleCloud())', extra='genkit-demo[google-cloud]') + + +def test_load_google_adc_refreshes_and_returns_project(fake_google_auth: MagicMock) -> None: + """load_google_adc requests cloud-platform scope and refreshes immediately.""" + credentials = MagicMock(name='user-credentials') + fake_google_auth.return_value = (credentials, 'gcloud-project') + + assert load_google_adc(caller='DemoPlugin(backend=GoogleCloud())') == (credentials, 'gcloud-project') + assert fake_google_auth.call_args.kwargs['scopes'] == ['https://www.googleapis.com/auth/cloud-platform'] + credentials.refresh.assert_called_once() + + +@pytest.mark.parametrize('stale', [False, True], ids=['no-adc', 'stale-login']) +def test_load_google_adc_failures_map_to_failed_precondition(fake_google_auth: MagicMock, stale: bool) -> None: + """Missing or stale credentials raise FAILED_PRECONDITION naming caller and the gcloud fix.""" + credentials = MagicMock(name='user-credentials') + if stale: + cause: Exception = _FakeRefreshError('Reauthentication is needed.') + credentials.refresh.side_effect = cause + fake_google_auth.return_value = (credentials, None) + else: + cause = _FakeDefaultCredentialsError('not found') + fake_google_auth.side_effect = cause + + with pytest.raises(GenkitError) as exc_info: + load_google_adc(caller='DemoPlugin(backend=GoogleCloud())') + + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'DemoPlugin(backend=GoogleCloud())' in exc_info.value.message + assert 'gcloud auth application-default login' in exc_info.value.message + assert exc_info.value.__cause__ is cause + + +@pytest.mark.asyncio +async def test_google_adc_token_refreshes_only_when_expired(fake_google_auth: MagicMock) -> None: + """GoogleAdcToken refreshes expired credentials and reuses valid ones.""" + del fake_google_auth + credentials = MagicMock(name='adc-credentials') + credentials.valid = False + credentials.token = 'fresh' + token = GoogleAdcToken(credentials, caller='DemoPlugin(backend=GoogleCloud())') + + assert await token() == 'fresh' + credentials.refresh.assert_called_once() + + credentials.valid = True + assert await token() == 'fresh' + credentials.refresh.assert_called_once() + + +@pytest.mark.asyncio +async def test_google_adc_token_refresh_failure_maps_to_failed_precondition(fake_google_auth: MagicMock) -> None: + """A rejected mid-run refresh raises FAILED_PRECONDITION naming caller and the gcloud fix.""" + del fake_google_auth + cause = _FakeRefreshError('Reauthentication is needed.') + credentials = MagicMock(name='adc-credentials') + credentials.valid = False + credentials.refresh.side_effect = cause + + with pytest.raises(GenkitError) as exc_info: + await GoogleAdcToken(credentials, caller='DemoPlugin(backend=GoogleCloud())')() + + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'DemoPlugin(backend=GoogleCloud())' in exc_info.value.message + assert 'gcloud auth application-default login' in exc_info.value.message + assert exc_info.value.__cause__ is cause