| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import TYPE_CHECKING, Any, cast |
| 4 |
from typing_extensions import ClassVar, override |
| 5 |
|
| 6 |
from ._common import MissingDependencyError |
| 7 |
from ..._utils import LazyProxy |
| 8 |
|
| 9 |
if TYPE_CHECKING: |
| 10 |
import google.auth # type: ignore |
| 11 |
from google.auth.credentials import Credentials as GoogleCredentials # type: ignore |
| 12 |
|
| 13 |
google_auth = google.auth |
| 14 |
|
| 15 |
# pyright: reportMissingTypeStubs=false, reportUnknownVariableType=false, reportUnknownMemberType=false, reportUnknownArgumentType=false |
| 16 |
# google libraries don't ship type stubs. |
| 17 |
|
| 18 |
CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform" |
| 19 |
|
| 20 |
|
| 21 |
class GoogleAuthProxy(LazyProxy[Any]): |
| 22 |
should_cache: ClassVar[bool] = True |
| 23 |
|
| 24 |
@override |
| 25 |
def __load__(self) -> Any: |
| 26 |
try: |
| 27 |
import google.auth # type: ignore |
| 28 |
except ImportError as err: |
| 29 |
raise MissingDependencyError(extra="vertex", library="google-auth") from err |
| 30 |
|
| 31 |
return google.auth |
| 32 |
|
| 33 |
|
| 34 |
if not TYPE_CHECKING: |
| 35 |
google_auth = GoogleAuthProxy() |
| 36 |
|
| 37 |
|
| 38 |
def _request(*, extra: str = "vertex") -> Any: |
| 39 |
try: |
| 40 |
from google.auth.transport.requests import Request # type: ignore[import-untyped] |
| 41 |
except ImportError as err: |
| 42 |
raise MissingDependencyError(extra=extra, library="google-auth") from err |
| 43 |
return Request() |
| 44 |
|
| 45 |
|
| 46 |
def load_default_credentials(*, extra: str = "vertex") -> tuple[GoogleCredentials, str | None]: |
| 47 |
"""Load Application Default Credentials with the `cloud-platform` scope and |
| 48 |
mint an initial access token. |
| 49 |
|
| 50 |
Returns the credentials object and the project they resolve to (`None` for |
| 51 |
plain user ADC). Blocking — async callers wrap with `anthropic._utils.asyncify`. |
| 52 |
|
| 53 |
`extra` names the pip extra that the install hint in `MissingDependencyError` |
| 54 |
points at when `google-auth` isn't installed; callers pass the extra for their client. |
| 55 |
""" |
| 56 |
try: |
| 57 |
import google.auth # type: ignore |
| 58 |
except ImportError as err: |
| 59 |
raise MissingDependencyError(extra=extra, library="google-auth") from err |
| 60 |
|
| 61 |
credentials, project = google.auth.default(scopes=[CLOUD_PLATFORM_SCOPE]) |
| 62 |
cast(Any, credentials).refresh(_request(extra=extra)) |
| 63 |
return cast("GoogleCredentials", credentials), project |
| 64 |
|
| 65 |
|
| 66 |
def refresh_credentials(credentials: GoogleCredentials, *, extra: str = "vertex") -> None: |
| 67 |
"""Refresh `credentials` in place via `google.auth.transport.requests`. |
| 68 |
|
| 69 |
Blocking — async callers wrap with `anthropic._utils.asyncify`. |
| 70 |
""" |
| 71 |
cast(Any, credentials).refresh(_request(extra=extra)) |