Example #1
0
    def __init__(self, user_name=None, password=None):
        self._endpoint = None
        self._url = None
        self._auth_string = None
        self._auto_renew = True
        self._disable_ssl_hook = False
        self._is_closed = False
        # The base path for security related services.
        self._base_path = HttpConstants.KV_SECURITY_PATH
        # The login token expiration time.
        self._expiration_time = 0
        self._logger = None
        self._logutils = LogUtils(self._logger)
        self._sess = Session()
        self._request_utils = borneo.http.RequestUtils(self._sess,
                                                       self._logutils)
        self._lock = Lock()
        self._timer = None
        self.lock = Lock()

        if user_name is None and password is None:
            # Used to access to a store without security enabled.
            self._is_secure = False
        else:
            if user_name is None or password is None:
                raise IllegalArgumentException('Invalid input arguments.')
            CheckValue.check_str(user_name, 'user_name')
            CheckValue.check_str(password, 'password')
            self._is_secure = True
            self._user_name = user_name
            self._password = password
 def set_service_url(self, config):
     service_url = config.get_service_url()
     if service_url is None:
         raise IllegalArgumentException('Must set service URL first.')
     self._service_url = (service_url.scheme + '://' +
                          service_url.hostname + '/' +
                          HttpConstants.NOSQL_DATA_PATH)
     return self
 def get_authorization_string(self, request=None):
     if self._service_url is None:
         raise IllegalArgumentException(
             'Unable to find service url, use set_service_url to load ' +
             'from NoSQLHandleConfig')
     sig_details = self._get_signature_details()
     if sig_details is not None:
         return sig_details['authorization']
Example #4
0
 def __get_idcs_url(self, properties_file):
     # Methods used to fetch IDCS-related properties from given file.
     idcs_url = PropertiesCredentialsProvider.get_property_from_file(
         properties_file, DefaultAccessTokenProvider._IDCS_URL_PROP)
     if idcs_url is None:
         raise IllegalArgumentException(
             'Must specify IDCS URL in IDCS properties file.')
     return idcs_url
Example #5
0
 def get_authorization_string(self, request=None):
     if request is not None and not isinstance(request, Request):
         raise IllegalArgumentException(
             'get_authorization_string requires an instance of Request or '
             + 'None as parameter.')
     if not self._is_secure or self._is_closed:
         return None
     # If there is no cached auth string, re-authentication to retrieve the
     # login token and generate the auth string.
     if self._auth_string is None:
         self.bootstrap_login()
     return self._auth_string
Example #6
0
    def set_properties_file(self, file_path):
        """
        Sets the properties file to use to a non-default path.

        :param file_path: a path to the file to use.
        :returns: self.
        """
        CheckValue.check_str(file_path, 'file_path')
        if not path.exists(file_path):
            raise IllegalArgumentException('Path: \'' + file_path +
                                           '\' not found.')
        self.__properties_file = file_path
        return self
Example #7
0
    def set_endpoint(self, endpoint):
        """
        Sets the endpoint of the on-prem proxy.

        :param endpoint: the endpoint.
        :type endpoint: str
        :returns: self.
        :raises IllegalArgumentException: raises the exception if endpoint is
            not a string.
        """
        CheckValue.check_str(endpoint, 'endpoint')
        self._endpoint = endpoint
        self._url = NoSQLHandleConfig.create_url(endpoint, '')
        if self._is_secure and self._url.scheme.lower() != 'https':
            raise IllegalArgumentException(
                'StoreAccessTokenProvider requires use of https.')
        return self
 def set_required_headers(self, request, auth_string, headers):
     sig_details = self._get_signature_details()
     if sig_details is None:
         return
     headers[HttpConstants.AUTHORIZATION] = sig_details['authorization']
     headers[HttpConstants.DATE] = sig_details['date']
     compartment = request.get_compartment()
     if compartment is None:
         # If request doesn't has compartment, set the tenant id as the
         # default compartment, which is the root compartment in IAM if using
         # user principal. If using an instance principal this value is
         # None.
         compartment = self._get_tenant_ocid()
     if compartment is not None:
         headers[HttpConstants.REQUEST_COMPARTMENT_ID] = compartment
     else:
         raise IllegalArgumentException(
             'Compartment is None. When authenticating using an Instance ' +
             'Principal the compartment for the operation must be specified.'
         )
Example #9
0
 def _handle_token_error_response(self, response_code, content):
     if response_code >= codes.server_error:
         self._logutils.log_info(
             'Error acquiring access token, expected to retry, error ' +
             'response: ' + content + ', status code: ' + str(response_code))
         raise RequestTimeoutException(
             'Error acquiring access token, expected to retry, error ' +
             'response: ' + content + ', status code: ' + str(response_code))
     elif response_code == codes.bad and content is None:
         # IDCS doesn't return error message in case of credentials has
         # invalid URL encoded characters.
         raise IllegalArgumentException(
             'Error acquiring access token, status code: ' +
             str(response_code) +
             ', CredentialsProvider supplies invalid credentials')
     else:
         raise InvalidAuthorizationException(
             'Error acquiring access token from Identity Cloud Service. ' +
             'IDCS error response: ' + content + ', status code: ' +
             str(response_code))
Example #10
0
    def get_authorization_string(self, request=None):
        """
        Returns IDCS ATs appropriate for the operation.

        :param request: the request that client attempts to issue.
        :type request: Request
        :returns: authorization string that can be present by client, which
            indicates this client is authorized to issue the specified request.
        :rtype: str
        """
        if not isinstance(request, Request):
            raise IllegalArgumentException(
                'get_authorization_string requires an instance of Request as ' +
                'parameter.')
        need_account_at = self._need_account_at(request)
        key = (AccessTokenProvider.ACCOUNT_AT_KEY if need_account_at else
               AccessTokenProvider.SERVICE_AT_KEY)
        auth_string = self._at_cache.get(key)
        if auth_string is None:
            auth_string = self._get_at(key)
        return auth_string
Example #11
0
 def __init__(self, duration_seconds=MAX_ENTRY_LIFE_TIME,
              refresh_ahead=DEFAULT_REFRESH_AHEAD):
     """
     Creates an AccessTokenProvider with the specified cache duration. The
     duration specifies the lifetime of an AT in the cache. Setting the
     duration too large runs the risk that client requests may stall because
     a current token is not available or expired. Setting the duration too
     small means that there may be unnecessary overhead due to token renewal.
     """
     self._timer = None
     # Refresh time before AT expired from cache.
     self._refresh_ahead_s = refresh_ahead
     CheckValue.check_int_gt_zero(duration_seconds, 'duration_seconds')
     if duration_seconds > AccessTokenProvider.MAX_ENTRY_LIFE_TIME:
         raise IllegalArgumentException(
             'Access token cannot be cached longer than ' +
             str(AccessTokenProvider.MAX_ENTRY_LIFE_TIME) + ' seconds')
     self._duration_seconds = duration_seconds
     self._at_cache = Memoize(self._duration_seconds)
     # AT refresh interval, if zero, no refresh will be scheduled.
     self._refresh_interval_s = (
         self._duration_seconds - self._refresh_ahead_s if
         self._duration_seconds > self._refresh_ahead_s else 0)
Example #12
0
 def validate_auth_string(self, auth_string):
     if self._is_secure and auth_string is None:
         raise IllegalArgumentException(
             'Secured StoreAccessProvider requires a non-none string.')
Example #13
0
 def __get_client_creds(self):
     creds = self.__creds_provider.get_oauth_client_credentials()
     if creds is None:
         raise IllegalArgumentException(
             'OAuth client credentials unavailable.')
     return creds
Example #14
0
 def set_service_host(self, config):
     service_url = config.get_service_url()
     if service_url is None:
         raise IllegalArgumentException('Must set service URL first.')
     self._service_host = service_url.hostname
     return self
    def __init__(self,
                 provider=None,
                 config_file=None,
                 profile_name=None,
                 tenant_id=None,
                 user_id=None,
                 fingerprint=None,
                 private_key=None,
                 pass_phrase=None,
                 region=None,
                 duration_seconds=MAX_ENTRY_LIFE_TIME,
                 refresh_ahead=DEFAULT_REFRESH_AHEAD):
        """
        The SignatureProvider that generates and caches request signature.
        """
        #
        # This class depends on the oci package
        #
        if oci is None:
            raise ImportError('Package "oci" is required; please install.')

        CheckValue.check_int_gt_zero(duration_seconds, 'duration_seconds')
        CheckValue.check_int_gt_zero(refresh_ahead, 'refresh_ahead')
        if duration_seconds > SignatureProvider.MAX_ENTRY_LIFE_TIME:
            raise IllegalArgumentException(
                'Access token cannot be cached longer than ' +
                str(SignatureProvider.MAX_ENTRY_LIFE_TIME) + ' seconds.')

        self._region = None
        if provider is not None:
            if not isinstance(
                    provider,
                (oci.signer.Signer, oci.auth.signers.SecurityTokenSigner)):
                raise IllegalArgumentException(
                    'provider should be an instance of oci.signer.Signer or ' +
                    'oci.auth.signers.SecurityTokenSigner.')
            self._provider = provider
            try:
                region_id = provider.region
            except AttributeError:
                region_id = None
            if region_id is not None:
                self._region = Regions.from_region_id(region_id)
        elif (tenant_id is None or user_id is None or fingerprint is None
              or private_key is None):
            CheckValue.check_str(config_file, 'config_file', True)
            CheckValue.check_str(profile_name, 'profile_name', True)
            if config_file is None and profile_name is None:
                # Use default user profile and private key from default path of
                # configuration file ~/.oci/config.
                config = oci.config.from_file()
            elif config_file is None and profile_name is not None:
                # Use user profile with given profile name and private key from
                # default path of configuration file ~/.oci/config.
                config = oci.config.from_file(profile_name=profile_name)
            elif config_file is not None and profile_name is None:
                # Use user profile with default profile name and private key
                # from specified configuration file.
                config = oci.config.from_file(file_location=config_file)
            else:  # config_file is not None and profile_name is not None
                # Use user profile with given profile name and private key from
                # specified configuration file.
                config = oci.config.from_file(file_location=config_file,
                                              profile_name=profile_name)
            self._provider = oci.signer.Signer(config['tenancy'],
                                               config['user'],
                                               config['fingerprint'],
                                               config['key_file'],
                                               config.get('pass_phrase'),
                                               config.get('key_content'))
            region_id = config.get('region')
            if region_id is not None:
                self._provider.region = region_id
                self._region = Regions.from_region_id(region_id)
        else:
            CheckValue.check_str(tenant_id, 'tenant_id')
            CheckValue.check_str(user_id, 'user_id')
            CheckValue.check_str(fingerprint, 'fingerprint')
            CheckValue.check_str(private_key, 'private_key')
            CheckValue.check_str(pass_phrase, 'pass_phrase', True)
            if path.isfile(private_key):
                key_file = private_key
                key_content = None
            else:
                key_file = None
                key_content = private_key
            self._provider = oci.signer.Signer(tenant_id, user_id, fingerprint,
                                               key_file, pass_phrase,
                                               key_content)
            if region is not None:
                if not isinstance(region, Region):
                    raise IllegalArgumentException(
                        'region must be an instance of an instance of Region.')
                self._provider.region = region.get_region_id()
                self._region = region

        self._signature_cache = Memoize(duration_seconds)
        self._refresh_interval_s = (duration_seconds - refresh_ahead
                                    if duration_seconds > refresh_ahead else 0)

        # Refresh timer.
        self._timer = None
        self._service_url = None
        self._logger = None
        self._logutils = LogUtils()
        self._sess = Session()
        self._request_utils = RequestUtils(self._sess, self._logutils)
Example #16
0
 def __ensure_creds_provider(self):
     if self.__creds_provider is None:
         raise IllegalArgumentException('CredentialsProvider unavailable.')
Example #17
0
 def __is_credentials_provider(self, provider):
     if (provider is not None
             and not isinstance(provider, CredentialsProvider)):
         raise IllegalArgumentException('provider must be an instance of ' +
                                        'CredentialsProvider.')
Example #18
0
 def __get_user_creds(self):
     user_creds = self.__creds_provider.get_user_credentials()
     if user_creds is None:
         raise IllegalArgumentException('User credentials unavailable.')
     return user_creds