/**
  * @return string
  */
 public function getRequestId()
 {
     if ($this->request->hasHeader($this->headerName)) {
         return $this->request->getHeader($this->headerName);
     }
     return $this->fallback->getRequestId();
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function getHeader($header)
 {
     if (!$this->request->hasHeader($header)) {
         if (strtolower($header) === 'host' && ($this->request->getUri() && $this->request->getUri()->getHost())) {
             return array($this->getHostFromUri());
         }
         return array();
     }
     return $this->request->getHeader($header);
 }
Example #3
0
 /**
  * @Then the sent request should contain an :header header
  */
 public function theSentRequestShouldContainAnHeader($header)
 {
     if (null === $this->request) {
         throw new \RuntimeException('No request found, maybe no registered hook, right?');
     } else {
         if (!$this->request->hasHeader($header)) {
             throw new \RuntimeException('Header not found in request');
         }
     }
 }
Example #4
0
 private function addExpectHeader(RequestInterface $request, array $options, array &$modify)
 {
     // Determine if the Expect header should be used
     if ($request->hasHeader('Expect')) {
         return;
     }
     $expect = isset($options['expect']) ? $options['expect'] : null;
     // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0
     if ($expect === false || $request->getProtocolVersion() < 1.1) {
         return;
     }
     // The expect header is unconditionally enabled
     if ($expect === true) {
         $modify['set_headers']['Expect'] = '100-Continue';
         return;
     }
     // By default, send the expect header when the payload is > 1mb
     if ($expect === null) {
         $expect = 1048576;
     }
     // Always add if the body cannot be rewound, the size cannot be
     // determined, or the size is greater than the cutoff threshold
     $body = $request->getBody();
     $size = $body->getSize();
     if ($size === null || $size >= (int) $expect || !$body->isSeekable()) {
         $modify['set_headers']['Expect'] = '100-Continue';
     }
 }
 /**
  * @param RequestInterface $request
  * @return MatchResultInterface
  */
 public function match(RequestInterface $request)
 {
     if ($request->hasHeader('X-GitHub-Event')) {
         return new MatchResult(true, $this->getNotificationEvent($request));
     }
     return new UnmatchedResult();
 }
 /**
  * Always add a x-amz-content-sha-256 for data integrity.
  */
 public function presign(RequestInterface $request, CredentialsInterface $credentials, $expires)
 {
     if (!$request->hasHeader('x-amz-content-sha256')) {
         $request = $request->withHeader('X-Amz-Content-Sha256', $this->getPresignedPayload($request));
     }
     return parent::presign($request, $credentials, $expires);
 }
 /**
  * @param RequestInterface $request
  * @return MatchResultInterface
  */
 public function match(RequestInterface $request)
 {
     if ($request->hasHeader('x-amz-sns-message-type')) {
         return new MatchResult(true, $this->getNotificationEvent($request));
     }
     return new UnmatchedResult();
 }
Example #8
0
 /**
  * {@inheritdoc}
  */
 public function handleRequest(RequestInterface $request, callable $next, callable $first)
 {
     foreach ($this->headers as $header) {
         if ($request->hasHeader($header)) {
             $request = $request->withoutHeader($header);
         }
     }
     return $next($request);
 }
 public function __invoke(CommandInterface $command, RequestInterface $request)
 {
     $name = $command->getName();
     $body = $request->getBody();
     if (!$request->hasHeader('Content-MD5') && $body->getSize() && in_array($name, self::$requireMd5)) {
         $request = $request->withHeader('Content-MD5', base64_encode(Psr7\hash($body, 'md5', true)));
     }
     $next = $this->nextHandler;
     return $next($command, $request);
 }
 /**
  * Normalizes the custom headers for signing.
  *
  * @return string[]
  *   An array of normalized headers.
  */
 protected function normalizeCustomHeaders()
 {
     $headers = [];
     // The spec requires that headers are sorted by header name.
     sort($this->headers);
     foreach ($this->headers as $header) {
         if ($this->request->hasHeader($header)) {
             $headers[] = strtolower($header) . ':' . $this->request->getHeaderLine($header);
         }
     }
     return $headers;
 }
 /**
  * Signs the request, adds the HMAC hash to the authorization header.
  *
  * @param \Psr\Http\Message\RequestInterface $request
  *
  * @return \Psr\Http\Message\RequestInterface
  */
 public function signRequest(RequestInterface $request)
 {
     if (!$request->hasHeader('Date')) {
         $time = new \DateTime();
         $time->setTimezone(new \DateTimeZone('GMT'));
         $request = $request->withHeader('Date', $time->format('D, d M Y H:i:s \\G\\M\\T'));
     }
     if (!$request->hasHeader('Content-Type')) {
         $request = $request->withHeader('Content-Type', $this->defaultContentType);
     }
     $authorization = $this->requestSigner->getAuthorization(new RequestWrapper($request), $this->id, $this->secretKey);
     return $request->withHeader('Authorization', $authorization);
 }
Example #12
0
 /**
  * Take a request and update the $_SERVER global to match
  *
  * @param RequestInterface $request
  */
 private function forgeServerGlobal(RequestInterface $request)
 {
     $_SERVER['REQUEST_URI'] = $request->getUri()->getPath();
     $_SERVER['REQUEST_METHOD'] = $request->getMethod();
     $_SERVER['QUERY_STRING'] = $request->getUri()->getQuery();
     if ($request->hasHeader('Content-Type')) {
         $_SERVER['CONTENT_TYPE'] = $request->getHeaderLine('Content-Type');
     }
     if ($request->hasHeader('Referer')) {
         $_SERVER['HTTP_REFERER'] = $request->getHeaderLine('Referer');
     }
     if ($request->hasHeader('X-Requested-with')) {
         $_SERVER['HTTP_X_REQUESTED_WITH'] = $request->getHeaderLine('X-Requested-With');
     }
     if ($request->hasHeader('User-Agent')) {
         $_SERVER['HTTP_USER_AGENT'] = $request->getHeaderLine('User-Agent');
     }
     if ($request->hasHeader('X-Forwarded-For')) {
         $_SERVER['HTTP_X_FORWARDED_FOR'] = $request->getHeaderLine('X-Forwarded-For');
     }
     return $this;
 }
Example #13
0
 /**
  * {@inheritdoc}
  */
 public function handleRequest(RequestInterface $request, callable $next, callable $first)
 {
     if (!$request->hasHeader('Content-Length')) {
         $stream = $request->getBody();
         // Cannot determine the size so we use a chunk stream
         if (null === $stream->getSize()) {
             $stream = new ChunkStream($stream);
             $request = $request->withBody($stream);
         } else {
             $request = $request->withHeader('Content-Length', $stream->getSize());
         }
     }
     return $next($request);
 }
 public function __invoke(CommandInterface $command, RequestInterface $request)
 {
     $next = $this->nextHandler;
     $name = $command->getName();
     $body = $request->getBody();
     if (in_array($name, self::$md5) && !$request->hasHeader('Content-MD5')) {
         // Set the content MD5 header for operations that require it.
         $request = $request->withHeader('Content-MD5', base64_encode(Psr7\hash($body, 'md5', true)));
     } elseif (in_array($name, self::$sha256) && $command['ContentSHA256']) {
         // Set the content hash header if provided in the parameters.
         $request = $request->withHeader('X-Amz-Content-Sha256', $command['ContentSHA256']);
     }
     return $next($command, $request);
 }
Example #15
0
 protected function getPayload(RequestInterface $request)
 {
     // Calculate the request signature payload
     if ($request->hasHeader('X-Amz-Content-Sha256')) {
         // Handle streaming operations (e.g. Glacier.UploadArchive)
         return $request->getHeaderLine('X-Amz-Content-Sha256');
     }
     if (!$request->getBody()->isSeekable()) {
         throw new CouldNotCreateChecksumException('sha256');
     }
     try {
         return Psr7\hash($request->getBody(), 'sha256');
     } catch (\Exception $e) {
         throw new CouldNotCreateChecksumException('sha256', $e);
     }
 }
 /**
  * {@inheritDoc}
  */
 public static function createFromRequest(RequestInterface $request)
 {
     if (!$request->hasHeader('Authorization')) {
         throw new MalformedRequestException('Authorization header is required.', null, 0, $request);
     }
     $header = $request->getHeaderLine('Authorization');
     $id_match = preg_match('/.*id="(.*?)"/', $header, $id_matches);
     $realm_match = preg_match('/.*realm="(.*?)"/', $header, $realm_matches);
     $nonce_match = preg_match('/.*nonce="(.*?)"/', $header, $nonce_matches);
     $version_match = preg_match('/.*version="(.*?)"/', $header, $version_matches);
     $signature_match = preg_match('/.*signature="(.*?)"/', $header, $signature_matches);
     $headers_match = preg_match('/.*headers="(.*?)"/', $header, $headers_matches);
     if (!$id_match || !$realm_match || !$nonce_match || !$version_match || !$signature_match) {
         throw new MalformedRequestException('Authorization header requires a realm, id, version, nonce and a signature.', null, 0, $request);
     }
     $customHeaders = !empty($headers_matches[1]) ? explode('%3B', $headers_matches[1]) : [];
     return new static(rawurldecode($realm_matches[1]), $id_matches[1], $nonce_matches[1], $version_matches[1], $customHeaders, $signature_matches[1]);
 }
 /**
  * @param RequestInterface $request
  * @param array            $options
  *
  * @return PromiseInterface
  */
 public function __invoke(RequestInterface $request, array $options)
 {
     $nextHandler = $this->nextHandler;
     if ($request->hasHeader('Authorization')) {
         return $nextHandler($request, $options);
     }
     $request = $request->withHeader('Authorization', sprintf('Bearer %s', $this->session->getToken()));
     return $nextHandler($request, $options)->then(function (ResponseInterface $response) use($request, $options) {
         $code = $response->getStatusCode();
         if ($code < 400) {
             return $response;
         }
         if ($response->hasHeader("WWW-Authenticate")) {
             throw BearerErrorResponseException::create($request, $response);
         }
         throw RequestException::create($request, $response);
     });
 }
 /**
  * {@inheritDoc}
  *
  * @throws \InvalidArgumentException
  */
 protected function compareTimestamp(RequestInterface $request, $expiry)
 {
     if (!$request->hasHeader('X-Authorization-Timestamp')) {
         throw new MalformedRequestException('Request is missing X-Authorization-Timestamp.', null, 0, $request);
     }
     $timestamp = (int) $request->getHeaderLine('X-Authorization-Timestamp');
     $current = $this->getCurrentTimestamp();
     // Is the request too old?
     $lowerLimit = $this->getExpiry($expiry, $timestamp);
     if ($current > $lowerLimit) {
         return -1;
     }
     // Is the request too far in the future?
     $upperLimit = $this->getExpiry($expiry, $current);
     if ($timestamp > $upperLimit) {
         return 1;
     }
     // Timestamp is within the expected range.
     return 0;
 }
 private function getDefaultContext(RequestInterface $request)
 {
     $headers = '';
     foreach ($request->getHeaders() as $name => $value) {
         foreach ($value as $val) {
             $headers .= "{$name}: {$val}\r\n";
         }
     }
     $context = ['http' => ['method' => $request->getMethod(), 'header' => $headers, 'protocol_version' => $request->getProtocolVersion(), 'ignore_errors' => true, 'follow_location' => 0]];
     $body = (string) $request->getBody();
     if (!empty($body)) {
         $context['http']['content'] = $body;
         // Prevent the HTTP handler from adding a Content-Type header.
         if (!$request->hasHeader('Content-Type')) {
             $context['http']['header'] .= "Content-Type:\r\n";
         }
     }
     $context['http']['header'] = rtrim($context['http']['header']);
     return $context;
 }
Example #20
0
 /**
  * @param RequestInterface $request
  *
  * @return ParsedUrlInterface|null
  */
 protected function getOrigin(RequestInterface $request)
 {
     $origin = null;
     if ($request->hasHeader(CorsRequestHeaders::ORIGIN) === true) {
         $headerValue = $request->getHeader(CorsRequestHeaders::ORIGIN);
         empty($headerValue) === false ? $origin = $this->factory->createParsedUrl($headerValue[0]) : null;
     }
     return $origin;
 }
Example #21
0
 /**
  * Return remote socket from the request.
  *
  * @param RequestInterface $request
  *
  * @throws InvalidRequestException When no remote can be determined from the request
  *
  * @return string
  */
 private function determineRemoteFromRequest(RequestInterface $request)
 {
     if (!$request->hasHeader('Host') && $request->getUri()->getHost() === '') {
         throw new InvalidRequestException('Remote is not defined and we cannot determine a connection endpoint for this request (no Host header)', $request);
     }
     $host = $request->getUri()->getHost();
     $port = $request->getUri()->getPort() ?: ($request->getUri()->getScheme() === 'https' ? 443 : 80);
     $endpoint = sprintf('%s:%s', $host, $port);
     // If use the host header if present for the endpoint
     if (empty($host) && $request->hasHeader('Host')) {
         $endpoint = $request->getHeaderLine('Host');
     }
     return sprintf('tcp://%s', $endpoint);
 }
 /**
  * @param RequestInterface $request
  * @return bool
  */
 public function isVaryEquals(RequestInterface $request)
 {
     if ($this->response->hasHeader('Vary')) {
         if ($this->request === null) {
             return false;
         }
         $varyHeaders = new KeyValueHttpHeader($this->response->getHeader('Vary'));
         foreach ($varyHeaders as $key => $value) {
             if (!$this->request->hasHeader($key) && !$request->hasHeader($key)) {
                 // Absent from both
                 continue;
             } elseif ($this->request->getHeaderLine($key) == $request->getHeaderLine($key)) {
                 // Same content
                 continue;
             }
             return false;
         }
     }
     return true;
 }
Example #23
0
 /**
  * {@inheritDoc}
  */
 public function getAuthorizedRequest(RequestInterface $request, array $customHeaders = [])
 {
     if ($request->hasHeader('Authorization')) {
         $authHeader = AuthorizationHeader::createFromRequest($request);
     } else {
         $authHeader = $this->buildAuthorizationHeader($request, $customHeaders);
     }
     /** @var RequestInterface $request */
     $request = $request->withHeader('Authorization', (string) $authHeader);
     return $request;
 }
 /**
  * Return a CacheEntry or null if no cache.
  *
  * @param RequestInterface $request
  *
  * @return CacheEntry|null
  */
 public function fetch(RequestInterface $request)
 {
     /** @var int|null $maxAge */
     $maxAge = null;
     if ($request->hasHeader('Cache-Control')) {
         $reqCacheControl = new KeyValueHttpHeader($request->getHeader('Cache-Control'));
         if ($reqCacheControl->has('no-cache')) {
             // Can't return cache
             return null;
         }
         $maxAge = $reqCacheControl->get('max-age', null);
     } elseif ($request->hasHeader('Pragma')) {
         $pragma = new KeyValueHttpHeader($request->getHeader('Pragma'));
         if ($pragma->has('no-cache')) {
             // Can't return cache
             return null;
         }
     }
     $cache = $this->storage->fetch($this->getCacheKey($request));
     if ($cache !== null) {
         if ((string) $cache->getOriginalRequest()->getUri() !== (string) $request->getUri()) {
             return null;
         }
         if ($maxAge !== null) {
             if ($cache->getAge() > $maxAge) {
                 // Cache entry is too old for the request requirements!
                 return null;
             }
         }
         if (!$cache->isVaryEquals($request)) {
             return null;
         }
     }
     return $cache;
 }
 /**
  * Return remote socket from the request
  *
  * @param RequestInterface $request
  *
  * @throws NetworkException When no remote can be determined from the request
  *
  * @return string
  */
 private function determineRemoteFromRequest(RequestInterface $request)
 {
     if ($request->getUri()->getHost() == "" && !$request->hasHeader('Host')) {
         throw new NetworkException("Cannot find connection endpoint for this request", $request);
     }
     $host = $request->getUri()->getHost();
     $port = $request->getUri()->getPort() ?: ($request->getUri()->getScheme() == "https" ? 443 : 80);
     $endpoint = sprintf("%s:%s", $host, $port);
     // If use the host header if present for the endpoint
     if (empty($host) && $request->hasHeader('Host')) {
         $endpoint = $request->getHeaderLine('Host');
     }
     return sprintf('tcp://%s', $endpoint);
 }
Example #26
0
 private function applyBody(RequestInterface $request, array $options, array &$conf)
 {
     $size = $request->hasHeader('Content-Length') ? (int) $request->getHeaderLine('Content-Length') : null;
     // Send the body as a string if the size is less than 1MB OR if the
     // [curl][body_as_string] request value is set.
     if ($size !== null && $size < 1000000 || !empty($options['_body_as_string'])) {
         $conf[CURLOPT_POSTFIELDS] = (string) $request->getBody();
         // Don't duplicate the Content-Length header
         $this->removeHeader('Content-Length', $conf);
         $this->removeHeader('Transfer-Encoding', $conf);
     } else {
         $conf[CURLOPT_UPLOAD] = true;
         if ($size !== null) {
             $conf[CURLOPT_INFILESIZE] = $size;
             $this->removeHeader('Content-Length', $conf);
         }
         $body = $request->getBody();
         $conf[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use($body) {
             return $body->read($length);
         };
     }
     // If the Expect header is not present, prevent curl from adding it
     if (!$request->hasHeader('Expect')) {
         $conf[CURLOPT_HTTPHEADER][] = 'Expect:';
     }
     // cURL sometimes adds a content-type by default. Prevent this.
     if (!$request->hasHeader('Content-Type')) {
         $conf[CURLOPT_HTTPHEADER][] = 'Content-Type:';
     }
 }
Example #27
0
 /**
  * Generates cURL options
  *
  * @param RequestInterface $request
  *
  * @throws UnexpectedValueException  if unsupported HTTP version requested
  *
  * @return array
  */
 private function createCurlOptions(RequestInterface $request)
 {
     $options = array_key_exists('curl_options', $this->options) ? $this->options['curl_options'] : [];
     $options[CURLOPT_HEADER] = true;
     $options[CURLOPT_RETURNTRANSFER] = true;
     $options[CURLOPT_HTTP_VERSION] = $this->getProtocolVersion($request->getProtocolVersion());
     $options[CURLOPT_URL] = (string) $request->getUri();
     $options[CURLOPT_CONNECTTIMEOUT] = $this->options['connection_timeout'];
     $options[CURLOPT_FOLLOWLOCATION] = $this->options['follow_redirects'];
     $options[CURLOPT_MAXREDIRS] = $this->options['max_redirects'];
     $options[CURLOPT_SSL_VERIFYPEER] = $this->options['ssl_verify_peer'];
     $options[CURLOPT_TIMEOUT] = $this->options['timeout'];
     if ($this->options['decode_content'] && $request->hasHeader('accept-encoding')) {
         $options[CURLOPT_ENCODING] = $request->getHeaderLine('accept-encoding');
     }
     if ($this->options['use_cookies'] && $request->hasHeader('cookie')) {
         $options[CURLOPT_COOKIE] = implode('; ', $request->getHeader('cookie'));
     }
     switch ($request->getMethod()) {
         case 'GET':
             $options[CURLOPT_HTTPGET] = true;
             break;
         case 'HEAD':
             $options[CURLOPT_NOBODY] = true;
             break;
         case 'POST':
         case 'CONNECT':
         case 'DELETE':
         case 'PATCH':
         case 'PUT':
         case 'TRACE':
             $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
             break;
     }
     $headers = array_keys($request->getHeaders());
     foreach ($headers as $name) {
         $values = $request->getHeader($name);
         foreach ($values as $value) {
             $options[CURLOPT_HTTPHEADER][] = $name . ': ' . $value;
         }
     }
     if ($request->getUri()->getUserInfo()) {
         $options[CURLOPT_USERPWD] = $request->getUri()->getUserInfo();
     }
     return $options;
 }
Example #28
0
 public function sendAsync(RequestInterface $request, array $options = [])
 {
     // Merge the base URI into the request URI if needed.
     $options = $this->prepareDefaults($options);
     return $this->transfer($request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), $options);
 }
 /**
  * @param RequestInterface $request
  *
  * @return bool
  */
 private function isRequestValid(RequestInterface $request)
 {
     $uri = $request->getUri();
     $queryParams = \GuzzleHttp\Psr7\parse_query($uri->getQuery());
     return $request->hasHeader('Authorization') || $request->hasHeader('Authentication') || array_key_exists('jwt', $queryParams) || !empty($queryParams['jwt']);
 }
 /**
  * @param string $header
  * @return bool
  */
 public function hasHeader($header)
 {
     return $this->request->hasHeader($header);
 }