Prevent replays of requests by checking that they are timely.

 @param [String] raw_body the raw body of our https request
 @raise [AlexaVerifier::InvalidRequestError] raised when the timestamp is not timely, or is not set
349235
def check_that_request_is_timely(raw_body)
      request_json = JSON.parse(raw_body)

      raise AlexaVerifier::InvalidRequestError, 'Timestamp field not present in request' if request_json.fetch('request', {}).fetch('timestamp', nil).nil?

      request_is_timely = (Time.parse(request_json['request']['timestamp'].to_s) >= (Time.now - REQUEST_THRESHOLD))
      raise AlexaVerifier::InvalidRequestError, "Request is from more than #{REQUEST_THRESHOLD} seconds ago" unless request_is_timely
    end
1230743
def validate(response)
      case response.code
        when 400; raise Error::BadRequest.new error_message(response)
        when 401; raise Error::Unauthorized.new error_message(response)
        when 403; raise Error::Forbidden.new error_message(response)
        when 404; raise Error::NotFound.new error_message(response)
        when 405; raise Error::MethodNotAllowed.new error_message(response)
        when 409; raise Error::Conflict.new error_message(response)
        when 500; raise Error::InternalServerError.new error_message(response)
        when 502; raise Error::BadGateway.new error_message(response)
        when 503; raise Error::ServiceUnavailable.new error_message(response)
      end

      response.parsed_response
    end
701896
async function _request (client, url, body, method, times = 1) {
  if (client.isDebug) {
    debug('Push URL :' + url)
    if (body) {
      debug('Body :' + body)
    }
    // debug("Auth :" + JSON.stringify(auth))
    debug('Method :' + method)
    debug('Times/MaxTryTimes : ' + times + '/' + client.maxTryTimes)
  }

  var options = {
    method: method.toUpperCase(),
    json: true,
    uri: url,
    body: body,
    auth: {
      user: client.appkey,
      pass: client.masterSecret
    },
    timeout: client.readTimeOut,
    proxy: client.proxy
  };

  try {
    return await Request(options);
  } catch (err) {
    if (err.error.code === 'ETIMEDOUT' && err.error.syscall !== 'connect') {
      // response timeout
      throw new JError.APIConnectionError(
        'Response timeout. Your request to the server may have already received, please check whether or not to push',
        true)
    } else if (err.error.code === 'ENOTFOUND') {
      // unknown host
      throw new JError.APIConnectionError('Unknown host : ' + url)
    } else if (times < client.maxTryTimes) {
      return _request(client, url, body, method, times + 1)
    } else {
      if (client.isDebug) {
        debug('Fail, HttpStatusCode: ' + err.statusCode + ' result: ' + JSON.stringify(err.error))
      }
      throw new JError.APIRequestError(err.statusCode, JSON.stringify(err.error))
    }
  }
}
630509
def request(method, path, params=None, data=None, auto_retry=True):
    
    body = None
    if data is not None:
        body = json.dumps(data, cls=utils.DateTimeEncoder)

    headers = {
        'accept': 'application/json',
        'content-type': 'application/json',
        'user-agent': analyzere.user_agent,
    }
    resp = request_raw(method, path, params=params, body=body, headers=headers,
                       auto_retry=auto_retry)
    content = resp.text
    if content:
        try:
            content = json.loads(content, cls=utils.DateTimeDecoder)
        except ValueError:
            raise errors.ServerError('Unable to parse JSON response returned '
                                     'from server.', resp, resp.status_code)
    return content
551080
def request_raw(self, method, url, params=None, supplied_headers=None):
        

        if self.api_key:
            my_api_key = self.api_key
        else:
            from stripe import api_key

            my_api_key = api_key

        if my_api_key is None:
            raise error.AuthenticationError(
                "No API key provided. (HINT: set your API key using "
                '"stripe.api_key = <API-KEY>"). You can generate API keys '
                "from the Stripe web interface.  See https://stripe.com/api "
                "for details, or email support@stripe.com if you have any "
                "questions."
            )

        abs_url = "%s%s" % (self.api_base, url)

        encoded_params = urlencode(list(_api_encode(params or {})))

        # Don't use strict form encoding by changing the square bracket control
        # characters back to their literals. This is fine by the server, and
        # makes these parameter strings easier to read.
        encoded_params = encoded_params.replace("%5B", "[").replace("%5D", "]")

        if method == "get" or method == "delete":
            if params:
                abs_url = _build_api_url(abs_url, encoded_params)
            post_data = None
        elif method == "post":
            if (
                supplied_headers is not None
                and supplied_headers.get("Content-Type")
                == "multipart/form-data"
            ):
                generator = MultipartDataGenerator()
                generator.add_params(params or {})
                post_data = generator.get_post_data()
                supplied_headers[
                    "Content-Type"
                ] = "multipart/form-data; boundary=%s" % (generator.boundary,)
            else:
                post_data = encoded_params
        else:
            raise error.APIConnectionError(
                "Unrecognized HTTP method %r.  This may indicate a bug in the "
                "Stripe bindings.  Please contact support@stripe.com for "
                "assistance." % (method,)
            )

        headers = self.request_headers(my_api_key, method)
        if supplied_headers is not None:
            for key, value in six.iteritems(supplied_headers):
                headers[key] = value

        util.log_info("Request to Stripe api", method=method, path=abs_url)
        util.log_debug(
            "Post details",
            post_data=encoded_params,
            api_version=self.api_version,
        )

        rbody, rcode, rheaders = self._client.request_with_retries(
            method, abs_url, headers, post_data
        )

        util.log_info("Stripe API response", path=abs_url, response_code=rcode)
        util.log_debug("API response body", body=rbody)

        if "Request-Id" in rheaders:
            request_id = rheaders["Request-Id"]
            util.log_debug(
                "Dashboard link for request",
                link=util.dashboard_link(request_id),
            )

        return rbody, rcode, rheaders, my_api_key
761731
def is_valid_request(self, request, parameters={},
                         fake_method=None, handle_error=True):
        '''
        

        '''
        try:
            # Set the parameters to be what we were passed earlier
            # if we didn't get any passed to us now
            if not parameters and hasattr(self, 'params'):
                parameters = self.params

            method, url, headers, parameters = self.parse_request(
                request, parameters, fake_method)

            oauth_request = oauth2.Request.from_request(
                method,
                url,
                headers=headers,
                parameters=parameters)

            self.oauth_server.verify_request(
                oauth_request, self.oauth_consumer, {})

        except oauth2.MissingSignature, e:
            if handle_error:
                return False
            else:
                raise e
        # Signature was valid
        return True
1305790
def check_roads_body_error(response, body)
        error = body[:error]
        return unless error

        case error[:status]
          when 'INVALID_ARGUMENT'
            if error[:message] == 'The provided API key is invalid.'
              raise GoogleMapsService::Error::RequestDeniedError.new(response), error[:message]
            end
            raise GoogleMapsService::Error::InvalidRequestError.new(response), error[:message]
          when 'PERMISSION_DENIED'
            raise GoogleMapsService::Error::RequestDeniedError.new(response), error[:message]
          when 'RESOURCE_EXHAUSTED'
            raise GoogleMapsService::Error::RateLimitError.new(response), error[:message]
          else
            raise GoogleMapsService::Error::ApiError.new(response), error[:message]
        end
      end
448139
def request(*args)
      response = make_request(*args)
      # binding.pry unless response.kind_of?(Net::HTTPSuccess)
      raise HTTPError, response unless response.is_a?(Net::HTTPSuccess)
      response
    end
508180
def re_raise_error(body)
      error = body.fetch(:message, nil)
      case body.fetch(:glimrerrorcode, nil)
      when 511 # FeeLiability not found for FeeLiabilityID
        raise FeeLiabilityNotFound, error
      when 512 # PBA account \w+ not found
        raise AccountNotFound, error
      when 513 # Invalid PBAAccountNumber/PBAConfirmationCode combination
        raise InvalidAccountAndConfirmation, error
      when 514 # Invalid AmountToPay
        raise InvalidAmount, error
      when 521 # PBAGlobalStatus is inactive
        raise GlobalStatusInactive, error
      when 522  # PBAJurisdictionStatus is inactive
        raise JurisdictionStatusInactive, error
      end
      super(message: error)
    end
584364
def request(method, path, options, raw=false, unformatted=true)
      response = connection(raw).send(method) do |request|
        path = formatted_path(path) unless unformatted
        case method
        when :get, :delete
          request.url(path, options)
        when :post, :put
          request.path = path
          request.body = options unless options.empty?
        end
      end
      raw ? response : response.body
    end
1113958
def _check_request(self, msg):
        
        if "jsonrpc" not in msg:
            raise InvalidRequestError("'\"jsonrpc\": \"2.0\"' must be included.")
        if msg["jsonrpc"] != "2.0":
            raise InvalidRequestError("'jsonrpc' must be exactly the string '2.0', but it was '{}'."
                                      .format(msg["jsonrpc"]))
        if "method" not in msg:
            raise InvalidRequestError("No method specified.")
        if "id" in msg:
            if msg["id"] is None:
                raise InvalidRequestError("typedjsonrpc does not allow id to be None.")
            if isinstance(msg["id"], float):
                raise InvalidRequestError("typedjsonrpc does not support float ids.")
            if not isinstance(msg["id"], (six.string_types, six.integer_types)):
                raise InvalidRequestError("id must be a string or integer; '{}' is of type {}."
                                          .format(msg["id"], type(msg["id"])))
        if msg["method"] not in self._name_to_method_info:
            raise MethodNotFoundError("Could not find method '{}'.".format(msg["method"]))
870868
async def on_raw(self, message):
        
        self.logger.debug('<< %s', message._raw)
        if not message._valid:
            self.logger.warning('Encountered strictly invalid IRC message from server: %s',
                                message._raw)

        if isinstance(message.command, int):
            cmd = str(message.command).zfill(3)
        else:
            cmd = message.command

        # Invoke dispatcher, if we have one.
        method = 'on_raw_' + cmd.lower()
        try:
            # Set _top_level so __getattr__() can decide whether to return on_unknown or _ignored for unknown handlers.
            # The reason for this is that features can always call super().on_raw_* safely and thus don't need to care for other features,
            # while unknown messages for which no handlers exist at all are still logged.
            self._handler_top_level = True
            handler = getattr(self, method)
            self._handler_top_level = False

            await handler(message)
        except:
            self.logger.exception('Failed to execute %s handler.', method)
1219567
def raw_post
      unless has_header? "RAW_POST_DATA"
        raw_post_body = body
        set_header("RAW_POST_DATA", raw_post_body.read(content_length))
        raw_post_body.rewind if raw_post_body.respond_to?(:rewind)
      end
      get_header "RAW_POST_DATA"
    end
105757
def request
      raise StateError, "already processing a request" if current_request

      req = @parser.current_request
      @request_fsm.transition :headers
      @keepalive = false if req[CONNECTION] == CLOSE || req.version == HTTP_VERSION_1_0
      @current_request = req

      req
    rescue IOError, Errno::ECONNRESET, Errno::EPIPE
      @request_fsm.transition :closed
      @keepalive = false
      nil
    end
172519
def guard_prepublish(analysis_request):
    
    valid_states = ['verified', 'to_be_verified']
    for analysis in analysis_request.getAnalyses():
        analysis = api.get_object(analysis)
        if api.get_workflow_status_of(analysis) in valid_states:
            return True
    return False
230451
function makeHttpRequest(next) {
  var start = Date.now();

  var timestamp = Date.now();
  var reqBody = 'time * 2 = ' + (timestamp * 2);

  sepia.filter({
    url: /.*/,
    urlFilter: function(url) {
      // disregard the timestamp in the query parameter
      return url.replace(/time\=[0-9]+/, '');
    },
    bodyFilter: function(body) {
      // disregard the timestamp in the request body
      return body.replace(/\= [0-9]+/, '');
    }
  });

  request({
    url: 'http://localhost:1337',
    method: 'POST',
    qs: {
      time: timestamp
    },
    body: reqBody
  }, function(err, data, body) {
    var time = Date.now() - start;

    console.log('FILTERS');
    console.log('  status:', data.statusCode);
    console.log('  body  :', body);
    console.log('  time  :', time);

    common.verify(function() {
      common.shouldBeDynamicallyTimed(time);
    });

    console.log();

    next();
  });
}
357328
def treat(request_body):
    
    # Python 3+ support
    if isinstance(request_body, six.binary_type):
        request_body = request_body.decode('utf-8')

    try:
        data = json.loads(request_body)
    except ValueError:
        raise exceptions.UnknownAPIResource('Request body is malformed JSON.')

    unsafe_api_resource = APIResource.factory(data)

    try:
        consistent_api_resource = unsafe_api_resource.get_consistent_resource()
    except AttributeError:
        raise exceptions.UnknownAPIResource('The API resource provided is invalid.')

    return consistent_api_resource