def GetElevationAccessTokenGoogleAuth(self, source_credentials, service_account_id, scopes): """Creates a fresh impersonation credential using google-auth library.""" request_client = core_requests.GoogleAuthRequest() # google-auth makes a shadow copy of the source_credentials and refresh # the copy instead of the original source_credentials. During the copying, # the monkey patch # (creds.CredentialStoreWithCache._WrapCredentialsRefreshWithAutoCaching) # is lost. Here, before passing to google-auth, we refresh # source_credentials. source_credentials.refresh(request_client) # Import only when necessary to decrease the startup time. Move it to # global once google-auth is ready to replace oauth2client. # pylint: disable=g-import-not-at-top from google.auth import impersonated_credentials as google_auth_impersonated_creds # pylint: enable=g-import-not-at-top cred = google_auth_impersonated_creds.Credentials( source_credentials, service_account_id, scopes) try: cred.refresh(request_client) except google_auth_exceptions.RefreshError: raise ImpersonatedCredGoogleAuthRefreshError( 'Failed to impersonate [{service_acc}]. Make sure the ' 'account that\'s trying to impersonate it has access to the service ' 'account itself and the "roles/iam.serviceAccountTokenCreator" ' 'role.'.format(service_acc=service_account_id)) return cred
def __init__(self, host_mode=False): self.initialized = False self.base_url = 'https://storage.googleapis.com/storage/v1/' if host_mode: # make read-only temporary credentials target_scopes = [ 'https://www.googleapis.com/auth/devstorage.read_only' ] self.admin_credentials = service_account.Credentials.from_service_account_file( os.getenv('RD_STORAGE_GOOGLE_ACCOUNT'), scopes=target_scopes) self.reader_credentials = impersonated_credentials.Credentials( source_credentials=self.admin_credentials, target_principal=os.getenv( 'RD_STORAGE_GOOGLE_ACCOUNT_READONLY'), target_scopes=target_scopes, lifetime=3600) self.reader_credentials.refresh(Request()) self.initialize(os.getenv('RD_STORAGE_GOOGLE_BUCKET'), self.reader_credentials.token) else: # guest mode pass
def impersonate_service_account( service_account_name: str, target_scopes: Optional[Sequence[str]] = None ) -> impersonated_credentials.Credentials: """Impersonates a service account. This method impersonates a service account and returns a credential object which then can be used to authenticate calls to Google Cloud APIs. The caller must have "Service Account Token Creator" IAM role explicitly added. This is applicable even for users who have "Owner" IAM role. Args: service_account_name: The service account name. target_scopes: Scopes to request during the authorization grant. Returns: Credential object to authenticate while calling GCP APIs. """ if not target_scopes: # Full access to all resources and services in the specified GCP project. logging.info( 'The target scope was not passed. So by default requesting' 'impersonated credentials to access all resources and services') target_scopes = [_SCOPE] default_credentials = get_default_credentials() return impersonated_credentials.Credentials( source_credentials=default_credentials, target_principal=service_account_name, target_scopes=target_scopes)
def get_credentials_and_project(self): """ Get current credentials and project ID. :return: Google Auth Credentials :type: Tuple[google.auth.credentials.Credentials, str] """ if self.key_path: credentials, project_id = self._get_credentials_using_key_path() elif self.keyfile_dict: credentials, project_id = self._get_credentials_using_keyfile_dict( ) else: credentials, project_id = self._get_credentials_using_adc() if self.delegate_to: if hasattr(credentials, 'with_subject'): credentials = credentials.with_subject(self.delegate_to) else: raise AirflowException( "The `delegate_to` parameter cannot be used here as the current " "authentication method does not support account impersonate. " "Please use service-account for authorization.") if self.target_principal: credentials = impersonated_credentials.Credentials( source_credentials=credentials, target_principal=self.target_principal, delegates=self.delegates, target_scopes=self.scopes) return credentials, project_id
def get_credential(auth_type, target): os.environ[ 'GOOGLE_APPLICATION_CREDENTIALS'] = "D:/Learning/GCP/key/admin.json" #credential = source_credentials = service_account.Credentials.from_service_account_file( #'/path/to/svc_account.json') if (auth_type == 'default'): cedential, project = google.auth.default() scoped_credentials = cedential.with_scopes([ 'https://www.googleapis.com/auth/compute', 'https://www.googleapis.com/auth/devstorage.read_write' ]) return [scoped_credentials, project] if (auth_type == 'servicefile'): credential = service_account.Credentials.from_service_account_file( 'D:/Learning/GCP/key/admin.json') if (auth_type == 'impersonate'): source_credentials, project = google.auth.default() target_credentials = impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal= '*****@*****.**', target_scopes='https://www.googleapis.com/auth/compute', lifetime=500) return target_credentials
def get_impersonated_bigquery_credentials(cls, profile_credentials): source_credentials = cls.get_bigquery_credentials(profile_credentials) return impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal=profile_credentials.impersonate_service_account, target_scopes=list(cls.SCOPE), lifetime=profile_credentials.timeout_seconds, )
def default_service_account_credentials(self): target_scopes = [u'https://www.googleapis.com/auth/cloud-platform'] default_service_account_credentials = app_engine.Credentials( scopes=target_scopes) return impersonated_credentials.Credentials( source_credentials=default_service_account_credentials, target_principal= u'*****@*****.**', target_scopes=target_scopes)
def get_target_credentials(self): impersonated_sa = f'{self._source_sa_name}@{self._project_id}.iam.gserviceaccount.com' source_credentials, _ = default() target_credentials = impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal=impersonated_sa, target_scopes=self.target_scopes, delegates=[], lifetime=500) return target_credentials
def _initialize_impersonated_credentials(self): """Generates an impersonated credentials. For more details, see `projects.serviceAccounts.generateAccessToken`_. .. _projects.serviceAccounts.generateAccessToken: https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken Returns: impersonated_credentials.Credential: The impersonated credentials object. Raises: google.auth.exceptions.RefreshError: If the generateAccessToken endpoint returned an error. """ # Return copy of instance with no service account impersonation. source_credentials = self.__class__( audience=self._audience, subject_token_type=self._subject_token_type, token_url=self._token_url, credential_source=self._credential_source, service_account_impersonation_url=None, client_id=self._client_id, client_secret=self._client_secret, quota_project_id=self._quota_project_id, scopes=self._scopes, default_scopes=self._default_scopes, ) # Determine target_principal. start_index = self._service_account_impersonation_url.rfind("/") end_index = self._service_account_impersonation_url.find( ":generateAccessToken") if start_index != -1 and end_index != -1 and start_index < end_index: start_index = start_index + 1 target_principal = self._service_account_impersonation_url[ start_index:end_index] else: raise exceptions.RefreshError( "Unable to determine target principal from service account impersonation URL." ) scopes = self._scopes if self._scopes is not None else self._default_scopes # Initialize and return impersonated credentials. return impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal=target_principal, target_scopes=scopes, quota_project_id=self._quota_project_id, iam_endpoint_override=self._service_account_impersonation_url, )
def __init__( self, credentials: Credentials = None, gcp_project_id: str = None, gcp_service_account_key_path: Path = None, gcp_impersonation_credentials: str = None, ) -> None: # Use Credentials object directly if provided if credentials: source_credentials = credentials # Use service account json key if provided elif gcp_service_account_key_path: source_credentials = service_account.Credentials.from_service_account_file( filename=gcp_service_account_key_path, scopes=TARGET_SCOPES, quota_project_id=gcp_project_id, ) # Otherwise, use Application Default Credentials else: application_credentials_file = os.environ.get( "GOOGLE_APPLICATION_CREDENTIALS", None) if application_credentials_file: logger.info( "Using environment variable GOOGLE_APPLICATION_CREDENTIALS " f"path: {application_credentials_file}") source_credentials, _ = google.auth.default( scopes=TARGET_SCOPES, quota_project_id=gcp_project_id) if not source_credentials.valid: self.__refresh_credentials(source_credentials) # Attempt service account impersonation if requested if gcp_impersonation_credentials: target_credentials = impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal=gcp_impersonation_credentials, target_scopes=TARGET_SCOPES, lifetime=3600, ) self.credentials = target_credentials else: # Otherwise use source_credentials self.credentials = source_credentials self.project_id = self.__resolve_project_id( credentials=self.credentials, project_id=gcp_project_id) self.user_id = self.__resolve_credentials_username( credentials=self.credentials) if self.user_id: logger.info("Successfully created GCP Client.") else: logger.warning( "Encountered error while retrieving user from GCP credentials.", )
def _initialize_impersonated_credentials(self): """Generates an impersonated credentials. For more details, see `projects.serviceAccounts.generateAccessToken`_. .. _projects.serviceAccounts.generateAccessToken: https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken Returns: impersonated_credentials.Credential: The impersonated credentials object. Raises: google.auth.exceptions.RefreshError: If the generateAccessToken endpoint returned an error. """ # Return copy of instance with no service account impersonation. d = dict( audience=self._audience, subject_token_type=self._subject_token_type, token_url=self._token_url, credential_source=self._credential_source, service_account_impersonation_url=None, client_id=self._client_id, client_secret=self._client_secret, quota_project_id=self._quota_project_id, scopes=self._scopes, default_scopes=self._default_scopes, workforce_pool_user_project=self._workforce_pool_user_project, ) if not self.is_workforce_pool: d.pop("workforce_pool_user_project") source_credentials = self.__class__(**d) # Determine target_principal. target_principal = self.service_account_email if not target_principal: raise exceptions.RefreshError( "Unable to determine target principal from service account impersonation URL." ) scopes = self._scopes if self._scopes is not None else self._default_scopes # Initialize and return impersonated credentials. return impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal=target_principal, target_scopes=scopes, quota_project_id=self._quota_project_id, iam_endpoint_override=self._service_account_impersonation_url, )
def GetElevationAccessTokenGoogleAuth(self, source_credentials, service_account_id, scopes): """Creates a fresh impersonation credential using google-auth library.""" request_client = http_core.GoogleAuthRequest() # google-auth makes a shadow copy of the source_credentials and refresh # the copy instead of the original source_credentials. During the copying, # the monkey patch # (creds.CredentialStoreWithCache._WrapCredentialsRefreshWithAutoCaching) # is lost. Here, before passing to google-auth, we refresh # source_credentials. source_credentials.refresh(request_client) cred = google_auth_impersonated_creds.Credentials( source_credentials, service_account_id, scopes) cred.refresh(request_client) return cred
def get_credentials(credentials_path, impersonate_service_account): """Fetch credentials for verifying Project Factory preconditions. Credentials will be loaded from a service account file if present, generated by impersonating the service account provided or from Application Default Credentials otherwise. Args: credentials_path: an optional path to service account credentials. impersonate_service_account: an optional service account to impersonate. Returns: (credentials, project_id): A tuple containing the credentials and associated project ID. """ if credentials_path is not None: # Prefer an explicit credentials file svc_credentials = service_account.Credentials\ .from_service_account_file(credentials_path) credentials = (svc_credentials, svc_credentials.project_id) elif impersonate_service_account is not None: try: source_credentials = google.auth.default() credentials = impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal=impersonate_service_account, target_scopes=[ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/userinfo.email' ], lifetime=120) except google.auth.exceptions.RefreshError: raise google.auth.exceptions.DefaultCredentialsError() else: # Fall back to application default credentials try: credentials = google.auth.default() except google.auth.exceptions.RefreshError: raise google.auth.exceptions.DefaultCredentialsError() return credentials
def GetElevationAccessTokenGoogleAuth(self, source_credentials, service_account_id, scopes): """Creates a fresh impersonation credential using google-auth library.""" request_client = http_core.GoogleAuthRequest() # google-auth makes a shadow copy of the source_credentials and refresh # the copy instead of the original source_credentials. During the copying, # the monkey patch # (creds.CredentialStoreWithCache._WrapCredentialsRefreshWithAutoCaching) # is lost. Here, before passing to google-auth, we refresh # source_credentials. source_credentials.refresh(request_client) # Import only when necessary to decrease the startup time. Move it to # global once google-auth is ready to replace oauth2client. # pylint: disable=g-import-not-at-top from google.auth import impersonated_credentials as google_auth_impersonated_creds # pylint: enable=g-import-not-at-top cred = google_auth_impersonated_creds.Credentials( source_credentials, service_account_id, scopes) cred.refresh(request_client) return cred
def _add_impersonation_credentials(credentials, pipeline_options): if isinstance(pipeline_options, PipelineOptions): gcs_options = pipeline_options.view_as(GoogleCloudOptions) impersonate_service_account = gcs_options.impersonate_service_account elif isinstance(pipeline_options, dict): impersonate_service_account = pipeline_options.get( 'impersonate_service_account') else: return credentials if impersonate_service_account: _LOGGER.info('Impersonating: %s', impersonate_service_account) impersonate_accounts = impersonate_service_account.split(',') target_principal = impersonate_accounts[-1] delegate_to = impersonate_accounts[0:-1] credentials = impersonated_credentials.Credentials( source_credentials=credentials, target_principal=target_principal, delegates=delegate_to, target_scopes=CLIENT_SCOPES, ) return credentials
def gbucket(filename): storage.Client() target_scopes = ['https://www.googleapis.com/auth/devstorage.read_only'] source_credentials = service_account.Credentials.from_service_account_file( cwd + "/keelaa.json", scopes=target_scopes, subject='*****@*****.**') # credentials=cwd+"/keelaa.json" target_credentials = impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal= '*****@*****.**', target_scopes=target_scopes, lifetime=500) credentials = service_account.Credentials.from_service_account_file( cwd + "/keelaa.json") client = storage.Client() client = client._credentials transport = AuthorizedSession(credentials=client) url_template = ( u'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' u'uploadType=resumable') upload_url = url_template.format(bucket='keelaa-images') chunk_size = 3 * 1024 * 1024 upload = ResumableUpload(upload_url, chunk_size) print(upload.total_bytes is None, "klvnsdkfvnk") print(upload_url) stream = open(filename, u'rb') total_bytes = os.path.getsize(filename) metadata = {u'name': filename} response = upload.initiate(transport, stream, metadata, u'text/plain', total_bytes=total_bytes, stream_final=True) print(upload.total_bytes == total_bytes) return response
def gmulti(filename, name): storage.Client() target_scopes = ['https://www.googleapis.com/auth/devstorage.read_only'] source_credentials = service_account.Credentials.from_service_account_file( cwd + "/keelaa.json", scopes=target_scopes, subject='*****@*****.**') # credentials=cwd+"/keelaa.json" target_credentials = impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal= '*****@*****.**', target_scopes=target_scopes, lifetime=500) credentials = service_account.Credentials.from_service_account_file( cwd + "/keelaa.json") name1 = re.sub('\.[a-zA-Z]+', '', name) client = storage.Client() client = client._credentials transport = AuthorizedSession(credentials=client) content_type = u'text/plain' with open(filename, "rb") as imageFile: data = imageFile.read() url_template = ( u'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' u'uploadType=multipart') upload_url = url_template.format(bucket='keelaa-images') upload = MultipartUpload(upload_url) metadata = { u'name': name1, u'metadata': { u'color': u'grurple', }, } response = upload.transmit(transport, data, metadata, content_type) print(upload.finished) return response.json()
def _get_impersonated_service_account_credentials(filename, info, scopes): from google.auth import impersonated_credentials try: source_credentials_info = info.get("source_credentials") source_credentials_type = source_credentials_info.get("type") if source_credentials_type == _AUTHORIZED_USER_TYPE: source_credentials, _ = _get_authorized_user_credentials( filename, source_credentials_info) elif source_credentials_type == _SERVICE_ACCOUNT_TYPE: source_credentials, _ = _get_service_account_credentials( filename, source_credentials_info) else: raise ValueError( "source credential of type {} is not supported.".format( source_credentials_type)) impersonation_url = info.get("service_account_impersonation_url") start_index = impersonation_url.rfind("/") end_index = impersonation_url.find(":generateAccessToken") if start_index == -1 or end_index == -1 or start_index > end_index: raise ValueError("Cannot extract target principal from {}".format( impersonation_url)) target_principal = impersonation_url[start_index + 1:end_index] delegates = info.get("delegates") quota_project_id = info.get("quota_project_id") credentials = impersonated_credentials.Credentials( source_credentials, target_principal, scopes, delegates, quota_project_id=quota_project_id, ) except ValueError as caught_exc: msg = "Failed to load impersonated service account credentials from {}".format( filename) new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) six.raise_from(new_exc, caught_exc) return credentials, None
def checkStatus(serviceName, userName, clusterName): print("Checking status....") serviceStatus = True while serviceStatus: time.sleep(1) if serviceName == 'traefik': credentials = service_account.Credentials.from_service_account_file( './app_controllers/secrets/serviceAccount.json') # scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/userinfo.email']) target_credentials = impersonated_credentials.Credentials( source_credentials=credentials, target_principal= '*****@*****.**', target_scopes=[ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ], lifetime=3600) # subject_credentials = credentials.with_subject('*****@*****.**') # print("CREDENTIALS:",subject_credentials) authed_session = AuthorizedSession(target_credentials) print("AUTHORIZED:", authed_session) print( "URL:", 'http://' + str(serviceName) + '.' + str(clusterName) + '.securethebox.us:8080/') response = authed_session.get('http://' + str(serviceName) + '.' + str(clusterName) + '.securethebox.us:8080/') # print("RESPONSE:",response.text) # signed_jwt = generate_jwt(audience='http://'+str(serviceName)+'.'+str(clusterName)+'.securethebox.us:8080/') # print(signed_jwt) # headers = { # 'Authorization': 'Bearer {}'.format(signed_jwt.decode('utf-8')), # 'content-type': 'application/json' # } # response = requests.get('http://'+str(serviceName)+'.'+str(clusterName)+'.securethebox.us:8080/', headers=headers, allow_redirects=True) # response.raise_for_status() # print("RESPONSE:",response.url) if response.status_code == 200: serviceStatus = False print(response.status_code, "out of loop") pass else: credentials = service_account.Credentials.from_service_account_file( './app_controllers/secrets/serviceAccount.json') # scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/userinfo.email']) target_credentials = impersonated_credentials.Credentials( source_credentials=credentials, target_principal= '*****@*****.**', target_scopes=[ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ], lifetime=3600) # print("CREDENTIALS:",target_credentials) authed_session = AuthorizedSession(target_credentials) print("AUTHORIZED:", authed_session) print( "URL:", 'http://' + str(serviceName) + '-' + str(userName) + '.' + str(clusterName) + '.securethebox.us/') response = authed_session.request( "GET", 'http://' + str(serviceName) + '-' + str(userName) + '.' + str(clusterName) + '.securethebox.us/') # print("RESPONSE:",response.text) # signed_jwt = generate_jwt(audience='http://'+str(serviceName)+'-'+str(userName)+'.'+str(clusterName)+'.securethebox.us/') # print(signed_jwt) # headers = { # 'Authorization': 'Bearer {}'.format(signed_jwt.decode('utf-8')), # 'content-type': 'application/json' # } # response = requests.get('http://'+str(serviceName)+'-'+str(userName)+'.'+str(clusterName)+'.securethebox.us/', headers=headers, allow_redirects=True) # response.raise_for_status() # print("RESPONSE:",response.url) if response.status_code == 200: serviceStatus = False print(response.status_code, "out of loop") pass
import google.oauth2.credentials from google.oauth2 import service_account from google.auth import impersonated_credentials from requests_oauthlib import OAuth2Session urllib3.disable_warnings() credentials = service_account.Credentials.from_service_account_file( './app_controllers/secrets/serviceAccount.json') scoped_credentials = credentials.with_scopes([ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ]) target_credentials = impersonated_credentials.Credentials( source_credentials=credentials, target_principal='*****@*****.**', target_scopes=[ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ], lifetime=3600) print("CREDENTIALS:", target_credentials) authed_session = AuthorizedSession(scoped_credentials) print("AUTHORIZED:", authed_session) client_id = "622501345065-1iqrldk5iqg33hq6fag500p364j94ljo.apps.googleusercontent.com" client_secret = "PFxqCSPdxXXN8-sMPW-5J_hw" redirect_uri = 'http://auth.securethebox.us/_oauth' scope = [ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ] google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)
# For service account credentials svc_account_file = 'svc-src.json' target_scopes = ['https://www.googleapis.com/auth/devstorage.read_only'] source_credentials = service_account.Credentials.from_service_account_file( svc_account_file, scopes=target_scopes) # For ComputeCredentials # source_credentials, project = google.auth.default() try: client = storage.Client(credentials=source_credentials) buckets = client.list_buckets(project='fabled-ray-104117') for bucket in buckets: print bucket.name except google.api_core.exceptions.Forbidden: print ">>>>> Forbidden" pass # now try delegation target_credentials = impersonated_credentials.Credentials( source_credentials=source_credentials, target_principal= '*****@*****.**', target_scopes=target_scopes, delegates=[], lifetime=500) client = storage.Client(credentials=target_credentials) buckets = client.list_buckets(project='fabled-ray-104117') for bucket in buckets: print bucket.name
def get_impersonation_credentials(target_principal, target_scopes=None, key_file=None): """ Get useful impersonation credentials. The target principal email address is required. If a key_file path is not provided, attempts will be made to determine your valid credentials from the environment. Potential target scopes when using impersonation are: 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/devstorage.read_write', :param target_principal: email address to impersonate. typically, this is an email address associated with a google service account. :param target_scopes: a list of scopes that the impersonating account needs to perform requested actions. if no list is provided, it defaults to a limited set of functionality. :param key_file: path to a json service account google key file. If provided, this key file will be used to create source credentials. If missing and the GOOGLE_APPLICATION_CREDENTIALS environment variable is set, that service account key file will be used. If this environment variable is unset, your user account default application credentials will be used. This usage is preferable. :returns: valid impersonated credentials """ if not target_principal: raise RuntimeError( "Cannot impersonate. No impersonation target specified.") if not target_scopes: LOGGER.warning(f"Using default scopes: {DEFAULT_SCOPES}") target_scopes = DEFAULT_SCOPES if not isinstance(target_scopes, (list, tuple)): LOGGER.warning(f"Target scopes requires an iterable. Currently " f"for lists and tuples. Using " f"default scopes: {DEFAULT_SCOPES}.") target_scopes = DEFAULT_SCOPES if key_file: try: creds = (service_account.Credentials.from_service_account_file( key_file, scopes=target_scopes)) except (OSError, ValueError) as exc: LOGGER.exception(f"{key_file} is an invalid file path.") raise (exc) # if the wrong key file is provided, this will cause a RefreshError # when the credentials are used, not at creation. return impersonated_credentials.Credentials( source_credentials=creds, target_principal=target_principal, target_scopes=target_scopes, lifetime=IMPERSONATION_LIFETIME) else: with warnings.catch_warnings(): # the library sends a UserWarning about end user credentials. # this context manager will ignore that one warning warnings.simplefilter("ignore", category=UserWarning) creds, _ = default() try: if creds.client_secret: LOGGER.info( f"Using end user account to impersonate: {target_principal}" ) target_credentials = impersonated_credentials.Credentials( source_credentials=creds, target_principal=target_principal, target_scopes=target_scopes, lifetime=IMPERSONATION_LIFETIME) # scopes must be reset when using end user credentials target_credentials._source_credentials._scopes = creds.scopes return target_credentials except AttributeError: if creds.service_account_email: LOGGER.info( f"Using service account to impersonate: {target_principal}" ) return impersonated_credentials.Credentials( source_credentials=creds, target_principal=target_principal, target_scopes=target_scopes, lifetime=IMPERSONATION_LIFETIME) except (OSError, ValueError, TypeError, RuntimeError) as exc: LOGGER.exception("An unexpected error was encountered") raise (exc)