def AddQuotaProjectToADC(quota_project): """Adds the quota project to the existing ADC file. Quota project is only added to ADC when the credentials have the "serviceusage.services.use" permission on the project. Args: quota_project: str, The project id of a valid GCP project to add to ADC. Raises: MissingPermissionOnQuotaProjectError: If the credentials do not have the "serviceusage.services.use" permission. """ AssertADCExists() if not ADCIsUserAccount(): raise c_exc.BadFileException( 'The application default credentials are not user credentials, quota ' 'project cannot be added.') if not AdcHasGivenPermissionOnProject( quota_project, permissions=[SERVICEUSAGE_PERMISSION]): raise MissingPermissionOnQuotaProjectError( 'Cannot add the project "{}" to application default credentials (ADC) ' 'as a quota project because the account in ADC does not have the ' '"{}" permission on this project.'.format(quota_project, SERVICEUSAGE_PERMISSION)) credentials = client.GoogleCredentials.from_stream(config.ADCFilePath()) adc_path = c_creds.ADC(credentials).DumpExtendedADCToFile( quota_project=quota_project) LogADCIsWritten(adc_path) LogQuotaProjectAdded(quota_project)
def _DockerRunOptions(enable_gpu=False, service_account_key=None, cred_mount_path=_DEFAULT_CONTAINER_CRED_KEY_PATH, extra_run_opts=None): """Returns a list of 'docker run' options. Args: enable_gpu: (bool) using GPU or not. service_account_key: (bool) path of the service account key to use in host. cred_mount_path: (str) path in the container to mount the credential key. extra_run_opts: (List[str]) other custom docker run options. """ if extra_run_opts is None: extra_run_opts = [] runtime = ["--runtime", "nvidia"] if enable_gpu else [] if service_account_key: mount = ["-v", "{}:{}".format(service_account_key, cred_mount_path)] else: # Calls Application Default Credential (ADC), adc_file_path = config.ADCEnvVariable() or config.ADCFilePath() mount = ["-v", "{}:{}".format(adc_file_path, cred_mount_path)] env_var = [ "-e", "GOOGLE_APPLICATION_CREDENTIALS={}".format(cred_mount_path) ] return ["--rm"] + runtime + mount + env_var + ["--ipc", "host" ] + extra_run_opts
def ADCIsUserAccount(): """Returns whether the ADC credentials correspond to a user account or not.""" cred_file = config.ADCFilePath() creds, _ = c_creds.GetGoogleAuthDefault().load_credentials_from_file( cred_file) return (c_creds.IsUserAccountCredentials(creds) or c_creds.IsExternalAccountUserCredentials(creds))
def Run(self, args): """Revoke Application Default Credentials.""" cred_file = config.ADCFilePath() if not os.path.isfile(cred_file): log.status.Print( 'Application Default Credentials have not been set up, ' 'nothing to revoke.') return creds = client.GoogleCredentials.from_stream(cred_file) if creds.serialization_data['type'] != 'authorized_user': raise c_exc.BadFileException( 'The given credential file is a service account credential, and ' 'cannot be revoked.') console_io.PromptContinue( 'You are about to revoke the credentials stored in: [{file}]'. format(file=cred_file), throw_if_unattended=True, cancel_on_no=True) c_store.RevokeCredentials(creds) os.remove(cred_file) log.status.Print('Credentials revoked.')
def _AdcHasGivenPermissionOnProjectHelper(project_ref, permissions): cred_file_override_old = properties.VALUES.auth.credential_file_override.Get() try: properties.VALUES.auth.credential_file_override.Set(config.ADCFilePath()) granted_permissions = projects_api.TestIamPermissions( project_ref, permissions).permissions return set(permissions) == set(granted_permissions) finally: properties.VALUES.auth.credential_file_override.Set(cred_file_override_old)
def DumpExtendedADCToFile(self, file_path=None, quota_project=None): """Dumps the credentials and the quota project to the ADC json file.""" if not self.is_user: raise CredentialFileSaveError( 'The credential is not a user credential, so we cannot insert a ' 'quota project to application default credential.') file_path = file_path or config.ADCFilePath() if not quota_project: quota_project = GetQuotaProject(self._credentials, force_resource_quota=True) extended_adc = self._ExtendADCWithQuotaProject(quota_project) return _DumpADCJsonToFile(extended_adc, file_path)
def PromptIfADCEnvVarIsSet(): """Warns users if ADC environment variable is set.""" override_file = config.ADCEnvVariable() if override_file: message = textwrap.dedent(""" The environment variable [{envvar}] is set to: [{override_file}] Credentials will still be generated to the default location: [{default_file}] To use these credentials, unset this environment variable before running your application. """.format(envvar=client.GOOGLE_APPLICATION_CREDENTIALS, override_file=override_file, default_file=config.ADCFilePath())) console_io.PromptContinue(message=message, throw_if_unattended=True, cancel_on_no=True)
def Run(self, args): cred_file = config.ADCFilePath() if not os.path.isfile(cred_file): raise c_exc.BadFileException( 'Application default credentials have not been set up. ' 'Run $gcloud auth application-default login to set it up before ' 'running this command.') creds = client.GoogleCredentials.from_stream(cred_file) if creds.serialization_data['type'] != 'authorized_user': raise c_exc.BadFileException( 'The credentials are not user credentials, quota project ' 'cannot be inserted.') c_creds.ADC(creds).DumpExtendedADCToFile( quota_project=args.quota_project_id) log.status.Print("Updated the quota project in application default " "credentials (ADC) to '{}'.".format( args.quota_project_id))
def Run(self, args): """Revoke Application Default Credentials.""" cred_file = config.ADCFilePath() if not os.path.isfile(cred_file): log.status.Print( 'Application Default Credentials have not been set up, ' 'nothing to revoke.') return creds, _ = c_creds.GetGoogleAuthDefault().load_credentials_from_file( cred_file) if not (c_creds.IsUserAccountCredentials(creds) or c_creds.IsExternalAccountCredentials(creds) or c_creds.IsExternalAccountUserCredentials(creds)): raise c_exc.BadFileException( 'The given credential file is a service account credential, and ' 'cannot be revoked.') if isinstance(creds, google_auth_creds.Credentials): creds = c_google_auth.Credentials.FromGoogleAuthUserCredentials( creds) console_io.PromptContinue( 'You are about to revoke the credentials stored in: [{file}]'. format(file=cred_file), throw_if_unattended=True, cancel_on_no=True) try: c_store.RevokeCredentials(creds) os.remove(cred_file) log.status.Print('Credentials revoked.') except c_store.RevokeError: os.remove(cred_file) log.warning( 'The credentials stored in: [{file}] are not revocable from the ' 'server but have been deleted from the file system.'.format( file=cred_file))
def ADCIsUserAccount(): cred_file = config.ADCFilePath() creds = client.GoogleCredentials.from_stream(cred_file) return creds.serialization_data['type'] == 'authorized_user'
def AssertADCExists(): adc_path = config.ADCFilePath() if not os.path.isfile(adc_path): raise c_exc.BadFileException( 'Application default credentials have not been set up. ' 'Run $ gcloud auth application-default login to set it up first.')
def GetADCAsJson(): """Reads ADC from disk and converts it to a json object.""" if not os.path.isfile(config.ADCFilePath()): return None with files.FileReader(config.ADCFilePath()) as f: return json.load(f)
def __init__(self, credentials): self._credentials = credentials self.adc = _ConvertCredentialsToADC(self._credentials) self.default_adc_file_path = config.ADCFilePath()
def DumpADCToFile(self, file_path=None): """Dumps the credentials to the ADC json file.""" file_path = file_path or config.ADCFilePath() return _DumpADCJsonToFile(self.adc, file_path)