Sanitizes http request query string

    :param client: an ElasticAPM client
    :param event: a transaction or error event
    :return: The modified event
341508
def sanitize_http_request_querystring(client, event):
    
    try:
        query_string = force_text(event["context"]["request"]["url"]["search"], errors="replace")
    except (KeyError, TypeError):
        return event
    if "=" in query_string:
        sanitized_query_string = _sanitize_string(query_string, "&", "=")
        full_url = event["context"]["request"]["url"]["full"]
        event["context"]["request"]["url"]["search"] = sanitized_query_string
        event["context"]["request"]["url"]["full"] = full_url.replace(query_string, sanitized_query_string)
    return event
1336991
def _FormatHostname(self, event):
    
    hostname = self._output_mediator.GetHostname(event)
    return self._SanitizeField(hostname)
1262767
def read_validate_params(self, request):
        
        self.client = self.client_authenticator.by_identifier(request)

        response_type = request.get_param("response_type")

        if self.client.response_type_supported(response_type) is False:
            raise OAuthInvalidError(error="unauthorized_client")

        self.state = request.get_param("state")

        self.scope_handler.parse(request, "query")

        return True
57308
def _FlushEvents(self):
    """"""
    try:
      # pylint: disable=unexpected-keyword-arg
      # pylint does not recognizes request_timeout as a valid kwarg. According
      # to http://elasticsearch-py.readthedocs.io/en/master/api.html#timeout
      # it should be supported.
      self._client.bulk(
          body=self._event_documents, doc_type=self._document_type,
          index=self._index_name, request_timeout=self._DEFAULT_REQUEST_TIMEOUT)

    except ValueError as exception:
      # Ignore problematic events
      logger.warning('Unable to bulk insert with error: {0!s}'.format(
          exception))

    logger.debug('Inserted {0:d} events into Elasticsearch'.format(
        self._number_of_buffered_events))

    self._event_documents = []
    self._number_of_buffered_events = 0
468692
def handle_client_registration_request(self, request, http_headers=None):
        # type: (Optional[str], Optional[Mapping[str, str]]) -> oic.oic.message.RegistrationResponse
        
        registration_req = RegistrationRequest().deserialize(request, 'json')

        for validator in self.registration_request_validators:
            validator(registration_req)
        logger.debug('parsed authentication_request: %s', registration_req)

        client_id, client_secret = self._issue_new_client()
        credentials = {
            'client_id': client_id,
            'client_id_issued_at': int(time.time()),
            'client_secret': client_secret,
            'client_secret_expires_at': 0  # never expires
        }

        response_params = self.match_client_preferences_with_provider_capabilities(registration_req)
        response_params.update(credentials)
        self.clients[client_id] = copy.deepcopy(response_params)

        registration_resp = RegistrationResponse(**response_params)
        logger.debug('registration_resp=%s from registration_req=%s', registration_resp, registration_req)
        return registration_resp
739017
async def request(self, request):
        
        assert request.transaction_id not in self.transactions

        if self.integrity_key:
            self.__add_authentication(request)

        transaction = stun.Transaction(request, self.server, self)
        self.transactions[request.transaction_id] = transaction
        try:
            return await transaction.run()
        finally:
            del self.transactions[request.transaction_id]
628410
def _post_parse_request(self, request, client_id='', **kwargs):
        

        request = RefreshAccessTokenRequest(**request.to_dict())

        try:
            keyjar = self.endpoint_context.keyjar
        except AttributeError:
            keyjar = ""

        request.verify(keyjar=keyjar, opponent_id=client_id)

        if "client_id" not in request:  # Optional for refresh access token request
            request["client_id"] = client_id

        logger.debug("%s: %s" % (request.__class__.__name__, sanitize(request)))

        return request
252525
def delete_events(self, event_collection, params):
        

        url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url,
                                                       self.api_version,
                                                       self.project_id,
                                                       event_collection)
        headers = utilities.headers(self.master_key)
        response = self.fulfill(HTTPMethods.DELETE, url, params=params, headers=headers, timeout=self.post_timeout)

        self._error_handling(response)
        return True
1091692
def encode_request(name, expected, updated):
    
    client_message = ClientMessage(payload_size=calculate_size(name, expected, updated))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(name)
    client_message.append_bool(expected is None)
    if expected is not None:
        client_message.append_data(expected)
    client_message.append_bool(updated is None)
    if updated is not None:
        client_message.append_data(updated)
    client_message.update_frame_length()
    return client_message
362209
function (event) {
    if (!event || !_.isObject(event)) {
      var err = new Error('Please inject a valid event object!');
      debug(err);
      throw err;
    }

    if (!event.payload && event.payload !== '') {
      event.payload = this.defaultEventPayload;
    }

    if (this.events.indexOf(event) < 0) {
      this.events.push(event);
    }
  }
129222
function eventsApi(obj, action, name, rest) {
  if (!name) {
    return false;
  }

  var results = {};

  // Handle event maps.
  if (typeof name === 'object') {
    for (var key in name) {
      var result = obj[action].apply(obj, [key, name[key]].concat(rest));
      eventSplitter.test(key) ? _.extend(results, result) : results[key] = result;
    }
    return results;
  }

  // Handle space separated event names.
  if (eventSplitter.test(name)) {
    var names = name.split(eventSplitter);
    for (var i = 0, l = names.length; i < l; i++) {
      results[names[i]] = obj[action].apply(obj, [names[i]].concat(rest));
    }
    return results;
  }

  return false;
}
790801
@Override
  public void queryError(WebSocket session,
                         HeadersAmp headers,
                         String to,
                         long qid,
                         Throwable exn)
    throws IOException
  {
    /*
    try (Writer out = session.getBasicRemote().getSendWriter()) {
      init(out);
      queryError(headers, to, qid, exn);
    }
    */
  }
1228593
def _validate_request(endpoint, file_type='json', data=None, params=None):
        
        if not isinstance(endpoint, string_types) or endpoint.strip() == '':
            raise ClientException("Must submit `endpoint` for DHIS2 API")
        if not isinstance(file_type, string_types) or file_type.lower() not in ('json', 'csv', 'xml', 'pdf', 'xlsx'):
            raise ClientException("Invalid file_type: {}".format(file_type))
        if params:
            if not isinstance(params, (dict, list)):
                raise ClientException("`params` must be a dict or list of tuples, not {}".format(params.__class__.__name__))
            if isinstance(params, list) and not all([isinstance(elem, tuple) for elem in params]):
                raise ClientException("`params` list must all be tuples")
        if data and not isinstance(data, dict):
            raise ClientException("`data` must be a dict, not {}".format(data.__class__.__name__))
691742
def errors(self,
               errors: List[str],
               code: Union[int, Tuple[int, str, str]] = HTTPStatus.BAD_REQUEST,
               key: str = 'errors',
               headers: Optional[Dict[str, str]] = None,
               ):
        
        return jsonify({key: errors}), code, headers or {}
387540
def process_request(self, req, resp):
        
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.',
                href='http://docs.examples.com/api/json')
        if req.method in ('POST', 'PUT'):
            if req.content_length != 0 and \
                            'application/json' not in req.content_type and \
                            'text/plain' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as JSON.',
                    href='http://docs.examples.com/api/json')
302179
def sanitize_http_wsgi_env(client, event):
    
    try:
        env = event["context"]["request"]["env"]
        event["context"]["request"]["env"] = varmap(_sanitize, env)
    except (KeyError, TypeError):
        pass
    return event
589545
function mergeAllowedClientHeaders({ headers, request }) {
  const prohibited = ['accept-encoding', 'connection', 'host', 'origin']
  request.headers = Object.entries(headers).reduce((memo, header) => {
    const [key, val] = header
    if (prohibited.indexOf(key) === -1) memo[key] = val // eslint-disable-line
    return memo
  }, request.headers)
  return request
}