Exemple #1
0
 def parse_error(self):
     if self.status == httplib.FOUND and '/api/error' in self.body:
         # Hacky, but DigitalOcean error responses are awful
         raise InvalidCredsError(self.body)
     elif self.status == httplib.UNAUTHORIZED:
         body = self.parse_body()
         raise InvalidCredsError(body['message'])
Exemple #2
0
 def parse_error(self):
     if int(self.status) == 401:
         if not self.body:
             raise InvalidCredsError(str(self.status) + ': ' + self.error)
         else:
             raise InvalidCredsError(self.body)
     return self.body
Exemple #3
0
    def parse_error(self):
        if self.status == httplib.FOUND and '/api/error' in self.body:
            # Hacky, but DigitalOcean error responses are awful
            raise InvalidCredsError(self.body)
        elif self.status == httplib.UNAUTHORIZED:
            body = self.parse_body()
            raise InvalidCredsError(body['message'])
        else:
            body = self.parse_body()

            if 'error_message' in body:
                error = '%s (code: %s)' % (body['error_message'], self.status)
            else:
                error = body
            return error
Exemple #4
0
    def _fetch_oauth_token(self):
        body = json.dumps({'client_id': self.user_id, 'grant_type': 'none'})

        authorization = 'Basic ' + str(
            base64.encodestring(b('%s:%s' %
                                  (self.user_id, self.key)))).rstrip()

        self.connect()

        headers = {
            'Host': self.host,
            'User-Agent': self._user_agent(),
            'Authorization': authorization,
            'Content-Type': 'application/json',
            'Content-Length': str(len(body))
        }

        response = self.connection.request(method='POST',
                                           url='/token',
                                           body=body,
                                           headers=headers)

        response = self.connection.getresponse()

        if response.status == httplib.OK:
            return json.loads(response.read())['access_token']
        else:
            responseCls = BrightboxResponse(response=response, connection=self)
            message = responseCls.parse_error()
            raise InvalidCredsError(message)
Exemple #5
0
    def authenticate_2_0_with_body(self, reqbody):
        resp = self.request('/v2.0/tokens/',
                    data=reqbody,
                    headers={'Content-Type':'application/json'},
                    method='POST')
        if resp.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError()
        elif resp.status not in [httplib.OK, httplib.NON_AUTHORITATIVE_INFORMATION]:
            raise MalformedResponseError('Malformed response',
                    body='code: %s body: %s' % (resp.status, resp.body),
                    driver=self.driver)
        else:
            try:
                body = json.loads(resp.body)
            except Exception:
                e = sys.exc_info()[1]
                raise MalformedResponseError('Failed to parse JSON', e)

            try:
                access = body['access']
                token = access['token']
                self.auth_token = token['id']
                self.urls = access['serviceCatalog']
            except KeyError:
                e = sys.exc_info()[1]
                raise MalformedResponseError('Auth JSON response is missing required elements', e)
Exemple #6
0
    def parse_error(self):
        if self.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError('Authorization Failed')
        if self.status == httplib.NOT_FOUND:
            raise Exception("The resource you are looking for is not found.")

        return self.body
Exemple #7
0
    def _fetch_oauth_token(self):
        body = json.dumps({"client_id": self.user_id, "grant_type": "none"})

        authorization = (
            "Basic " +
            str(base64_encode_string(b("%s:%s" %
                                       (self.user_id, self.key)))).rstrip())

        self.connect()

        headers = {
            "Host": self.host,
            "User-Agent": self._user_agent(),
            "Authorization": authorization,
            "Content-Type": "application/json",
            "Content-Length": str(len(body)),
        }

        # pylint: disable=assignment-from-no-return
        response = self.connection.request(method="POST",
                                           url="/token",
                                           body=body,
                                           headers=headers)

        if response.status == httplib.OK:
            return json.loads(response.read())["access_token"]
        else:
            responseCls = BrightboxResponse(response=response.getresponse(),
                                            connection=self)
            message = responseCls.parse_error()
            raise InvalidCredsError(message)
Exemple #8
0
    def _authenticate_2_0_with_body(self, reqbody):
        resp = self.request('/v2.0/tokens',
                            data=reqbody,
                            headers={'Content-Type': 'application/json'},
                            method='POST')

        if resp.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError()
        elif resp.status not in [
                httplib.OK, httplib.NON_AUTHORITATIVE_INFORMATION
        ]:
            body = 'code: %s body: %s' % (resp.status, resp.body)
            raise MalformedResponseError('Malformed response',
                                         body=body,
                                         driver=self.driver)
        else:
            body = resp.object

            try:
                access = body['access']
                expires = access['token']['expires']

                self.auth_token = access['token']['id']
                self.auth_token_expires = parse_date(expires)
                self.urls = access['serviceCatalog']
                self.auth_user_info = access.get('user', {})
            except KeyError:
                e = sys.exc_info()[1]
                raise MalformedResponseError(
                    'Auth JSON response is \
                                             missing required elements', e)

        return self
Exemple #9
0
    def authenticate_1_0(self):
        headers = {
            'X-Auth-User': self.user_id,
            'X-Auth-Key': self.key,
        }

        resp = self.request('/v1.0', headers=headers, method='GET')

        if resp.status == httplib.UNAUTHORIZED:
            # HTTP UNAUTHORIZED (401): auth failed
            raise InvalidCredsError()
        elif resp.status not in [httplib.NO_CONTENT, httplib.OK]:
            body = 'code: %s body:%s headers:%s' % (resp.status, resp.body,
                                                    resp.headers)
            raise MalformedResponseError('Malformed response',
                                         body=body,
                                         driver=self.driver)
        else:
            headers = resp.headers
            # emulate the auth 1.1 URL list
            self.urls = {}
            self.urls['cloudServers'] = \
                [{'publicURL': headers.get('x-server-management-url', None)}]
            self.urls['cloudFilesCDN'] = \
                [{'publicURL': headers.get('x-cdn-management-url', None)}]
            self.urls['cloudFiles'] = \
                [{'publicURL': headers.get('x-storage-url', None)}]
            self.auth_token = headers.get('x-auth-token', None)
            self.auth_user_info = None

            if not self.auth_token:
                raise MalformedResponseError('Missing X-Auth-Token in \
                                              response headers')

        return self
Exemple #10
0
    def authenticate_1_1(self):
        reqbody = json.dumps(
            {'credentials': {
                'username': self.user_id,
                'key': self.key
            }})
        resp = self.request("/auth", data=reqbody, headers={}, method='POST')

        if resp.status == httplib.UNAUTHORIZED:
            # HTTP UNAUTHORIZED (401): auth failed
            raise InvalidCredsError()
        elif resp.status != httplib.OK:
            raise MalformedResponseError('Malformed response',
                                         body='code: %s body:%s' %
                                         (resp.status, resp.body),
                                         driver=self.driver)
        else:
            try:
                body = json.loads(resp.body)
            except Exception, e:
                raise MalformedResponseError('Failed to parse JSON', e)
            try:
                self.auth_token = body['auth']['token']['id']
                self.urls = body['auth']['serviceCatalog']
            except KeyError, e:
                raise MalformedResponseError(
                    'Auth JSON response is missing required elements', e)
Exemple #11
0
 def authenticate_2_0(self):
     reqbody = json.dumps({
         'auth': {
             'passwordCredentials': {
                 'username': self.user_id,
                 'password': self.key
             }
         }
     })
     resp = self.request('tokens/',
                         data=reqbody,
                         headers={'Content-Type': 'application/json'},
                         method='POST')
     if resp.status == httplib.UNAUTHORIZED:
         raise InvalidCredsError()
     elif resp.status not in [
             httplib.OK, httplib.NON_AUTHORITATIVE_INFORMATION
     ]:
         raise MalformedResponseError('Malformed response',
                                      body='code: %s body: %s' %
                                      (resp.status, resp.body),
                                      driver=self.driver)
     else:
         try:
             body = json.loads(resp.body)
         except Exception, e:
             raise MalformedResponseError('Failed to parse JSON', e)
         try:
             self.auth_token = body['access']['token']['id']
             self.urls = body['access']['serviceCatalog']
         except KeyError, e:
             raise MalformedResponseError(
                 'Auth JSON response is missing required elements', e)
Exemple #12
0
 def decorated(*args, **kwds):
     for i in range(10):
         try:
             return fn(*args, **kwds)
         except InvalidCredsError as e:
             time.sleep(0.25)
             pass
     raise InvalidCredsError(e)
Exemple #13
0
    def parse_error(self):
        if self.status == 401:
            raise InvalidCredsError(self.body)

        body = super(SlicehostResponse, self).parse_body()
        try:
            return "; ".join([err.text for err in body.findall('error')])
        except ExpatError:
            return self.body
Exemple #14
0
    def _populate_hosts_and_request_paths(self):
        """
        Rackspace uses a separate host for API calls which is only provided
        after an initial authentication request. If we haven't made that
        request yet, do it here. Otherwise, just return the management host.
        """
        if not self.auth_token:
            # Initial connection used for authentication
            conn = self.conn_classes[self.secure](self.auth_host,
                                                  self.port[self.secure])
            conn.request(method='GET',
                         url='/%s' % (AUTH_API_VERSION),
                         headers={
                             'X-Auth-User': self.user_id,
                             'X-Auth-Key': self.key
                         })

            resp = conn.getresponse()

            if resp.status == httplib.NO_CONTENT:
                # HTTP NO CONTENT (204): auth successful
                headers = dict(resp.getheaders())

                try:
                    self.server_url = headers['x-server-management-url']
                    self.storage_url = headers['x-storage-url']
                    self.cdn_management_url = headers['x-cdn-management-url']
                    self.lb_url = self.server_url.replace(
                        "servers", "ord.loadbalancers")
                    self.auth_token = headers['x-auth-token']
                except KeyError, e:
                    # Returned 204 but has missing information in the header, something is wrong
                    raise MalformedResponseError('Malformed response',
                                                 body='Missing header: %s' %
                                                 (str(e)),
                                                 driver=self.driver)
            elif resp.status == httplib.UNAUTHORIZED:
                # HTTP UNAUTHORIZED (401): auth failed
                raise InvalidCredsError()
            else:
                # Any response code != 401 or 204, something is wrong
                raise MalformedResponseError(
                    'Malformed response',
                    body='code: %s body:%s' %
                    (resp.status, ''.join(resp.body.readlines())),
                    driver=self.driver)

            for key in [
                    'server_url', 'storage_url', 'cdn_management_url', 'lb_url'
            ]:
                scheme, server, request_path, param, query, fragment = (
                    urlparse.urlparse(getattr(self, key)))
                # Set host to where we want to make further requests to
                setattr(self, '__%s' % (key), server)
                setattr(self, '__request_path_%s' % (key), request_path)

            conn.close()
Exemple #15
0
    def host(self):
        """
        Rackspace uses a separate host for API calls which is only provided
        after an initial authentication request. If we haven't made that
        request yet, do it here. Otherwise, just return the management host.
        """
        if not self.__host:
            # Initial connection used for authentication
            conn = self.conn_classes[self.secure](self.auth_host,
                                                  self.port[self.secure])
            conn.request(method='GET',
                         url='/%s' % (AUTH_API_VERSION),
                         headers={
                             'X-Auth-User': self.user_id,
                             'X-Auth-Key': self.key
                         })

            resp = conn.getresponse()

            if resp.status != httplib.NO_CONTENT:
                raise InvalidCredsError()

            headers = dict(resp.getheaders())

            try:
                self.server_url = headers['x-server-management-url']
                self.storage_url = headers['x-storage-url']
                self.cdn_management_url = headers['x-cdn-management-url']
                self.auth_token = headers['x-auth-token']
            except KeyError:
                raise InvalidCredsError()

            scheme, server, self.request_path, param, query, fragment = (
                urlparse.urlparse(getattr(self, self._url_key)))

            if scheme is "https" and self.secure is not True:
                raise InvalidCredsError()

            # Set host to where we want to make further requests to;
            self.__host = server
            conn.close()

        return self.__host
Exemple #16
0
 def parse_error(self):
     if self.status == httplib.UNAUTHORIZED:
         body = self.parse_body()
         raise InvalidCredsError(body['message'])
     else:
         body = self.parse_body()
         if 'message' in body:
             error = '%s (code: %s)' % (body['message'], self.status)
         else:
             error = body
         return error
Exemple #17
0
    def parse_error(self):
        data = self.parse_body()

        if self.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError("%(code)s:%(message)s" % (data["error"]))
        elif self.status == httplib.PRECONDITION_FAILED:
            raise HostVirtualException(data["error"]["code"], data["error"]["message"])
        elif self.status == httplib.NOT_FOUND:
            raise HostVirtualException(data["error"]["code"], data["error"]["message"])

        return self.body
Exemple #18
0
    def parse_error(self):
        response = super(BrightboxResponse, self).parse_body()

        if "error" in response:
            if response["error"] in ["invalid_client", "unauthorized_client"]:
                raise InvalidCredsError(response["error"])

            return response["error"]
        elif "error_name" in response:
            return "%s: %s" % (response["error_name"], response["errors"][0])

        return self.body
Exemple #19
0
    def parse_error(self):
        response = super(BrightboxResponse, self).parse_body()

        if 'error' in response:
            if response['error'] in ['invalid_client', 'unauthorized_client']:
                raise InvalidCredsError(response['error'])

            return response['error']
        elif 'error_name' in response:
            return '%s: %s' % (response['error_name'], response['errors'][0])

        return self.body
Exemple #20
0
 def parse_error(self):
     if self.status == httplib.UNAUTHORIZED:
         body = self.parse_body()
         raise InvalidCredsError(body.get('error'))
     else:
         body = self.parse_body()
         if 'message' in body:
             error = '%s (code: %s)' % (body.get('message'), self.status)
         elif 'errors' in body:
             error = body.get('errors')
         else:
             error = body
         raise Exception(error)
Exemple #21
0
 def parse_error(self):
     if self.status == httplib.UNAUTHORIZED:
         body = self.parse_body()
         raise InvalidCredsError(body.get("error"))
     else:
         body = self.parse_body()
         if "message" in body:
             error = "%s (code: %s)" % (body.get("message"), self.status)
         elif "errors" in body:
             error = body.get("errors")
         else:
             error = body
         raise Exception(error)
Exemple #22
0
 def parse_error(self):
     if self.status == 401:
         data = self.parse_body()
         raise InvalidCredsError(
             data['error']['code'] + ': ' + data['error']['message'])
     elif self.status == 412:
         data = self.parse_body()
         raise HostVirtualException(
             data['error']['code'], data['error']['message'])
     elif self.status == 404:
         data = self.parse_body()
         raise HostVirtualException(
             data['error']['code'], data['error']['message'])
     else:
         return self.body
Exemple #23
0
    def parse_error(self):
        if self.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError('Invalid provider credentials')

        body = self.parse_body()
        values = list(body.values())[0]

        if 'errortext' in values:
            value = values['errortext']
        else:
            value = self.body

        error = ProviderError(value=value, http_code=self.status,
                              driver=self.connection.driver)
        raise error
Exemple #24
0
 def success(self):
     if self.status == httplib.OK or self.status == httplib.CREATED:
         try:
             j_body = json.loads(self.body)
         except ValueError:
             self.error = "JSON response cannot be decoded."
             return False
         if j_body['errno'] == 0:
             return True
         else:
             self.error = "ECP error: %s" % j_body['message']
             return False
     elif self.status == httplib.UNAUTHORIZED:
         raise InvalidCredsError()
     else:
         self.error = "HTTP Error Code: %s" % self.status
     return False
Exemple #25
0
    def parse_error(self):
        if self.status == 401:
            raise InvalidCredsError(self.body)

        try:
            body = ET.XML(self.body)
        except:
            raise MalformedResponseError(
                "Failed to parse XML",
                body=self.body,
                driver=SlicehostNodeDriver)
        try:
            return "; ".join([ err.text
                               for err in
                               body.findall('error') ])
        except ExpatError:
            return self.body
Exemple #26
0
    def authenticate(self, force=False):
        if not self._is_authentication_needed(force=force):
            return self

        reqbody = json.dumps(
            {'credentials': {
                'username': self.user_id,
                'key': self.key
            }})
        resp = self.request('/v1.1/auth',
                            data=reqbody,
                            headers={},
                            method='POST')

        if resp.status == httplib.UNAUTHORIZED:
            # HTTP UNAUTHORIZED (401): auth failed
            raise InvalidCredsError()
        elif resp.status != httplib.OK:
            body = 'code: %s body:%s' % (resp.status, resp.body)
            raise MalformedResponseError('Malformed response',
                                         body=body,
                                         driver=self.driver)
        else:
            try:
                body = json.loads(resp.body)
            except Exception:
                e = sys.exc_info()[1]
                raise MalformedResponseError('Failed to parse JSON', e)

            try:
                expires = body['auth']['token']['expires']

                self.auth_token = body['auth']['token']['id']
                self.auth_token_expires = parse_date(expires)
                self.urls = body['auth']['serviceCatalog']
                self.auth_user_info = None
            except KeyError:
                e = sys.exc_info()[1]
                raise MalformedResponseError(
                    'Auth JSON response is \
                                             missing required elements', e)

        return self
Exemple #27
0
    def parse_error(self):
        if self.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError('Invalid provider credentials')

        value = None
        body = self.parse_body()
        if hasattr(body, 'values'):
            values = list(body.values())[0]
            if 'errortext' in values:
                value = values['errortext']
        if value is None:
            value = self.body

        if not value:
            value = 'WARNING: error message text sent by provider was empty.'

        error = ProviderError(value=value, http_code=self.status,
                              driver=self.connection.driver)
        raise error
Exemple #28
0
    def _auth(self):
        conn = None
        try:
            conn = self.conn_classes[self.secure](
                self.auth_host, self.auth_port)

            conn.request(
                method='GET',
                url=self.auth_path,
                headers={
                    'X-Auth-User': self.user_id,
                    'X-Auth-Key': self.key
                }
            )

            resp = conn.getresponse()

            if resp.status == httplib.NO_CONTENT:
                # HTTP NO CONTENT (204): auth successful
                self._parse_url_headers(dict(resp.getheaders()))

            elif resp.status == httplib.UNAUTHORIZED:
                # HTTP UNAUTHORIZED (401): auth failed
                raise InvalidCredsError()
            else:
                # Any response code != 401 or 204, something is wrong
                raise MalformedResponseError('Malformed response',
                        body='code: %s body:%s' % (resp.status, ''.join(resp.body.readlines())),
                        driver=self.driver)

            for key in ['server_url', 'storage_url', 'cdn_management_url',
                        'lb_url']:
                url = getattr(self, key, None)
                if url:
                    scheme, server, request_path, param, query, fragment = (
                        urlparse.urlparse(getattr(self, key)))
                    # Set host to where we want to make further requests to
                    setattr(self, '__%s' % (key), server)
                    setattr(self, '__request_path_%s' % (key), request_path)
        finally:
            if conn:
                conn.close()
Exemple #29
0
    def authenticate(self, force=False):
        """
        Perform authentication.
        """
        if not self._is_authentication_needed(force=force):
            return self

        data = {
            'auth': {
                'identity': {
                    'methods': ['password'],
                    'password': {
                        'user': {
                            'domain': {
                                'name': self.domain_name
                            },
                            'name': self.user_id,
                            'password': self.key
                        }
                    }
                }
            }
        }

        if self.token_scope == OpenStackIdentityTokenScope.PROJECT:
            # Scope token to project (tenant)
            data['auth']['scope'] = {
                'project': {
                    'domain': {
                        'name': self.domain_name
                    },
                    'name': self.tenant_name
                }
            }
        elif self.token_scope == OpenStackIdentityTokenScope.DOMAIN:
            # Scope token to domain
            data['auth']['scope'] = {'domain': {'name': self.domain_name}}
        elif self.token_scope == OpenStackIdentityTokenScope.UNSCOPED:
            pass
        else:
            raise ValueError('Token needs to be scoped either to project or '
                             'a domain')

        data = json.dumps(data)
        response = self.request('/v3/auth/tokens',
                                data=data,
                                headers={'Content-Type': 'application/json'},
                                method='POST')

        if response.status == httplib.UNAUTHORIZED:
            # Invalid credentials
            raise InvalidCredsError()
        elif response.status in [httplib.OK, httplib.CREATED]:
            headers = response.headers

            try:
                body = json.loads(response.body)
            except Exception:
                e = sys.exc_info()[1]
                raise MalformedResponseError('Failed to parse JSON', e)

            try:
                roles = self._to_roles(body['token']['roles'])
            except Exception:
                e = sys.exc_info()[1]
                roles = []

            try:
                expires = body['token']['expires_at']

                self.auth_token = headers['x-subject-token']
                self.auth_token_expires = parse_date(expires)
                # Note: catalog is not returned for unscoped tokens
                self.urls = body['token'].get('catalog', None)
                self.auth_user_info = None
                self.auth_user_roles = roles
            except KeyError:
                e = sys.exc_info()[1]
                raise MalformedResponseError(
                    'Auth JSON response is \
                                             missing required elements', e)
            body = 'code: %s body:%s' % (response.status, response.body)
        else:
            raise MalformedResponseError('Malformed response',
                                         body=body,
                                         driver=self.driver)

        return self
Exemple #30
0
 def parse_error(self):
     if self.status == httplib.UNAUTHORIZED:
         data = self.parse_body()
         raise InvalidCredsError(data['code'] + ': ' + data['message'])
     return self.body