File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/auth.zip
Back
PK ���Z�a�E api_key.pynu �[��� # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Google API key support. This module provides authentication using the `API key`_. .. _API key: https://cloud.google.com/docs/authentication/api-keys/ """ from google.auth import _helpers from google.auth import credentials from google.auth import exceptions class Credentials(credentials.Credentials): """API key credentials. These credentials use API key to provide authorization to applications. """ def __init__(self, token): """ Args: token (str): API key string Raises: ValueError: If the provided API key is not a non-empty string. """ super(Credentials, self).__init__() if not token: raise exceptions.InvalidValue("Token must be a non-empty API key string") self.token = token @property def expired(self): return False @property def valid(self): return True @_helpers.copy_docstring(credentials.Credentials) def refresh(self, request): return def apply(self, headers, token=None): """Apply the API key token to the x-goog-api-key header. Args: headers (Mapping): The HTTP request headers. token (Optional[str]): If specified, overrides the current access token. """ headers["x-goog-api-key"] = token or self.token def before_request(self, request, method, url, headers): """Performs credential-specific before request logic. Refreshes the credentials if necessary, then calls :meth:`apply` to apply the token to the x-goog-api-key header. Args: request (google.auth.transport.Request): The object used to make HTTP requests. method (str): The request's HTTP method or the RPC method being invoked. url (str): The request's URI or the RPC service's URI. headers (Mapping): The request's headers. """ self.apply(headers) PK ���Z�5^�, , _helpers.pynu �[��� # Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper functions for commonly used utilities.""" import base64 import calendar import datetime from email.message import Message import sys import urllib from google.auth import exceptions # The smallest MDS cache used by this library stores tokens until 4 minutes from # expiry. REFRESH_THRESHOLD = datetime.timedelta(minutes=3, seconds=45) def copy_docstring(source_class): """Decorator that copies a method's docstring from another class. Args: source_class (type): The class that has the documented method. Returns: Callable: A decorator that will copy the docstring of the same named method in the source class to the decorated method. """ def decorator(method): """Decorator implementation. Args: method (Callable): The method to copy the docstring to. Returns: Callable: the same method passed in with an updated docstring. Raises: google.auth.exceptions.InvalidOperation: if the method already has a docstring. """ if method.__doc__: raise exceptions.InvalidOperation("Method already has a docstring.") source_method = getattr(source_class, method.__name__) method.__doc__ = source_method.__doc__ return method return decorator def parse_content_type(header_value): """Parse a 'content-type' header value to get just the plain media-type (without parameters). This is done using the class Message from email.message as suggested in PEP 594 (because the cgi is now deprecated and will be removed in python 3.13, see https://peps.python.org/pep-0594/#cgi). Args: header_value (str): The value of a 'content-type' header as a string. Returns: str: A string with just the lowercase media-type from the parsed 'content-type' header. If the provided content-type is not parsable, returns 'text/plain', the default value for textual files. """ m = Message() m["content-type"] = header_value return ( m.get_content_type() ) # Despite the name, actually returns just the media-type def utcnow(): """Returns the current UTC datetime. Returns: datetime: The current time in UTC. """ # We used datetime.utcnow() before, since it's deprecated from python 3.12, # we are using datetime.now(timezone.utc) now. "utcnow()" is offset-native # (no timezone info), but "now()" is offset-aware (with timezone info). # This will cause datetime comparison problem. For backward compatibility, # we need to remove the timezone info. now = datetime.datetime.now(datetime.timezone.utc) now = now.replace(tzinfo=None) return now def datetime_to_secs(value): """Convert a datetime object to the number of seconds since the UNIX epoch. Args: value (datetime): The datetime to convert. Returns: int: The number of seconds since the UNIX epoch. """ return calendar.timegm(value.utctimetuple()) def to_bytes(value, encoding="utf-8"): """Converts a string value to bytes, if necessary. Args: value (Union[str, bytes]): The value to be converted. encoding (str): The encoding to use to convert unicode to bytes. Defaults to "utf-8". Returns: bytes: The original value converted to bytes (if unicode) or as passed in if it started out as bytes. Raises: google.auth.exceptions.InvalidValue: If the value could not be converted to bytes. """ result = value.encode(encoding) if isinstance(value, str) else value if isinstance(result, bytes): return result else: raise exceptions.InvalidValue( "{0!r} could not be converted to bytes".format(value) ) def from_bytes(value): """Converts bytes to a string value, if necessary. Args: value (Union[str, bytes]): The value to be converted. Returns: str: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. Raises: google.auth.exceptions.InvalidValue: If the value could not be converted to unicode. """ result = value.decode("utf-8") if isinstance(value, bytes) else value if isinstance(result, str): return result else: raise exceptions.InvalidValue( "{0!r} could not be converted to unicode".format(value) ) def update_query(url, params, remove=None): """Updates a URL's query parameters. Replaces any current values if they are already present in the URL. Args: url (str): The URL to update. params (Mapping[str, str]): A mapping of query parameter keys to values. remove (Sequence[str]): Parameters to remove from the query string. Returns: str: The URL with updated query parameters. Examples: >>> url = 'http://example.com?a=1' >>> update_query(url, {'a': '2'}) http://example.com?a=2 >>> update_query(url, {'b': '3'}) http://example.com?a=1&b=3 >> update_query(url, {'b': '3'}, remove=['a']) http://example.com?b=3 """ if remove is None: remove = [] # Split the URL into parts. parts = urllib.parse.urlparse(url) # Parse the query string. query_params = urllib.parse.parse_qs(parts.query) # Update the query parameters with the new parameters. query_params.update(params) # Remove any values specified in remove. query_params = { key: value for key, value in query_params.items() if key not in remove } # Re-encoded the query string. new_query = urllib.parse.urlencode(query_params, doseq=True) # Unsplit the url. new_parts = parts._replace(query=new_query) return urllib.parse.urlunparse(new_parts) def scopes_to_string(scopes): """Converts scope value to a string suitable for sending to OAuth 2.0 authorization servers. Args: scopes (Sequence[str]): The sequence of scopes to convert. Returns: str: The scopes formatted as a single string. """ return " ".join(scopes) def string_to_scopes(scopes): """Converts stringifed scopes value to a list. Args: scopes (Union[Sequence, str]): The string of space-separated scopes to convert. Returns: Sequence(str): The separated scopes. """ if not scopes: return [] return scopes.split(" ") def padded_urlsafe_b64decode(value): """Decodes base64 strings lacking padding characters. Google infrastructure tends to omit the base64 padding characters. Args: value (Union[str, bytes]): The encoded value. Returns: bytes: The decoded value """ b64string = to_bytes(value) padded = b64string + b"=" * (-len(b64string) % 4) return base64.urlsafe_b64decode(padded) def unpadded_urlsafe_b64encode(value): """Encodes base64 strings removing any padding characters. `rfc 7515`_ defines Base64url to NOT include any padding characters, but the stdlib doesn't do that by default. _rfc7515: https://tools.ietf.org/html/rfc7515#page-6 Args: value (Union[str|bytes]): The bytes-like value to encode Returns: Union[str|bytes]: The encoded value """ return base64.urlsafe_b64encode(value).rstrip(b"=") def is_python_3(): """Check if the Python interpreter is Python 2 or 3. Returns: bool: True if the Python interpreter is Python 3 and False otherwise. """ return sys.version_info > (3, 0) PK ���ZèG 7- 7- _default_async.pynu �[��� # Copyright 2020 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Application default credentials. Implements application default credentials and project ID detection. """ import io import json import os from google.auth import _default from google.auth import environment_vars from google.auth import exceptions def load_credentials_from_file(filename, scopes=None, quota_project_id=None): """Loads Google credentials from a file. The credentials file must be a service account key or stored authorized user credentials. Args: filename (str): The full path to the credentials file. scopes (Optional[Sequence[str]]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary quota_project_id (Optional[str]): The project ID used for quota and billing. Returns: Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded credentials and the project ID. Authorized user credentials do not have the project ID information. Raises: google.auth.exceptions.DefaultCredentialsError: if the file is in the wrong format or is missing. """ if not os.path.exists(filename): raise exceptions.DefaultCredentialsError( "File {} was not found.".format(filename) ) with io.open(filename, "r") as file_obj: try: info = json.load(file_obj) except ValueError as caught_exc: new_exc = exceptions.DefaultCredentialsError( "File {} is not a valid json file.".format(filename), caught_exc ) raise new_exc from caught_exc # The type key should indicate that the file is either a service account # credentials file or an authorized user credentials file. credential_type = info.get("type") if credential_type == _default._AUTHORIZED_USER_TYPE: from google.oauth2 import _credentials_async as credentials try: credentials = credentials.Credentials.from_authorized_user_info( info, scopes=scopes ) except ValueError as caught_exc: msg = "Failed to load authorized user credentials from {}".format(filename) new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) raise new_exc from caught_exc if quota_project_id: credentials = credentials.with_quota_project(quota_project_id) if not credentials.quota_project_id: _default._warn_about_problematic_credentials(credentials) return credentials, None elif credential_type == _default._SERVICE_ACCOUNT_TYPE: from google.oauth2 import _service_account_async as service_account try: credentials = service_account.Credentials.from_service_account_info( info, scopes=scopes ).with_quota_project(quota_project_id) except ValueError as caught_exc: msg = "Failed to load service account credentials from {}".format(filename) new_exc = exceptions.DefaultCredentialsError(msg, caught_exc) raise new_exc from caught_exc return credentials, info.get("project_id") else: raise exceptions.DefaultCredentialsError( "The file {file} does not have a valid type. " "Type is {type}, expected one of {valid_types}.".format( file=filename, type=credential_type, valid_types=_default._VALID_TYPES ) ) def _get_gcloud_sdk_credentials(quota_project_id=None): """Gets the credentials and project ID from the Cloud SDK.""" from google.auth import _cloud_sdk # Check if application default credentials exist. credentials_filename = _cloud_sdk.get_application_default_credentials_path() if not os.path.isfile(credentials_filename): return None, None credentials, project_id = load_credentials_from_file( credentials_filename, quota_project_id=quota_project_id ) if not project_id: project_id = _cloud_sdk.get_project_id() return credentials, project_id def _get_explicit_environ_credentials(quota_project_id=None): """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment variable.""" from google.auth import _cloud_sdk cloud_sdk_adc_path = _cloud_sdk.get_application_default_credentials_path() explicit_file = os.environ.get(environment_vars.CREDENTIALS) if explicit_file is not None and explicit_file == cloud_sdk_adc_path: # Cloud sdk flow calls gcloud to fetch project id, so if the explicit # file path is cloud sdk credentials path, then we should fall back # to cloud sdk flow, otherwise project id cannot be obtained. return _get_gcloud_sdk_credentials(quota_project_id=quota_project_id) if explicit_file is not None: credentials, project_id = load_credentials_from_file( os.environ[environment_vars.CREDENTIALS], quota_project_id=quota_project_id ) return credentials, project_id else: return None, None def _get_gae_credentials(): """Gets Google App Engine App Identity credentials and project ID.""" # While this library is normally bundled with app_engine, there are # some cases where it's not available, so we tolerate ImportError. return _default._get_gae_credentials() def _get_gce_credentials(request=None): """Gets credentials and project ID from the GCE Metadata Service.""" # Ping requires a transport, but we want application default credentials # to require no arguments. So, we'll use the _http_client transport which # uses http.client. This is only acceptable because the metadata server # doesn't do SSL and never requires proxies. # While this library is normally bundled with compute_engine, there are # some cases where it's not available, so we tolerate ImportError. return _default._get_gce_credentials(request) def default_async(scopes=None, request=None, quota_project_id=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (google.auth.transport.Request): An object used to make HTTP requests. This is used to detect whether the application is running on Compute Engine. If not specified, then it will use the standard library http client to make requests. quota_project_id (Optional[str]): The project ID used for quota and billing. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth._credentials_async import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required(credentials, scopes) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _default._LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id raise exceptions.DefaultCredentialsError(_default._CLOUD_SDK_MISSING_CREDENTIALS) PK ���Znr\_� � _credentials_async.pynu �[��� # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Interfaces for credentials.""" import abc import inspect from google.auth import credentials class Credentials(credentials.Credentials, metaclass=abc.ABCMeta): """Async inherited credentials class from google.auth.credentials. The added functionality is the before_request call which requires async/await syntax. All credentials have a :attr:`token` that is used for authentication and may also optionally set an :attr:`expiry` to indicate when the token will no longer be valid. Most credentials will be :attr:`invalid` until :meth:`refresh` is called. Credentials can do this automatically before the first HTTP request in :meth:`before_request`. Although the token and expiration will change as the credentials are :meth:`refreshed <refresh>` and used, credentials should be considered immutable. Various credentials will accept configuration such as private keys, scopes, and other options. These options are not changeable after construction. Some classes will provide mechanisms to copy the credentials with modifications such as :meth:`ScopedCredentials.with_scopes`. """ async def before_request(self, request, method, url, headers): """Performs credential-specific before request logic. Refreshes the credentials if necessary, then calls :meth:`apply` to apply the token to the authentication header. Args: request (google.auth.transport.Request): The object used to make HTTP requests. method (str): The request's HTTP method or the RPC method being invoked. url (str): The request's URI or the RPC service's URI. headers (Mapping): The request's headers. """ # pylint: disable=unused-argument # (Subclasses may use these arguments to ascertain information about # the http request.) if not self.valid: if inspect.iscoroutinefunction(self.refresh): await self.refresh(request) else: self.refresh(request) self.apply(headers) class CredentialsWithQuotaProject(credentials.CredentialsWithQuotaProject): """Abstract base for credentials supporting ``with_quota_project`` factory""" class AnonymousCredentials(credentials.AnonymousCredentials, Credentials): """Credentials that do not provide any authentication information. These are useful in the case of services that support anonymous access or local service emulators that do not use credentials. This class inherits from the sync anonymous credentials file, but is kept if async credentials is initialized and we would like anonymous credentials. """ class ReadOnlyScoped(credentials.ReadOnlyScoped, metaclass=abc.ABCMeta): """Interface for credentials whose scopes can be queried. OAuth 2.0-based credentials allow limiting access using scopes as described in `RFC6749 Section 3.3`_. If a credential class implements this interface then the credentials either use scopes in their implementation. Some credentials require scopes in order to obtain a token. You can check if scoping is necessary with :attr:`requires_scopes`:: if credentials.requires_scopes: # Scoping is required. credentials = _credentials_async.with_scopes(scopes=['one', 'two']) Credentials that require scopes must either be constructed with scopes:: credentials = SomeScopedCredentials(scopes=['one', 'two']) Or must copy an existing instance using :meth:`with_scopes`:: scoped_credentials = _credentials_async.with_scopes(scopes=['one', 'two']) Some credentials have scopes but do not allow or require scopes to be set, these credentials can be used as-is. .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3 """ class Scoped(credentials.Scoped): """Interface for credentials whose scopes can be replaced while copying. OAuth 2.0-based credentials allow limiting access using scopes as described in `RFC6749 Section 3.3`_. If a credential class implements this interface then the credentials either use scopes in their implementation. Some credentials require scopes in order to obtain a token. You can check if scoping is necessary with :attr:`requires_scopes`:: if credentials.requires_scopes: # Scoping is required. credentials = _credentials_async.create_scoped(['one', 'two']) Credentials that require scopes must either be constructed with scopes:: credentials = SomeScopedCredentials(scopes=['one', 'two']) Or must copy an existing instance using :meth:`with_scopes`:: scoped_credentials = credentials.with_scopes(scopes=['one', 'two']) Some credentials have scopes but do not allow or require scopes to be set, these credentials can be used as-is. .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3 """ def with_scopes_if_required(credentials, scopes): """Creates a copy of the credentials with scopes if scoping is required. This helper function is useful when you do not know (or care to know) the specific type of credentials you are using (such as when you use :func:`google.auth.default`). This function will call :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if the credentials require scoping. Otherwise, it will return the credentials as-is. Args: credentials (google.auth.credentials.Credentials): The credentials to scope if necessary. scopes (Sequence[str]): The list of scopes to use. Returns: google.auth._credentials_async.Credentials: Either a new set of scoped credentials, or the passed in credentials instance if no scoping was required. """ if isinstance(credentials, Scoped) and credentials.requires_scopes: return credentials.with_scopes(scopes) else: return credentials class Signing(credentials.Signing, metaclass=abc.ABCMeta): """Interface for credentials that can cryptographically sign messages.""" PK ���Z��v�? ? _exponential_backoff.pynu �[��� # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import random import time # The default amount of retry attempts _DEFAULT_RETRY_TOTAL_ATTEMPTS = 3 # The default initial backoff period (1.0 second). _DEFAULT_INITIAL_INTERVAL_SECONDS = 1.0 # The default randomization factor (0.1 which results in a random period ranging # between 10% below and 10% above the retry interval). _DEFAULT_RANDOMIZATION_FACTOR = 0.1 # The default multiplier value (2 which is 100% increase per back off). _DEFAULT_MULTIPLIER = 2.0 """Exponential Backoff Utility This is a private module that implements the exponential back off algorithm. It can be used as a utility for code that needs to retry on failure, for example an HTTP request. """ class ExponentialBackoff: """An exponential backoff iterator. This can be used in a for loop to perform requests with exponential backoff. Args: total_attempts Optional[int]: The maximum amount of retries that should happen. The default value is 3 attempts. initial_wait_seconds Optional[int]: The amount of time to sleep in the first backoff. This parameter should be in seconds. The default value is 1 second. randomization_factor Optional[float]: The amount of jitter that should be in each backoff. For example, a value of 0.1 will introduce a jitter range of 10% to the current backoff period. The default value is 0.1. multiplier Optional[float]: The backoff multipler. This adjusts how much each backoff will increase. For example a value of 2.0 leads to a 200% backoff on each attempt. If the initial_wait is 1.0 it would look like this sequence [1.0, 2.0, 4.0, 8.0]. The default value is 2.0. """ def __init__( self, total_attempts=_DEFAULT_RETRY_TOTAL_ATTEMPTS, initial_wait_seconds=_DEFAULT_INITIAL_INTERVAL_SECONDS, randomization_factor=_DEFAULT_RANDOMIZATION_FACTOR, multiplier=_DEFAULT_MULTIPLIER, ): self._total_attempts = total_attempts self._initial_wait_seconds = initial_wait_seconds self._current_wait_in_seconds = self._initial_wait_seconds self._randomization_factor = randomization_factor self._multiplier = multiplier self._backoff_count = 0 def __iter__(self): self._backoff_count = 0 self._current_wait_in_seconds = self._initial_wait_seconds return self def __next__(self): if self._backoff_count >= self._total_attempts: raise StopIteration self._backoff_count += 1 jitter_variance = self._current_wait_in_seconds * self._randomization_factor jitter = random.uniform( self._current_wait_in_seconds - jitter_variance, self._current_wait_in_seconds + jitter_variance, ) time.sleep(jitter) self._current_wait_in_seconds *= self._multiplier return self._backoff_count @property def total_attempts(self): """The total amount of backoff attempts that will be made.""" return self._total_attempts @property def backoff_count(self): """The current amount of backoff attempts that have been made.""" return self._backoff_count PK ���Z�|��a a iam.pynu �[��� # Copyright 2017 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tools for using the Google `Cloud Identity and Access Management (IAM) API`_'s auth-related functionality. .. _Cloud Identity and Access Management (IAM) API: https://cloud.google.com/iam/docs/ """ import base64 import http.client as http_client import json from google.auth import _helpers from google.auth import crypt from google.auth import exceptions _IAM_SCOPE = ["https://www.googleapis.com/auth/iam"] _IAM_ENDPOINT = ( "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/{}:generateAccessToken" ) _IAM_SIGN_ENDPOINT = ( "https://iamcredentials.googleapis.com/v1/projects/-" + "/serviceAccounts/{}:signBlob" ) _IAM_IDTOKEN_ENDPOINT = ( "https://iamcredentials.googleapis.com/v1/" + "projects/-/serviceAccounts/{}:generateIdToken" ) class Signer(crypt.Signer): """Signs messages using the IAM `signBlob API`_. This is useful when you need to sign bytes but do not have access to the credential's private key file. .. _signBlob API: https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts /signBlob """ def __init__(self, request, credentials, service_account_email): """ Args: request (google.auth.transport.Request): The object used to make HTTP requests. credentials (google.auth.credentials.Credentials): The credentials that will be used to authenticate the request to the IAM API. The credentials must have of one the following scopes: - https://www.googleapis.com/auth/iam - https://www.googleapis.com/auth/cloud-platform service_account_email (str): The service account email identifying which service account to use to sign bytes. Often, this can be the same as the service account email in the given credentials. """ self._request = request self._credentials = credentials self._service_account_email = service_account_email def _make_signing_request(self, message): """Makes a request to the API signBlob API.""" message = _helpers.to_bytes(message) method = "POST" url = _IAM_SIGN_ENDPOINT.format(self._service_account_email) headers = {"Content-Type": "application/json"} body = json.dumps( {"payload": base64.b64encode(message).decode("utf-8")} ).encode("utf-8") self._credentials.before_request(self._request, method, url, headers) response = self._request(url=url, method=method, body=body, headers=headers) if response.status != http_client.OK: raise exceptions.TransportError( "Error calling the IAM signBlob API: {}".format(response.data) ) return json.loads(response.data.decode("utf-8")) @property def key_id(self): """Optional[str]: The key ID used to identify this private key. .. warning:: This is always ``None``. The key ID used by IAM can not be reliably determined ahead of time. """ return None @_helpers.copy_docstring(crypt.Signer) def sign(self, message): response = self._make_signing_request(message) return base64.b64decode(response["signedBlob"]) PK ���Z[�`� � environment_vars.pynu �[��� # Copyright 2016 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Environment variables used by :mod:`google.auth`.""" PROJECT = "GOOGLE_CLOUD_PROJECT" """Environment variable defining default project. This used by :func:`google.auth.default` to explicitly set a project ID. This environment variable is also used by the Google Cloud Python Library. """ LEGACY_PROJECT = "GCLOUD_PROJECT" """Previously used environment variable defining the default project. This environment variable is used instead of the current one in some situations (such as Google App Engine). """ GOOGLE_CLOUD_QUOTA_PROJECT = "GOOGLE_CLOUD_QUOTA_PROJECT" """Environment variable defining the project to be used for quota and billing.""" CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS" """Environment variable defining the location of Google application default credentials.""" # The environment variable name which can replace ~/.config if set. CLOUD_SDK_CONFIG_DIR = "CLOUDSDK_CONFIG" """Environment variable defines the location of Google Cloud SDK's config files.""" # These two variables allow for customization of the addresses used when # contacting the GCE metadata service. GCE_METADATA_HOST = "GCE_METADATA_HOST" """Environment variable providing an alternate hostname or host:port to be used for GCE metadata requests. This environment variable was originally named GCE_METADATA_ROOT. The system will check this environemnt variable first; should there be no value present, the system will fall back to the old variable. """ GCE_METADATA_ROOT = "GCE_METADATA_ROOT" """Old environment variable for GCE_METADATA_HOST.""" GCE_METADATA_IP = "GCE_METADATA_IP" """Environment variable providing an alternate ip:port to be used for ip-only GCE metadata requests.""" GOOGLE_API_USE_CLIENT_CERTIFICATE = "GOOGLE_API_USE_CLIENT_CERTIFICATE" """Environment variable controlling whether to use client certificate or not. The default value is false. Users have to explicitly set this value to true in order to use client certificate to establish a mutual TLS channel.""" LEGACY_APPENGINE_RUNTIME = "APPENGINE_RUNTIME" """Gen1 environment variable defining the App Engine Runtime. Used to distinguish between GAE gen1 and GAE gen2+. """ # AWS environment variables used with AWS workload identity pools to retrieve # AWS security credentials and the AWS region needed to create a serialized # signed requests to the AWS STS GetCalledIdentity API that can be exchanged # for a Google access tokens via the GCP STS endpoint. # When not available the AWS metadata server is used to retrieve these values. AWS_ACCESS_KEY_ID = "AWS_ACCESS_KEY_ID" AWS_SECRET_ACCESS_KEY = "AWS_SECRET_ACCESS_KEY" AWS_SESSION_TOKEN = "AWS_SESSION_TOKEN" AWS_REGION = "AWS_REGION" AWS_DEFAULT_REGION = "AWS_DEFAULT_REGION" PK ���Zx�\ \ ) __pycache__/_oauth2client.cpython-310.pycnu �[��� o �h� � @ s d Z ddlmZ ddlmZ ddlZddlZddlZddl Zzddl ZddlZddl ZW n ey= Z zed�e�dZ[ww zddlZdZW n eyQ dZY nw dZd d � Zdd� Zd d� Zdd� ZejjeejjeejjeejjeejjjeiZ er�ee ejj!j<