public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
 {
     $params = Psr7\parse_query($request->getBody());
     $params['Timestamp'] = gmdate('c');
     $params['SignatureVersion'] = '2';
     $params['SignatureMethod'] = 'HmacSHA256';
     $params['AWSAccessKeyId'] = $credentials->getAccessKeyId();
     if ($token = $credentials->getSecurityToken()) {
         $params['SecurityToken'] = $token;
     }
     // build string to sign
     $sign = $request->getMethod() . "\n" . $request->getHeaderLine('Host') . "\n" . '/' . "\n" . $this->getCanonicalizedParameterString($params);
     $params['Signature'] = base64_encode(hash_hmac('sha256', $sign, $credentials->getSecretKey(), true));
     return $request->withBody(Psr7\stream_for(http_build_query($params)));
 }
Exemple #2
0
 public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
 {
     $params = Psr7\parse_query($request->getBody()->__toString());
     $params['SignatureVersion'] = '2';
     $params['SignatureMethod'] = 'HmacSHA256';
     $params['AWSAccessKeyId'] = $credentials->getAccessKeyId();
     if ($credentials->getSecurityToken()) {
         $params['MWSAuthToken'] = $credentials->getSecurityToken();
     }
     $params['Timestamp'] = gmdate(self::ISO8601_BASIC);
     ksort($params);
     $canonicalizedQueryString = $this->getCanonicalizedQuery($params);
     $stringToSign = implode("\n", [$request->getMethod(), $request->getUri()->getHost(), $request->getUri()->getPath(), $canonicalizedQueryString]);
     // calculate HMAC with SHA256 and base64-encoding
     $signature = base64_encode(hash_hmac('sha256', $stringToSign, $credentials->getSecretKey(), TRUE));
     // encode the signature for the request
     $signature = str_replace('%7E', '~', rawurlencode($signature));
     $signature = str_replace('+', '%20', $signature);
     $signature = str_replace('*', '%2A', $signature);
     $queryString = $canonicalizedQueryString . "&Signature=" . $signature;
     if ($request->getMethod() === 'POST') {
         return new Request('POST', $request->getUri(), ['Content-Length' => strlen($queryString), 'Content-Type' => 'application/x-www-form-urlencoded'], $queryString);
     } else {
         return new Request('GET', $request->getUri()->withQuery($queryString));
     }
 }
 public function getSelectedValues(UriInterface $uri)
 {
     $queryParams = Psr7\parse_query($uri->getQuery());
     $selectedValues = [];
     foreach ($queryParams as $paramName => $params) {
         if (!isset($this->paramFacets[$paramName])) {
             continue;
         }
         $facetName = $this->paramFacets[$paramName];
         $selectedValues[$facetName] = $params;
     }
     return $selectedValues;
 }
 /**
  * Updates the request query with the developer key if auth is set to simple
  *
  *   use Google\Auth\Middleware\SimpleMiddleware;
  *   use GuzzleHttp\Client;
  *   use GuzzleHttp\HandlerStack;
  *
  *   $my_key = 'is not the same as yours';
  *   $middleware = new SimpleMiddleware(['key' => $my_key]);
  *   $stack = HandlerStack::create();
  *   $stack->push($middleware);
  *
  *   $client = new Client([
  *       'handler' => $stack,
  *       'base_uri' => 'https://www.googleapis.com/discovery/v1/',
  *       'auth' => 'simple'
  *   ]);
  *
  *   $res = $client->get('drive/v2/rest');
  */
 public function __invoke(callable $handler)
 {
     return function (RequestInterface $request, array $options) use($handler) {
         // Requests using "auth"="scoped" will be authorized.
         if (!isset($options['auth']) || $options['auth'] !== 'simple') {
             return $handler($request, $options);
         }
         $query = Psr7\parse_query($request->getUri()->getQuery());
         $params = array_merge($query, $this->config);
         $uri = $request->getUri()->withQuery(Psr7\build_query($params));
         $request = $request->withUri($uri);
         return $handler($request, $options);
     };
 }
Exemple #5
0
 /**
  * Create a signed Amazon CloudFront URL.
  *
  * Keep in mind that URLs meant for use in media/flash players may have
  * different requirements for URL formats (e.g. some require that the
  * extension be removed, some require the file name to be prefixed
  * - mp4:<path>, some require you to add "/cfx/st" into your URL).
  *
  * @param string              $url     URL to sign (can include query
  *                                     string string and wildcards)
  * @param string|integer|null $expires UTC Unix timestamp used when signing
  *                                     with a canned policy. Not required
  *                                     when passing a custom $policy.
  * @param string              $policy  JSON policy. Use this option when
  *                                     creating a signed URL for a custom
  *                                     policy.
  *
  * @return string The file URL with authentication parameters
  * @throws \InvalidArgumentException if the URL provided is invalid
  * @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/WorkingWithStreamingDistributions.html
  */
 public function getSignedUrl($url, $expires = null, $policy = null)
 {
     // Determine the scheme of the url
     $urlSections = explode('://', $url);
     if (count($urlSections) < 2) {
         throw new \InvalidArgumentException("Invalid URL: {$url}");
     }
     // Get the real scheme by removing wildcards from the scheme
     $scheme = str_replace('*', '', $urlSections[0]);
     $uri = new Uri($scheme . '://' . $urlSections[1]);
     $query = Psr7\parse_query($uri->getQuery(), PHP_QUERY_RFC3986);
     $signature = $this->signer->getSignature($this->createResource($scheme, (string) $uri), $expires, $policy);
     $uri = $uri->withQuery(http_build_query($query + $signature, null, '&', PHP_QUERY_RFC3986));
     return $scheme === 'rtmp' ? $this->createRtmpUrl($uri) : (string) $uri;
 }
 protected function assertUriEquals($expectedUri, $actualUri)
 {
     if (is_string($expectedUri)) {
         $expectedUri = new Psr7\Uri($expectedUri);
     }
     if (is_string($actualUri)) {
         $actualUri = new Psr7\Uri($actualUri);
     }
     $this->assertEquals($expectedUri->getScheme(), $actualUri->getScheme());
     $this->assertEquals($expectedUri->getPort(), $actualUri->getPort());
     $this->assertEquals($expectedUri->getHost(), $actualUri->getHost());
     $this->assertEquals($expectedUri->getPath(), $actualUri->getPath());
     $expectedQueryParts = Psr7\parse_query($expectedUri->getQuery());
     $actualQueryParts = Psr7\parse_query($actualUri->getQuery());
     $this->assertEquals($expectedQueryParts, $actualQueryParts);
 }
Exemple #7
0
 /**
  * Create a signed Amazon CloudFront URL.
  *
  * Keep in mind that URLs meant for use in media/flash players may have
  * different requirements for URL formats (e.g. some require that the
  * extension be removed, some require the file name to be prefixed
  * - mp4:<path>, some require you to add "/cfx/st" into your URL).
  *
  * @param string              $url     URL to sign (can include query
  *                                     string string and wildcards
  * @param string|integer|null $expires UTC Unix timestamp used when signing
  *                                     with a canned policy. Not required
  *                                     when passing a custom $policy.
  * @param string              $policy  JSON policy. Use this option when
  *                                     creating a signed URL for a custom
  *                                     policy.
  *
  * @return string The file URL with authentication parameters
  * @throws \InvalidArgumentException if the URL provided is invalid
  * @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/WorkingWithStreamingDistributions.html
  */
 public function getSignedUrl($url, $expires = null, $policy = null)
 {
     // Determine the scheme of the url
     $urlSections = explode('://', $url);
     if (count($urlSections) < 2) {
         throw new \InvalidArgumentException("Invalid URL: {$url}");
     }
     // Get the real scheme by removing wildcards from the scheme
     $scheme = str_replace('*', '', $urlSections[0]);
     $uri = new Uri($scheme . '://' . $urlSections[1]);
     if ($policy) {
         $isCustom = true;
     } else {
         $isCustom = false;
         $policy = $this->createCannedPolicy($scheme, (string) $uri, $expires);
     }
     $policy = str_replace(' ', '', $policy);
     $query = Psr7\parse_query($uri->getQuery(), PHP_QUERY_RFC3986);
     $query = $this->prepareQuery($isCustom, $policy, $query, $expires);
     $uri = $uri->withQuery(http_build_query($query, null, '&', PHP_QUERY_RFC3986));
     return $scheme === 'rtmp' ? $this->createRtmpUrl($uri) : (string) $uri;
 }
Exemple #8
0
 public function testCanControlDecodingType()
 {
     $result = Psr7\parse_query('var=foo+bar', PHP_QUERY_RFC3986);
     $this->assertEquals('foo+bar', $result['var']);
     $result = Psr7\parse_query('var=foo+bar', PHP_QUERY_RFC1738);
     $this->assertEquals('foo bar', $result['var']);
 }
Exemple #9
0
 /**
  * Asserts that the query string of the request contains the specified query parameter.
  *
  * If value is provided, the value will also be comaped
  *
  * @param RequestInterface $request
  * @param string $name
  * @param string|null $value
  */
 public function assertHasQuery(RequestInterface $request, $name, $value = null)
 {
     $query = Psr7\parse_query($request->getUri()->getQuery());
     $this->assertArrayHasKey($name, $query, "The request does not contain the query parameter {$name}");
     if (!is_null($value)) {
         $this->assertEquals($value, $query[$name], "The request contains the query parameter {$name}, but with the wrong value.");
     }
 }
 public function testGeneratesExtendedRequests()
 {
     $testConfig = $this->tokenRequestMinimal;
     $o = new OAuth2($testConfig);
     $o->setGrantType('urn:my_test_grant_type');
     $o->setExtensionParams(['my_param' => 'my_value']);
     // Generate the request and confirm that it's correct.
     $req = $o->generateCredentialsRequest();
     $this->assertInstanceOf('Psr\\Http\\Message\\RequestInterface', $req);
     $this->assertEquals('POST', $req->getMethod());
     $fields = Psr7\parse_query((string) $req->getBody());
     $this->assertEquals('my_value', $fields['my_param']);
     $this->assertEquals('urn:my_test_grant_type', $fields['grant_type']);
 }
Exemple #11
0
 protected function parseConnections($options, $defaultHost, $defaultPort, $defaultScheme = 'tcp')
 {
     if (isset($options['host']) || isset($options['port'])) {
         $options['connections'][] = $options;
     } elseif ($options['connection']) {
         $options['connections'][] = $options['connection'];
     }
     /** @var ParameterBag[] $toParse */
     $toParse = [];
     if (isset($options['connections'])) {
         foreach ((array) $options['connections'] as $alias => $conn) {
             if (is_string($conn)) {
                 $conn = ['host' => $conn];
             }
             $conn += ['scheme' => $defaultScheme, 'host' => $defaultHost, 'port' => $defaultPort];
             $conn = new ParameterBag($conn);
             if ($conn->has('password')) {
                 $conn->set('pass', $conn->get('password'));
                 $conn->remove('password');
             }
             $conn->set('uri', Uri::fromParts($conn->all()));
             $toParse[] = $conn;
         }
     } else {
         $connections = isset($options['save_path']) ? (array) explode(',', $options['save_path']) : [];
         if (empty($connections)) {
             $connections[] = $defaultHost . ':' . $defaultPort;
         }
         foreach ($connections as $conn) {
             // Default scheme if not given so parse_url works correctly.
             if (!preg_match('~^\\w+://.+~', $conn)) {
                 $conn = $defaultScheme . '://' . $conn;
             }
             $uri = new Uri($conn);
             $connBag = new ParameterBag();
             $connBag->set('uri', $uri);
             $connBag->add(Psr7\parse_query($uri->getQuery()));
             $toParse[] = $connBag;
         }
     }
     $connections = [];
     foreach ($toParse as $conn) {
         /** @var Uri $uri */
         $uri = $conn->get('uri');
         $parts = explode(':', $uri->getUserInfo(), 2);
         $password = isset($parts[1]) ? $parts[1] : null;
         $connections[] = ['scheme' => $uri->getScheme(), 'host' => $uri->getHost(), 'port' => $uri->getPort(), 'path' => $uri->getPath(), 'alias' => $conn->get('alias'), 'prefix' => $conn->get('prefix'), 'password' => $password, 'database' => $conn->get('database'), 'persistent' => $conn->get('persistent'), 'weight' => $conn->get('weight'), 'timeout' => $conn->get('timeout')];
     }
     return $connections;
 }
Exemple #12
0
 /**
  * Builds the authorization Uri that the user should be redirected to.
  *
  * @param array $config configuration options that customize the return url
  *
  * @return UriInterface the authorization Url.
  *
  * @throws InvalidArgumentException
  */
 public function buildFullAuthorizationUri(array $config = [])
 {
     if (is_null($this->getAuthorizationUri())) {
         throw new InvalidArgumentException('requires an authorizationUri to have been set');
     }
     $params = array_merge(['response_type' => 'code', 'access_type' => 'offline', 'client_id' => $this->clientId, 'redirect_uri' => $this->redirectUri, 'state' => $this->state, 'scope' => $this->getScope()], $config);
     // Validate the auth_params
     if (is_null($params['client_id'])) {
         throw new InvalidArgumentException('missing the required client identifier');
     }
     if (is_null($params['redirect_uri'])) {
         throw new InvalidArgumentException('missing the required redirect URI');
     }
     if (!empty($params['prompt']) && !empty($params['approval_prompt'])) {
         throw new InvalidArgumentException('prompt and approval_prompt are mutually exclusive');
     }
     // Construct the uri object; return it if it is valid.
     $result = clone $this->authorizationUri;
     $existingParams = Psr7\parse_query($result->getQuery());
     $result = $result->withQuery(Psr7\build_query(array_merge($existingParams, $params)));
     if ($result->getScheme() != 'https') {
         throw new InvalidArgumentException('Authorization endpoint must be protected by TLS');
     }
     return $result;
 }
 private function parseRequest(RequestInterface $request)
 {
     // Clean up any previously set headers.
     /** @var RequestInterface $request */
     $request = $request->withoutHeader('X-Amz-Date')->withoutHeader('Date')->withoutHeader('Authorization');
     $uri = $request->getUri();
     return ['method' => $request->getMethod(), 'path' => $uri->getPath(), 'query' => Psr7\parse_query($uri->getQuery()), 'uri' => $uri, 'headers' => $request->getHeaders(), 'body' => $request->getBody(), 'version' => $request->getProtocolVersion()];
 }
Exemple #14
0
 private function applyQuery(RequestInterface $request, $query)
 {
     $uri = $request->getUri();
     if (!is_array($query)) {
         $query = GuzzlePsr7\parse_query($query);
     }
     $newQuery = array_merge(GuzzlePsr7\parse_query($uri->getQuery()), $query);
     return $request->withUri($uri->withQuery(http_build_query($newQuery, null, '&')));
 }
 private function fetchSourceMetadata()
 {
     if ($this->config['source_metadata'] instanceof ResultInterface) {
         return $this->config['source_metadata'];
     }
     list($bucket, $key) = explode('/', ltrim($this->source, '/'), 2);
     $headParams = ['Bucket' => $bucket, 'Key' => $key];
     if (strpos($key, '?')) {
         list($key, $query) = explode('?', $key, 2);
         $headParams['Key'] = $key;
         $query = Psr7\parse_query($query, false);
         if (isset($query['versionId'])) {
             $headParams['VersionId'] = $query['versionId'];
         }
     }
     return $this->client->headObject($headParams);
 }
Exemple #16
0
 /**
  * Returns the parsed query string for the passed request as key-value array.
  *
  * @param RequestInterface $request
  *
  * @return array
  */
 protected function getQueryAsArray(RequestInterface $request)
 {
     return Psr7\parse_query($request->getUri()->getQuery());
 }
 /**
  * @When I retrieve :type with id :id and the query string :query
  *
  * @param string $type
  * @param string $id
  * @param string $query
  *
  * @return void
  */
 public function iRetrieveWithIdAndTheQueryString($type, $id, $query)
 {
     $this->getClient()->get($this->createUri($type, $id), parse_query($query, false));
 }
Exemple #18
0
 /**
  * Helper method to generate an alternative form of an URL, where array indices have either
  * been added or removed. foo[] is transformed into foo[0], while foo[0] is transformed into foo[].
  *
  * The result for URLs with both formats is undefined, or for URLs that intermingle their parameters,
  * i.e. t[]=foo&b[]=bar&t[]=baz
  *
  * This was introduced because of differences between the URLs generated by the different clients, and
  * because Facebook (at least) generates URLs were []s in URL arguments are expanded to [0] when
  * requested from the backend. Since we sign our URLs, this breaks the token generation and thus breaks
  * URLs when Facebook attempts to retrieve them.
  *
  * @param string $url The URL to generate the alternative form of
  * @param int $encoding The encoding to use - from GuzzleHttp\Psr7
  * @return string
  */
 protected function getAlternativeURL($url, $encoding = PHP_QUERY_RFC3986)
 {
     $urlParts = parse_url($url);
     if (!isset($urlParts['query'])) {
         return $url;
     }
     $queryString = $urlParts['query'];
     $fixKeyPattern = '#\\[[0-9]+\\]$#';
     $parsed = Psr7\parse_query($queryString);
     $newArguments = array();
     foreach ($parsed as $key => $value) {
         $fixedKey = preg_replace($fixKeyPattern, '', $key);
         // if the key came out different, we're talking about a t[x] format - so we store those
         // to allow for the correct sequence when regenerating the URL further below.
         if ($fixedKey != $key) {
             $fixedKey .= '[]';
             if (!isset($newArguments[$fixedKey])) {
                 $newArguments[$fixedKey] = array();
             }
             $newArguments[$fixedKey][] = $value;
         } else {
             if (is_array($value) && substr($key, -2) == '[]') {
                 // if the value is an array, and we have the [] format already, we expand the keys
                 foreach ($value as $innerKey => $innerValue) {
                     // remove [] from the key and append the inner array key
                     $indexedKey = substr($key, 0, -2) . '[' . $innerKey . ']';
                     $newArguments[$indexedKey] = $innerValue;
                 }
             } else {
                 $newArguments[$key] = $value;
             }
         }
     }
     $urlParts['query'] = Psr7\build_query($newArguments, $encoding);
     $url = Urls::buildFromParseUrlParts($urlParts);
     return $url;
 }