示例#1
0
    def _refresh_if_needed(self, request_ret):
        refresh_required = True

        if request_ret.status_code not in range(200, 300):
            try:
                message = json.loads(request_ret.text)[0]
            except Exception:
                message = request_ret.text

            raise ServerError(request_ret.status_code,
                              message,
                              result="Did not update {} record.".format(
                                  self.__class__.__name__))
        else:
            message = request_ret.json()
            log.debug("Received response: %s" % message)
            if not isinstance(message, dict):
                raise ServerError(
                    request_ret.status_code,
                    message,
                    result="Unknown error updating {0:s} record.".format(
                        self.__class__.__name__))
            else:
                if message.get("success", False):
                    if isinstance(message.get(self.info_key, None), dict):
                        self._info = message.get(self.info_key)
                        self._full_init = True
                        refresh_required = False
                    else:
                        if self._change_object_key_name in message.keys():
                            # if all we got back was an ID, try refreshing to get the entire record.
                            log.debug(
                                "Only received an ID back from the server, forcing a refresh"
                            )
                            self._info[self.primary_key] = message[
                                self._change_object_key_name]
                            refresh_required = True
                else:
                    # "success" is False
                    raise ServerError(
                        request_ret.status_code,
                        message.get("message", ""),
                        result="Did not update {0:s} record.".format(
                            self.__class__.__name__))

        self._dirty_attributes = {}
        if refresh_required:
            self.refresh()
        return self._model_unique_id
示例#2
0
    def bulk_delete(cls, cb, overrides):
        """
        Deletes reputation overrides in bulk by id.

        Args:
            cb (BaseAPI): Reference to API object used to communicate with the server.
            overrides (List): List if reputation override ids

        Example:
            [
                "e9410b754ea011ebbfd0db2585a41b07"
            ]

        """
        resp = cb.post_object(
            cls.urlobject.format(cb.credentials.org_key) + "/_delete",
            overrides)
        if resp.status_code not in (200, 204):
            try:
                message = json.loads(resp.text)[0]
            except Exception:
                message = resp.text
            raise ServerError(resp.status_code,
                              message,
                              result="Did not delete overrides.")

        return resp.json()
示例#3
0
    def stop(self):
        """Stop a running query.

        Returns:
            (bool): True if query was stopped successfully, False otherwise.

        Raises:
            ServerError: If the server response cannot be parsed as JSON.
        """
        if self._is_deleted:
            raise ApiError("cannot stop a deleted query")
        url = self.urlobject_single.format(self._cb.credentials.org_key,
                                           self.id) + "/status"
        result = self._cb.put_object(url, {'status': 'CANCELLED'})
        if (result.status_code == 200):
            try:
                self._info = result.json()
                self._last_refresh_time = time.time()
                return True
            except Exception:
                raise ServerError(
                    result.status_code,
                    "Cannot parse response as JSON: {0:s}".format(
                        result.content))
        return False
    def delete(self):
        """Delete this object."""
        if self._model_unique_id:
            ret = self._cb.delete_object(self._build_api_request_uri())
        else:
            return

        if ret.status_code not in (200, 204):
            try:
                message = json.loads(ret.text)[0]
            except Exception:
                message = ret.text
            raise ServerError(ret.status_code, message, result="Did not delete {0:s}.".format(str(self)))
    def delete(self):
        """Delete this object."""
        if self._model_unique_id is None:
            return

        resp = self._cb.delete_object(self.urlobject_single.format(self._cb.credentials.org_key, self._model_unique_id))
        if resp.status_code not in (200, 204):
            try:
                message = json.loads(resp.text)[0]
            except Exception:
                message = resp.text
            raise ServerError(resp.status_code, message, result="Did not delete {0:s}.".format(str(self)))
        self._is_deleted = True
    def vulnerability_refresh(self):
        """Perform an action on a specific device. Only REFRESH is supported."""
        request = {"action_type": 'REFRESH'}
        url = "/vulnerability/assessment/api/v1/orgs/{}".format(
            self._cb.credentials.org_key)

        url += '/devices/{}/device_actions'.format(self._model_unique_id)

        resp = self._cb.post_object(url, body=request)
        if resp.status_code == 200:
            return resp.json()
        elif resp.status_code == 204:
            return None
        else:
            raise ServerError(error_code=resp.status_code,
                              message="Device action error: {0}".format(
                                  resp.content))
示例#7
0
    def _raw_device_action(self, request):
        """
        Invokes the API method for a device action.

        :param dict request: The request body to be passed as JSON to the API method.
        :return: The parsed JSON output from the request.
        :raises ServerError: If the API method returns an HTTP error code.
        """
        url = "/appservices/v6/orgs/{0}/device_actions".format(
            self.credentials.org_key)
        resp = self.post_object(url, body=request)
        if resp.status_code == 200:
            return resp.json()
        elif resp.status_code == 204:
            return None
        else:
            raise ServerError(error_code=resp.status_code,
                              message="Device action error: {0}".format(
                                  resp.content))
示例#8
0
    def _create_user(cls, cb, user_data):
        """
        Creates a new user from template data.

        Args:
            cb (BaseAPI): Reference to API object used to communicate with the server.
            user_data (dict): The user data to be used to create the new user.

        Raises:
            ServerError: If the user registration was unsuccessful.

        Notes:
            The new user will not be "findable" by other API functions until it has been activated and its initial
            password has been set.
        """
        url = User.urlobject.format(cb.credentials.org_key)
        result = cb.post_object(url, user_data)
        resp = result.json()
        if resp['registration_status'] != 'SUCCESS':
            raise ServerError(
                500,
                f"registration return was unsuccessful: {resp['registration_status']} - "
                f"{resp['message']}")
            assert session1.device_id == 2468
            assert session1._cblr_manager is manager
            assert session1._cb is cbcsdk_mock.api
            assert session1.os_type == 1
        with manager.request_session(2468) as session2:
            assert session2 is session1
        assert len(manager._sessions) == 1
        manager._maintain_sessions()
        assert len(manager._sessions) == 0
    finally:
        manager.stop_keepalive_thread()


@pytest.mark.parametrize("thrown_exception", [
    (ObjectNotFoundError('/integrationServices/v3/cblr/session/1:2468'),),
    (ServerError(404, 'test error'),)
])
def test_session_maintenance_sends_keepalive(cbcsdk_mock, thrown_exception):
    """Test to ensure the session maintenance sends the keepalive messages as needed."""
    cbcsdk_mock.mock_request('POST', '/integrationServices/v3/cblr/session/2468', SESSION_INIT_RESP)
    cbcsdk_mock.mock_request('GET', '/integrationServices/v3/cblr/session/1:2468', SESSION_POLL_RESP)
    cbcsdk_mock.mock_request('GET', '/integrationServices/v3/device/2468', DEVICE_RESPONSE)
    cbcsdk_mock.mock_request('GET', '/integrationServices/v3/cblr/session/1:2468/keepalive', {})
    cbcsdk_mock.mock_request('GET', '/integrationServices/v3/cblr/session/1:2468/keepalive', thrown_exception)
    manager = LiveResponseSessionManager(cbcsdk_mock.api, 100000, True)
    try:
        with manager.request_session(2468):
            manager._maintain_sessions()
            assert len(manager._sessions) == 1
            manager._maintain_sessions()
    finally: