def AuthorizeClient(self, http_client, creds): """Returns an http_client authorized with the given credentials.""" if core_creds.IsGoogleAuthCredentials(creds): http_client = google_auth_httplib2.AuthorizedHttp(creds, http_client) else: http_client = creds.authorize(http_client) return http_client
def Run(self, args): credential = store.Load(args.account_name, use_google_auth=True) if not credential: raise exceptions.CredentialsNotFound( 'The credentials for account [{0}] do not exist.'.format( args.account_name)) if creds.IsGoogleAuthCredentials(credential): json_cred = creds.SerializeCredsGoogleAuth(credential) return json.loads(json_cred) return json.loads(credential.to_json())
def _GetAccessTokenCallback(credentials): """Callback function to refresh credentials and return access token.""" if not credentials: return None log.debug('credentials type for _GetAccessTokenCallback is [%s].', six.text_type(credentials)) store.Refresh(credentials) if creds.IsGoogleAuthCredentials(credentials): return credentials.token else: return credentials.access_token
def GetGapicCredentials(enable_resource_quota=True, allow_account_impersonation=True): """Returns a credential object for use by gapic client libraries. Currently, we set _quota_project on the credentials, unlike for http requests, which add quota project through request wrapping to implement go/gcloud-quota-model-v2. Additionally, we wrap the refresh method and plug in our own google.auth.transport.Request object that uses our transport. Args: enable_resource_quota: bool, By default, we are going to tell APIs to use the quota of the project being operated on. For some APIs we want to use gcloud's quota, so you can explicitly disable that behavior by passing False here. allow_account_impersonation: bool, True to allow use of impersonated service account credentials for calls made with this client. If False, the active user credentials will always be used. Returns: A google auth credentials.Credentials object. Raises: MissingStoredCredentialsError: If a google-auth credential cannot be loaded. """ credentials = store.LoadIfEnabled( allow_account_impersonation=allow_account_impersonation, use_google_auth=True) if not creds.IsGoogleAuthCredentials(credentials): raise MissingStoredCredentialsError('Unable to load credentials') if enable_resource_quota: # pylint: disable=protected-access credentials._quota_project_id = creds.GetQuotaProject(credentials) # In order to ensure that credentials.Credentials:refresh is called with a # google.auth.transport.Request that uses our transport, we ignore the request # argument that is passed in and plug in our own. original_refresh = credentials.refresh def WrappedRefresh(request): del request # unused return original_refresh(requests.GoogleAuthRequest()) credentials.refresh = WrappedRefresh return credentials
def Run(self, args): """Run the helper command.""" if args.method == DockerHelper.LIST: return { # This tells Docker that the secret will be an access token, not a # username/password. # Docker normally expects a prefixed 'https://' for auth configs. ('https://' + url): '_dcgcloud_token' for url in credential_utils.DefaultAuthenticatedRegistries() } elif args.method == DockerHelper.GET: # docker credential helper protocol expects that error is printed to # stdout. try: cred = c_store.Load(use_google_auth=True) except creds_exceptions.NoActiveAccountException: log.Print( 'You do not currently have an active account selected. ' 'See https://cloud.google.com/sdk/docs/authorizing for more ' 'information.') sys.exit(1) c_store.RefreshIfExpireWithinWindow(cred, window=TOKEN_MIN_LIFETIME) url = sys.stdin.read().strip() if (url.replace('https://', '', 1) not in credential_utils.SupportedRegistries()): raise exceptions.Error( 'Repository url [{url}] is not supported'.format(url=url)) # Putting an actual username in the response doesn't work. Docker will # then prompt for a password instead of using the access token. token = (cred.token if c_creds.IsGoogleAuthCredentials(cred) else cred.access_token) return { 'Secret': token, 'Username': '******', } # Don't print anything if we are not supporting the given action. # The credential helper protocol also support 'store' and 'erase' actions # that don't apply here. The full spec can be found here: # https://github.com/docker/docker-credential-helpers#development args.GetDisplayInfo().AddFormat('none') return None
def Http(timeout='unset', response_encoding=None, ca_certs=None, enable_resource_quota=True, force_resource_quota=False, allow_account_impersonation=True, use_google_auth=None): """Get an httplib2.Http client for working with the Google API. Args: timeout: double, The timeout in seconds to pass to httplib2. This is the socket level timeout. If timeout is None, timeout is infinite. If default argument 'unset' is given, a sensible default is selected. response_encoding: str, the encoding to use to decode the response. ca_certs: str, absolute filename of a ca_certs file that overrides the default enable_resource_quota: bool, By default, we are going to tell APIs to use the quota of the project being operated on. For some APIs we want to use gcloud's quota, so you can explicitly disable that behavior by passing False here. force_resource_quota: bool, If true resource project quota will be used by this client regardless of the settings in gcloud. This should be used for newer APIs that cannot work with legacy project quota. allow_account_impersonation: bool, True to allow use of impersonated service account credentials for calls made with this client. If False, the active user credentials will always be used. use_google_auth: bool, True if the calling command indicates to use google-auth library for authentication. If False, authentication will fallback to using the oauth2client library. If None, set the value based on the configuration. Returns: 1. A regular httplib2.Http object if no credentials are available; 2. Or a httplib2.Http client object authorized by oauth2client credentials if use_google_auth==False; 3. Or a google_auth_httplib2.AuthorizedHttp client object authorized by google-auth credentials. Raises: c_store.Error: If an error loading the credentials occurs. """ http_client = http.Http(timeout=timeout, response_encoding=response_encoding, ca_certs=ca_certs) if use_google_auth is None: use_google_auth = base.UseGoogleAuth() request_wrapper = RequestWrapper() http_client = request_wrapper.WrapQuota( http_client, enable_resource_quota, force_resource_quota, allow_account_impersonation, use_google_auth) http_client = request_wrapper.WrapCredentials(http_client, allow_account_impersonation, use_google_auth) if hasattr(http_client, '_googlecloudsdk_credentials'): creds = http_client._googlecloudsdk_credentials # pylint: disable=protected-access if core_creds.IsGoogleAuthCredentials(creds): apitools_creds = _GoogleAuthApitoolsCredentials(creds) else: apitools_creds = creds # apitools needs this attribute to do credential refreshes during batch API # requests. setattr(http_client.request, 'credentials', apitools_creds) return http_client
def _InitCredentials(self, credentials): if c_creds.IsGoogleAuthCredentials(credentials): self._InitGoogleAuthCreds(credentials) else: self._InitOauth2clientCreds(credentials)
def Http(timeout='unset', enable_resource_quota=True, force_resource_quota=False, response_encoding=None, ca_certs=None, allow_account_impersonation=True, use_google_auth=False): """Get an httplib2.Http client for working with the Google API. Args: timeout: double, The timeout in seconds to pass to httplib2. This is the socket level timeout. If timeout is None, timeout is infinite. If default argument 'unset' is given, a sensible default is selected. enable_resource_quota: bool, By default, we are going to tell APIs to use the quota of the project being operated on. For some APIs we want to use gcloud's quota, so you can explicitly disable that behavior by passing False here. force_resource_quota: bool, If true resource project quota will be used by this client regardless of the settings in gcloud. This should be used for newer APIs that cannot work with legacy project quota. response_encoding: str, the encoding to use to decode the response. ca_certs: str, absolute filename of a ca_certs file that overrides the default allow_account_impersonation: bool, True to allow use of impersonated service account credentials for calls made with this client. If False, the active user credentials will always be used. use_google_auth: bool, True if the calling command indicates to use google-auth library for authentication. If False, authentication will fallback to using the oauth2client library. Returns: 1. A regular httplib2.Http object if no credentials are available; 2. Or a httplib2.Http client object authorized by oauth2client credentials if use_google_auth==False; 3. Or a google_auth_httplib2.AuthorizedHttp client object authorized by google-auth credentials. Raises: c_store.Error: If an error loading the credentials occurs. """ http_client = http.Http(timeout=timeout, response_encoding=response_encoding, ca_certs=ca_certs) # Wrappers for IAM header injection. authority_selector = properties.VALUES.auth.authority_selector.Get() authorization_token_file = ( properties.VALUES.auth.authorization_token_file.Get()) handlers = _GetIAMAuthHandlers(authority_selector, authorization_token_file) creds = store.LoadIfEnabled(allow_account_impersonation, use_google_auth) if creds: # Inject the resource project header for quota unless explicitly disabled. if enable_resource_quota or force_resource_quota: quota_project = core_creds.GetQuotaProject(creds, force_resource_quota) if quota_project: handlers.append(http.Modifiers.Handler( http.Modifiers.SetHeader('X-Goog-User-Project', quota_project))) if core_creds.IsGoogleAuthCredentials(creds): http_client = google_auth_httplib2.AuthorizedHttp(creds, http_client) else: http_client = creds.authorize(http_client) # Wrap the request method to put in our own error handling. http_client = http.Modifiers.WrapRequest(http_client, handlers, _HandleAuthError, client.AccessTokenRefreshError) return http_client