|
| 1 | +# Copyright 2026 Cloudsmith Ltd |
| 2 | +"""Google Cloud OIDC detector. |
| 3 | +
|
| 4 | +Discovers the ambient Google identity via google-auth's Application Default |
| 5 | +Credentials chain and mints an OIDC ID token for Cloudsmith. |
| 6 | +
|
| 7 | +Requires google-auth (optional dependency): pip install cloudsmith-cli[gcp] |
| 8 | +
|
| 9 | +References: |
| 10 | + https://docs.cloud.google.com/iam/docs/authenticate-with-auth-libraries#authenticate-standard |
| 11 | + https://googleapis.dev/python/google-auth/latest/index.html |
| 12 | + https://googleapis.dev/python/google-auth/latest/user-guide.html |
| 13 | + https://github.com/googleapis/google-cloud-python/tree/main/packages/google-auth |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import logging |
| 19 | + |
| 20 | +from .base import DEFAULT_AUDIENCE, EnvironmentDetector |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | +METADATA_IDENTITY_PATH = "instance/service-accounts/default/identity" |
| 25 | + |
| 26 | + |
| 27 | +class GCPDetector(EnvironmentDetector): |
| 28 | + """Detects Google Cloud environments and obtains an OIDC ID token.""" |
| 29 | + |
| 30 | + name = "Google Cloud" |
| 31 | + |
| 32 | + def __init__(self, context): |
| 33 | + super().__init__(context) |
| 34 | + self._credentials = None |
| 35 | + |
| 36 | + def detect(self) -> bool: |
| 37 | + try: |
| 38 | + import google.auth |
| 39 | + from google.auth import exceptions |
| 40 | + except ImportError: |
| 41 | + logger.debug("GCPDetector: google-auth not installed, skipping") |
| 42 | + return False |
| 43 | + |
| 44 | + try: |
| 45 | + self._credentials, _ = google.auth.default() |
| 46 | + return True |
| 47 | + except exceptions.DefaultCredentialsError: |
| 48 | + return self._on_gce() |
| 49 | + except exceptions.GoogleAuthError: |
| 50 | + logger.debug("GCPDetector: error during detection", exc_info=True) |
| 51 | + return False |
| 52 | + |
| 53 | + def get_token(self) -> str: |
| 54 | + audience = self.context.oidc_audience or DEFAULT_AUDIENCE |
| 55 | + |
| 56 | + import google.auth # pylint: disable=import-error |
| 57 | + from google.auth import ( # pylint: disable=import-error |
| 58 | + compute_engine, |
| 59 | + exceptions, |
| 60 | + ) |
| 61 | + from google.auth.transport.requests import ( # pylint: disable=import-error |
| 62 | + Request, |
| 63 | + ) |
| 64 | + from google.oauth2 import ( # pylint: disable=import-error |
| 65 | + credentials as user_creds, |
| 66 | + ) |
| 67 | + |
| 68 | + request = Request() |
| 69 | + credentials = self._credentials |
| 70 | + if credentials is None: |
| 71 | + try: |
| 72 | + credentials, _ = google.auth.default() |
| 73 | + except exceptions.DefaultCredentialsError: |
| 74 | + credentials = None |
| 75 | + |
| 76 | + if credentials is None: |
| 77 | + token = self._token_from_metadata(audience, request) |
| 78 | + elif isinstance(credentials, compute_engine.Credentials): |
| 79 | + token = self._token_from_metadata(audience, request) |
| 80 | + if not token: |
| 81 | + token = self._token_from_compute_id_token_credentials(audience, request) |
| 82 | + elif isinstance(credentials, user_creds.Credentials): |
| 83 | + if self.context.oidc_audience: |
| 84 | + logger.debug( |
| 85 | + "GCPDetector: user credentials cannot mint a token for a " |
| 86 | + "custom audience; the configured oidc_audience is ignored" |
| 87 | + ) |
| 88 | + token = self._token_from_user_credentials(credentials, request) |
| 89 | + else: |
| 90 | + token = self._token_from_id_token_credentials(audience, request) |
| 91 | + |
| 92 | + if not token: |
| 93 | + raise ValueError( |
| 94 | + "Google Cloud detector resolved Google credentials but could " |
| 95 | + "not mint an OIDC ID token. Set CLOUDSMITH_OIDC_TOKEN to " |
| 96 | + "provide a token directly." |
| 97 | + ) |
| 98 | + return token |
| 99 | + |
| 100 | + def _on_gce(self) -> bool: |
| 101 | + from google.auth import exceptions # pylint: disable=import-error |
| 102 | + from google.auth.compute_engine import _metadata # pylint: disable=import-error |
| 103 | + from google.auth.transport.requests import ( # pylint: disable=import-error |
| 104 | + Request, |
| 105 | + ) |
| 106 | + |
| 107 | + try: |
| 108 | + return bool(_metadata.is_on_gce(Request())) |
| 109 | + except exceptions.GoogleAuthError: |
| 110 | + return False |
| 111 | + |
| 112 | + def _token_from_metadata(self, audience: str, request) -> str | None: |
| 113 | + from google.auth import exceptions # pylint: disable=import-error |
| 114 | + from google.auth.compute_engine import _metadata # pylint: disable=import-error |
| 115 | + |
| 116 | + try: |
| 117 | + token = _metadata.get( |
| 118 | + request, |
| 119 | + METADATA_IDENTITY_PATH, |
| 120 | + params={"audience": audience, "format": "full"}, |
| 121 | + ) |
| 122 | + except exceptions.GoogleAuthError: |
| 123 | + logger.debug("GCPDetector: metadata id token fetch failed", exc_info=True) |
| 124 | + return None |
| 125 | + if not isinstance(token, str): |
| 126 | + return None |
| 127 | + return token.strip() or None |
| 128 | + |
| 129 | + def _token_from_compute_id_token_credentials( |
| 130 | + self, audience: str, request |
| 131 | + ) -> str | None: |
| 132 | + # Cloud Build's metadata server has no identity (ID-token) endpoint, so |
| 133 | + # _token_from_metadata returns nothing there. Fall back to the IAM |
| 134 | + # Credentials API (generateIdToken), which the workload's service |
| 135 | + # account can call for itself when granted roles/iam.serviceAccountTokenCreator. |
| 136 | + from google.auth import ( # pylint: disable=import-error |
| 137 | + compute_engine, |
| 138 | + exceptions, |
| 139 | + ) |
| 140 | + |
| 141 | + try: |
| 142 | + id_credentials = compute_engine.IDTokenCredentials( |
| 143 | + request, |
| 144 | + target_audience=audience, |
| 145 | + use_metadata_identity_endpoint=False, |
| 146 | + ) |
| 147 | + id_credentials.refresh(request) |
| 148 | + except exceptions.GoogleAuthError: |
| 149 | + logger.debug( |
| 150 | + "GCPDetector: compute ID token credentials fetch failed", |
| 151 | + exc_info=True, |
| 152 | + ) |
| 153 | + return None |
| 154 | + return id_credentials.token or None |
| 155 | + |
| 156 | + def _token_from_user_credentials(self, credentials, request) -> str | None: |
| 157 | + from google.auth import exceptions # pylint: disable=import-error |
| 158 | + |
| 159 | + try: |
| 160 | + credentials.refresh(request) |
| 161 | + except exceptions.GoogleAuthError: |
| 162 | + logger.debug("GCPDetector: ADC id_token refresh failed", exc_info=True) |
| 163 | + return None |
| 164 | + return getattr(credentials, "id_token", None) or None |
| 165 | + |
| 166 | + def _token_from_id_token_credentials(self, audience: str, request) -> str | None: |
| 167 | + from google.auth import exceptions # pylint: disable=import-error |
| 168 | + from google.oauth2 import id_token # pylint: disable=import-error |
| 169 | + |
| 170 | + try: |
| 171 | + id_credentials = id_token.fetch_id_token_credentials(audience, request) |
| 172 | + id_credentials.refresh(request) |
| 173 | + return id_credentials.token or None |
| 174 | + except exceptions.GoogleAuthError: |
| 175 | + logger.debug( |
| 176 | + "GCPDetector: ID token credentials fetch failed", exc_info=True |
| 177 | + ) |
| 178 | + return None |
0 commit comments