Author: Fabien Potencier (fabien.potencier@symfony-project.com)
Exemplo n.º 1
0
 public function it_will_create_event_from_request(Request $request, HeaderBag $headerBag)
 {
     $request->headers = $headerBag;
     $headerBag->get('X-GitHub-Event')->willReturn('push');
     $headerBag->get('X-Hub-Signature')->willReturn('sha1=abc123');
     $this->create($request)->shouldReturnAnInstanceOf('DevBoard\\Notify\\Event');
 }
Exemplo n.º 2
0
 function it_gets_an_item_from_the_header(Request $request, HeaderBag $headerBag)
 {
     $item = 'foo';
     $return = 'bar';
     $request->headers = $headerBag;
     $headerBag->get($item)->shouldBeCalled(1)->willReturn($return);
     $this->header($item)->shouldReturn($return);
 }
 /**
  * PHP does not include HTTP_AUTHORIZATION in the $_SERVER array, so this header is missing.
  * We retrieve it from apache_request_headers()
  *
  * @see https://github.com/symfony/symfony/issues/7170
  *
  * @param HeaderBag $headers
  */
 private static function fixAuthHeader(\Symfony\Component\HttpFoundation\HeaderBag $headers)
 {
     if (!$headers->has('Authorization') && function_exists('apache_request_headers')) {
         $all = apache_request_headers();
         if (isset($all['Authorization'])) {
             $headers->set('Authorization', $all['Authorization']);
         }
     }
 }
Exemplo n.º 4
0
 public function it_will_create_pull_request_event($signatureFactory, WebHookSignature $signature, Request $request, HeaderBag $headerBag)
 {
     $request->headers = $headerBag;
     $headerBag->get('X-GitHub-Event')->willReturn('pull_request');
     $headerBag->get('X-Hub-Signature')->willReturn('sha1=abc123');
     $signatureFactory->create('sha1=abc123')->willReturn($signature);
     $request->getContent()->willReturn('{}');
     $this->create($request)->shouldReturnAnInstanceOf('DevBoard\\Github\\WebHook\\Data\\PullRequestEvent');
 }
Exemplo n.º 5
0
 function it_invalidates_signature(Request $request, HeaderBag $headers)
 {
     $headers->get('X-Shopify-Hmac-Sha256')->willReturn(self::HMAC_HEADER_WRONG)->shouldbeCalled();
     $request->headers = $headers;
     $request->getContent()->willReturn(self::DATA)->shouldbeCalled();
     $this->setHttpRequest($request);
     $this->verify()->shouldBeBool();
     $this->verify()->shouldReturn(false);
 }
Exemplo n.º 6
0
 private function formatHeaders(HeaderBag $headerBag)
 {
     $headers = $headerBag->all();
     $content = '';
     foreach ($headers as $name => $values) {
         $name = implode('-', array_map('ucfirst', explode('-', $name)));
         foreach ($values as $value) {
             $content .= sprintf("%s %s; ", $name . ':', $value);
         }
     }
     return $content;
 }
Exemplo n.º 7
0
 /**
  * PHP does not include HTTP_AUTHORIZATION in the $_SERVER array, so this header is missing.
  * We retrieve it from apache_request_headers()
  *
  * @param HeaderBag $headers
  */
 protected function fixAuthHeader(HeaderBag $headers)
 {
     if (!$headers->has('Authorization') && function_exists('apache_request_headers')) {
         $all = apache_request_headers();
         if (isset($all['Authorization'])) {
             $headers->set('Authorization', $all['Authorization']);
         }
         if (isset($all['authorization'])) {
             $headers->set('Authorization', $all['authorization']);
         }
     }
 }
 /**
  * Creates an array of cacheable and normalized request headers
  *
  * @param HeaderBag $headers
  * @return array
  */
 private function persistHeaders(HeaderBag $headers)
 {
     // Headers are excluded from the caching (see RFC 2616:13.5.1)
     static $noCache = array('age', 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade', 'set-cookie', 'set-cookie2');
     foreach ($headers as $key => $value) {
         if (in_array($key, $noCache) || strpos($key, 'x-') === 0) {
             $headers->remove($key);
         }
     }
     // Postman client sends a dynamic token to bypass a Chrome bug
     $headers->remove('postman-token');
     return $headers;
 }
Exemplo n.º 9
0
 /**
  * @covers Symfony\Component\HttpFoundation\HeaderBag::contains
  */
 public function testContains()
 {
     $bag = new HeaderBag(array('foo' => 'bar', 'fuzz' => 'bizz'));
     $this->assertTrue($bag->contains('foo', 'bar'), '->contains first value');
     $this->assertTrue($bag->contains('fuzz', 'bizz'), '->contains second value');
     $this->assertFalse($bag->contains('nope', 'nope'), '->contains unknown value');
     $this->assertFalse($bag->contains('foo', 'nope'), '->contains unknown value');
     // Multiple values
     $bag->set('foo', 'bor', false);
     $this->assertTrue($bag->contains('foo', 'bar'), '->contains first value');
     $this->assertTrue($bag->contains('foo', 'bor'), '->contains second value');
     $this->assertFalse($bag->contains('foo', 'nope'), '->contains unknown value');
 }
Exemplo n.º 10
0
 /**
  * @return array
  */
 public function getUpdateHeaders()
 {
     // filter normal headers to contain only updateable keys
     $keys = ['etag', 'content-length', 'content-type'];
     $headers = array_diff_key($this->headers->all(), array_flip($keys));
     return array_merge($this->metadata->getHeaders(), $headers);
 }
Exemplo n.º 11
0
 protected function prepareRequestUri()
 {
     $requestUri = '';
     if ($this->headers->has('X_REWRITE_URL') && false !== stripos(PHP_OS, 'WIN')) {
         // check this first so IIS will catch
         $requestUri = $this->headers->get('X_REWRITE_URL');
     } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
         // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
         $requestUri = $this->server->get('UNENCODED_URL');
     } elseif ($this->server->has('REQUEST_URI')) {
         $requestUri = $this->server->get('REQUEST_URI');
         // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
         $schemeAndHttpHost = $this->getScheme() . '://' . $this->getHttpHost();
         if (strpos($requestUri, $schemeAndHttpHost) === 0) {
             $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
         }
     } elseif ($this->server->has('ORIG_PATH_INFO')) {
         // IIS 5.0, PHP as CGI
         $requestUri = $this->server->get('ORIG_PATH_INFO');
         if ($this->server->get('QUERY_STRING')) {
             $requestUri .= '?' . $this->server->get('QUERY_STRING');
         }
     }
     return $requestUri;
 }
 public function let(AngularCsrfTokenManager $tokenManager, RouteMatcherInterface $routeMatcher, Request $secureValidRequest, Request $secureInvalidRequest, Request $unsecureRequest, HeaderBag $validHeaders, HeaderBag $invalidHeaders)
 {
     $tokenManager->isTokenValid(self::VALID_TOKEN)->willReturn(true);
     $tokenManager->isTokenValid(self::INVALID_TOKEN)->willReturn(false);
     $this->secureValidRequest = $secureValidRequest;
     $validHeaders->get(self::HEADER_NAME)->willReturn(self::VALID_TOKEN);
     $this->secureValidRequest->headers = $validHeaders;
     $this->secureInvalidRequest = $secureInvalidRequest;
     $invalidHeaders->get(self::HEADER_NAME)->willReturn(self::INVALID_TOKEN);
     $this->secureInvalidRequest->headers = $invalidHeaders;
     $this->unsecureRequest = $unsecureRequest;
     $routeMatcher->match($this->secureValidRequest, $this->routes)->willReturn(true);
     $routeMatcher->match($this->secureInvalidRequest, $this->routes)->willReturn(true);
     $routeMatcher->match($this->unsecureRequest, $this->routes)->willReturn(false);
     $this->beConstructedWith($tokenManager, $routeMatcher, $this->routes, self::HEADER_NAME);
 }
Exemplo n.º 13
0
 /**
  * Verifies that the provided header has the expected/mandatory fields.
  *
  * @param ParameterBag|HeaderBag $header    object representation of the request header.
  * @param string                 $fieldName Name of the header field to be validated.
  *
  * @return void
  * @throws \Symfony\Component\HttpKernel\Exception\HttpException
  */
 protected function validateField($header, $fieldName)
 {
     $passed = $header->has($fieldName);
     // return without exception so we can return a dummy user
     if (true === $passed) {
         // get rid of anything not a valid character
         $authInfo = filter_var($header->get($fieldName), FILTER_SANITIZE_STRING);
         // get rid of whitespaces
         $patterns = array("\r\n", "\n", "\r", "\\s", "\t");
         $authInfo = str_replace($patterns, "", trim($authInfo));
         // get rid of control characters
         if (empty($authInfo) || $authInfo !== preg_replace('#[[:cntrl:]]#i', '', $authInfo)) {
             throw new HttpException(Response::HTTP_NETWORK_AUTHENTICATION_REQUIRED, 'Mandatory header field (' . $fieldName . ') not provided or invalid.');
         }
     }
 }
 function it_handles_communication_logging(CommunicationLogger $logger, CommunicationExtractor $extractor, Request $request, Response $response, HeaderBag $requestHeaders, IEvent $event)
 {
     $request->getMethod()->shouldBeCalled()->willReturn('POST');
     $request->getContent()->shouldBeCalled()->willReturn('request');
     $request->getUri()->shouldBeCalled()->willReturn('http://example.com');
     $request->headers = $requestHeaders;
     $requestHeaders->all()->shouldBeCalled()->willReturn([]);
     $next = function (Request $request) use($response) {
         return new Response();
     };
     $extractor->getRequest(Argument::type(GuzzleRequest::class))->shouldBeCalled()->willReturn(['request' => 'request']);
     $extractor->getResponse(Argument::type(GuzzleResponse::class))->shouldBeCalled()->willReturn(['response' => 'response']);
     $logger->begin('request', 'http://example.com', 'POST', '')->shouldBeCalled()->willReturn($event);
     $logger->end($event, 'response')->shouldBeCalled();
     $this->handle($request, $next);
 }
Exemplo n.º 15
0
 protected function prepareRequestUri()
 {
     $requestUri = '';
     if ($this->headers->has('X_ORIGINAL_URL')) {
         // IIS with Microsoft Rewrite Module
         $requestUri = $this->headers->get('X_ORIGINAL_URL');
         $this->headers->remove('X_ORIGINAL_URL');
         $this->server->remove('HTTP_X_ORIGINAL_URL');
         $this->server->remove('UNENCODED_URL');
         $this->server->remove('IIS_WasUrlRewritten');
     } elseif ($this->headers->has('X_REWRITE_URL')) {
         // IIS with ISAPI_Rewrite
         $requestUri = $this->headers->get('X_REWRITE_URL');
         $this->headers->remove('X_REWRITE_URL');
     } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
         // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
         $requestUri = $this->server->get('UNENCODED_URL');
         $this->server->remove('UNENCODED_URL');
         $this->server->remove('IIS_WasUrlRewritten');
     } elseif ($this->server->has('REQUEST_URI')) {
         $requestUri = $this->server->get('REQUEST_URI');
         // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
         $schemeAndHttpHost = $this->getSchemeAndHttpHost();
         if (strpos($requestUri, $schemeAndHttpHost) === 0) {
             $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
         }
     } elseif ($this->server->has('ORIG_PATH_INFO')) {
         // IIS 5.0, PHP as CGI
         $requestUri = $this->server->get('ORIG_PATH_INFO');
         if ('' != $this->server->get('QUERY_STRING')) {
             $requestUri .= '?' . $this->server->get('QUERY_STRING');
         }
         $this->server->remove('ORIG_PATH_INFO');
     }
     // normalize the request URI to ease creating sub-requests from this request
     $this->server->set('REQUEST_URI', $requestUri);
     return $requestUri;
 }
Exemplo n.º 16
0
 public function isRedirected($location)
 {
     return $this->isRedirect() && $location == $this->headers->get('Location');
 }
Exemplo n.º 17
0
 public function testCacheControlDirectiveOverrideWithReplace()
 {
     $bag = new HeaderBag(array('cache-control' => 'private, max-age=100'));
     $bag->replace(array('cache-control' => 'public, max-age=10'));
     $this->assertTrue($bag->hasCacheControlDirective('public'));
     $this->assertTrue($bag->getCacheControlDirective('public'));
     $this->assertTrue($bag->hasCacheControlDirective('max-age'));
     $this->assertEquals(10, $bag->getCacheControlDirective('max-age'));
 }
 /**
  * Retrieve and decode the tag list from the response
  * headers.
  *
  * If no tags header is found then throw a \RuntimeException.
  * If the JSON is invalid then throw a \RuntimeException
  *
  * @param HeaderBag $headers
  *
  * @throws \RuntimeException
  *
  * @return string[]
  */
 private function getTagsFromHeaders(HeaderBag $headers)
 {
     $tagsRaw = $headers->get($this->options['header_tags']);
     $tags = $this->decodeTags($tagsRaw, true);
     return $tags;
 }
Exemplo n.º 19
0
 /**
  * Returns true if the request is a XMLHttpRequest.
  *
  * It works if your JavaScript library set an X-Requested-With HTTP header.
  * It is known to work with common JavaScript frameworks:
  *
  * @link http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
  *
  * @return bool    true if the request is an XMLHttpRequest, false otherwise
  *
  * @api
  */
 public function isXmlHttpRequest()
 {
     return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
 }
Exemplo n.º 20
0
 /**
  * @return \Symfony\Component\HttpFoundation\Request
  */
 private function createRequestMock(array $headers = null)
 {
     $headers = $this->mergeHeaders($headers);
     $headerBag = new HeaderBag();
     $headerBag->add($headers);
     $fakeReq = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\Request')->disableOriginalConstructor()->getMock();
     $fakeReq->headers = $headerBag;
     return $fakeReq;
 }
Exemplo n.º 21
0
 /**
  * @param string $name
  *
  * @return array|string
  */
 public function getHeader($name)
 {
     return $this->headers->get($name);
 }
 /**
  * @param HeaderBag $headers
  */
 private function enforceNoCache(HeaderBag $headers)
 {
     $headers->set('cache-control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', false);
     $headers->set('Pragma', 'no-cache', false);
 }
Exemplo n.º 23
0
 /**
  * Sets a header by name.
  *
  * @param string  $key
  * @param mixed   $values
  * @param Boolean $replace
  */
 public function set($key, $values, $replace = true)
 {
     parent::set($key, $values, $replace);
     $this->updateRequest();
 }
 protected function getProgramByOrigin(HeaderBag $headers)
 {
     $program = null;
     if ($headers->has('Origin')) {
         $host = parse_url($headers->get('Origin'), PHP_URL_HOST);
         /** @var \Petrosoft\LoyaltyBundle\Models\FrontSiteSettings\Collection $siteCol */
         $siteCol = $this->meetz->collection('Loyalty:Models\\FrontSiteSettings');
         $siteCol->addFieldToFilter('hosts', array($host), 'in');
         $siteSettings = $siteCol->getFirstItem();
         if (!$siteSettings->isObjectNew()) {
             $program = $siteSettings->getData('loyalty_program_id');
             if ($program instanceof \MongoId) {
                 $program = $program->{'$id'};
             }
         }
     }
     return $program;
 }
Exemplo n.º 25
0
 /**
  * Determine if the request is the result of an PJAX call.
  *
  * @return bool
  */
 public function pjax()
 {
     return $this->headers->get('X-PJAX') == true;
 }
 protected function getContainerRenderActionCached()
 {
     $headerBag = new HeaderBag();
     $headerBag->set('If-Modified-Since', false);
     $requestMock = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\Request')->disableOriginalConstructor()->getMock();
     $requestMock->expects($this->at(0))->method('get')->will($this->returnValue('test.txt'));
     $requestMock->expects($this->at(1))->method('get')->will($this->returnValue('cached_hash'));
     $requestMock->expects($this->any())->method('isMethodSafe')->will($this->returnValue(true));
     $requestMock->expects($this->any())->method('getMethod')->will($this->returnValue('GET'));
     $requestMock->expects($this->any())->method('getEtags')->will($this->returnValue(array('"cached_hash"')));
     $requestMock->headers = $headerBag;
     $container = new Container();
     $container->set('request', $requestMock);
     return $container;
 }
Exemplo n.º 27
0
 /**
  * {@inheritdoc}
  *
  * @api
  */
 public function remove($key)
 {
     parent::remove($key);
     $uniqueKey = strtr(strtolower($key), '_', '-');
     unset($this->headerNames[$uniqueKey]);
 }
Exemplo n.º 28
0
 /**
  * Export data to array.
  *
  * @return array
  */
 public function toArray()
 {
     return array('ip' => $this->ip, 'headers' => $this->headers->all(), 'method' => $this->method, 'uri' => $this->uri, 'data' => $this->data->all(), 'protocol' => $this->protocol, 'scheme' => $this->scheme, 'user_agent' => $this->userAgent->getUserAgentString(), 'is_browser' => $this->isBrowser());
 }
Exemplo n.º 29
0
 /**
  * Validate the Accept header of the Request
  * @link http://jsonapi.org/format/#content-negotiation-servers
  *
  * - Accept MUST be `application/vnd.api+json`
  * - Accept MUST NOT contain any media type parameters
  *
  * @param HeaderBag $headerBag The headers of the Request
  * @throws \Symfony\Component\HttpKernel\Exception\HttpException If invalid request Accept
  */
 private function validateRequestAccept(HeaderBag $headerBag)
 {
     if ($headerBag->has('Accept')) {
         // Validate MediaType
         $mediaType = $this->convertMediaType($headerBag->get('Accept'));
         if ($mediaType && 'application/vnd.api+json' === $mediaType['type']) {
             // Valid media type found
             if (!empty($mediaType['parameters'])) {
                 // Media type parameters are not allowed
                 throw new HttpException('406', 'Accept header MUST NOT have any media type parameters.');
             }
         }
     }
 }
Exemplo n.º 30
0
 /**
  * Determines whether two Request HTTP header sets are non-varying based on
  * the vary response header value provided.
  *
  * @param string $vary A Response vary header
  * @param array  $env1 A Request HTTP header array
  * @param array  $env2 A Request HTTP header array
  *
  * @return Boolean true if the the two environments match, false otherwise
  */
 public function requestsMatch($vary, $env1, $env2)
 {
     if (empty($vary)) {
         return true;
     }
     foreach (preg_split('/[\\s,]+/', $vary) as $header) {
         $key = HeaderBag::normalizeHeaderName($header);
         $v1 = isset($env1[$key]) ? $env1[$key] : null;
         $v2 = isset($env2[$key]) ? $env2[$key] : null;
         if ($v1 !== $v2) {
             return false;
         }
     }
     return true;
 }