public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { // Ensure that the signable query string parameters are sorted sort($this->signableQueryString); // Add the security token header if one is being used by the credentials if ($token = $credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $token); } $request->removeHeader('x-amz-date'); $request->setHeader('Date', gmdate(\DateTime::RFC2822)); $stringToSign = $this->createCanonicalizedString($request); $request->getParams()->set('aws.string_to_sign', $stringToSign); $request->setHeader('Authorization', 'AWS ' . $credentials->getAccessKeyId() . ':' . $this->signString($stringToSign, $credentials)); // COMMONLOG(DEBUG, "send header:%s",$request->getRawHeaders()); // if(self::$isFile) // { // if(self::$filePath) // COMMONLOG(DEBUG, "souce file:%s",self::$filePath); // } // else // { // if(get_class($request) === 'Guzzle\Http\Message\EntityEnclosingRequest' && get_class($request->getBody()) === 'Guzzle\Http\EntityBody' && $request->getBody()->getContentLength() != 0) // { // COMMONLOG(DEBUG, "send msg:%s",$request->getBody()); // } // } }
/** * {@inheritdoc} */ public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { // Refresh the cached timestamp $this->getTimestamp(true); // Add default headers $request->setHeader('x-amz-date', $this->getDateTime(DateFormat::RFC1123)); // Add the security token if one is present if ($credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $credentials->getSecurityToken()); } // Grab the path and ensure that it is absolute $path = '/' . ltrim($request->getUrl(true)->normalizePath()->getPath(), '/'); // Begin building the string to sign $sign = $request->getMethod() . "\n" . "{$path}\n" . $this->getCanonicalizedQueryString($request) . "\n"; // Get all of the headers that must be signed (host and x-amz-*) $headers = $this->getHeadersToSign($request); foreach ($headers as $key => $value) { $sign .= $key . ':' . $value . "\n"; } $sign .= "\n"; // Add the body of the request if a body is present if ($request instanceof EntityEnclosingRequestInterface) { $sign .= (string) $request->getBody(); } // Add the string to sign to the request for debugging purposes $request->getParams()->set('aws.string_to_sign', $sign); $signature = base64_encode(hash_hmac('sha256', hash('sha256', $sign, true), $credentials->getSecretKey(), true)); // Add the authorization header to the request $request->setHeader('x-amzn-authorization', sprintf('AWS3 AWSAccessKeyId=%s,Algorithm=HmacSHA256,SignedHeaders=%s,Signature=%s', $credentials->getAccessKeyId(), implode(';', array_keys($headers)), $signature)); }
/** * @param RequestInterface|EntityEnclosingRequestInterface $request * @param Credentials $credentials */ public function signRequest($request, $credentials) { $request->setHeader('X-HMB-Signature-Method', self::DEFAULT_METHOD); $request->setHeader('X-HMB-Signature-Version', self::DEFAULT_SIGN_VERSION); $request->setHeader('X-HMB-TimeStamp', time()); $contentMd5 = $request instanceof EntityEnclosingRequestInterface ? md5($request->getBody()) : ''; if ($contentMd5) { $request->setHeader('Content-MD5', $contentMd5); } $sign = array(); $sign[] = strtoupper($request->getMethod()); $sign[] = $request->getHost(); if ($request->getHeader('Content-MD5')) { $sign[] = $request->getHeader('Content-MD5'); } if ($request->getHeader('Content-Type')) { $sign[] = $request->getHeader('Content-Type'); } $sign[] = $request->getHeader('X-HMB-Signature-Method'); $sign[] = $request->getHeader('X-HMB-Signature-Version'); $sign[] = $request->getHeader('X-HMB-TimeStamp'); if ($request->getHeader('X-HMB-User-Session-Token')) { $sign[] = $request->getHeader('X-HMB-User-Session-Token'); } $sign[] = $request->getQuery(true) ? $request->getPath() . '?' . $request->getQuery(true) : $request->getPath(); $signature = base64_encode(hash_hmac(strtolower($request->getHeader('X-HMB-Signature-Method')), implode("\n", $sign), $credentials->getSecret())); $request->setHeader('Authorization', sprintf('%s %s:%s', self::AUTHORIZATION_SCHME, $credentials->getKey(), $signature)); }
public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()) { $request->setHeader('X-Amz-Content-Sha256', EntityBody::getHash($request->getBody(), 'sha256')); } else { $request->setHeader('X-Amz-Content-Sha256', hash('sha256', '')); } parent::signRequest($request, $credentials); }
/** * {@inheritdoc} */ public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { // Add a date header if one is not set if (!$request->hasHeader('date') && !$request->hasHeader('x-amz-date')) { $request->setHeader('Date', gmdate(DateFormat::RFC2822)); } $stringToSign = (string) $request->getHeader('Date') ?: (string) $request->getHeader('x-amz-date'); $request->getParams()->set('aws.string_to_sign', $stringToSign); $request->setHeader('Authorization', 'AWS ' . $credentials->getAccessKeyId() . ':' . $this->signString($stringToSign, $credentials)); }
/** * {@inheritdoc} */ public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { // Add the security token header if one is being used by the credentials if ($token = $credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $token); } // Add a date header if one is not set if (!$request->hasHeader('date') && !$request->hasHeader('x-amz-date')) { $request->setHeader('Date', gmdate(DateFormat::RFC2822)); } $stringToSign = $this->createCanonicalizedString($request); $request->getParams()->set('aws.string_to_sign', $stringToSign); $request->setHeader('Authorization', 'AWS ' . $credentials->getAccessKeyId() . ':' . $this->signString($stringToSign, $credentials)); }
public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { // Ensure that the signable query string parameters are sorted sort($this->signableQueryString); // Add the security token header if one is being used by the credentials if ($token = $credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $token); } $request->removeHeader('x-amz-date'); $request->setHeader('Date', gmdate(\DateTime::RFC2822)); $stringToSign = $this->createCanonicalizedString($request); $request->getParams()->set('aws.string_to_sign', $stringToSign); $request->setHeader('Authorization', 'AWS ' . $credentials->getAccessKeyId() . ':' . $this->signString($stringToSign, $credentials)); }
public function after(CommandInterface $command, RequestInterface $request) { $xml = null; if (isset($this->data[$command])) { $xml = $this->finishDocument($this->data[$command]); unset($this->data[$command]); } else { $operation = $command->getOperation(); if ($operation->getData('xmlAllowEmpty')) { $xmlWriter = $this->createRootElement($operation); $xml = $this->finishDocument($xmlWriter); } } if ($xml) { if ($this->contentType && !$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->contentType); } $request->setBody($xml); } }
/** * Always add a x-amz-content-sha-256 for data integrity. */ public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { if ($request instanceof EntityEnclosingRequestInterface && $request->getBody() && !$request->hasHeader('x-amz-content-sha256')) { $request->setHeader('X-Amz-Content-Sha256', $this->getPresignedPayload($request)); } parent::signRequest($request, $credentials); }
/** * @param RequestInterface $request * * @return RequestInterface */ private function setHeaders(RequestInterface $request) { foreach ($this->headers as $name => $value) { $request->setHeader($name, $value); } return $request; }
/** * Always add a x-amz-content-sha-256 for data integrity. */ public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { if (!$request->hasHeader('x-amz-content-sha256')) { $request->setHeader('x-amz-content-sha256', $this->getPayload($request)); } parent::signRequest($request, $credentials); }
public function after(CommandInterface $command, RequestInterface $request) { if (isset($this->data[$command])) { if ($this->jsonContentType && !$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->jsonContentType); } $request->setBody(json_encode($this->data[$command])); unset($this->data[$command]); } }
/** * {@inheritdoc} */ public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { // Add a date header if one is not set if (!$request->hasHeader('date') && !$request->hasHeader('x-amz-date')) { $request->setHeader('Date', $this->getDateTime(DateFormat::RFC1123)); } // Add the security token if one is present if ($credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $credentials->getSecurityToken()); } // Determine the string to sign $stringToSign = $request->getHeader('Date', true) ?: $request->getHeader('x-amz-date', true); $request->getParams()->set('aws.string_to_sign', $stringToSign); // Calculate the signature $signature = base64_encode(hash_hmac('sha256', $stringToSign, $credentials->getSecretKey(), true)); // Add the authorization header to the request $headerFormat = 'AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s'; $request->setHeader('X-Amzn-Authorization', sprintf($headerFormat, $credentials->getAccessKeyId(), $signature)); }
/** * Add a prefixed array of headers to the request * * @param RequestInterface $request Request to update * @param Parameter $param Parameter object * @param array $value Header array to add * * @throws InvalidArgumentException */ protected function addPrefixedHeaders(RequestInterface $request, Parameter $param, $value) { if (!is_array($value)) { throw new InvalidArgumentException('An array of mapped headers expected, but received a single value'); } $prefix = $param->getSentAs(); foreach ($value as $headerName => $headerValue) { $request->setHeader($prefix . $headerName, $headerValue); } }
/** * {@inheritdoc} */ public function after(CommandInterface $command, RequestInterface $request) { if (isset($this->data[$command])) { $xml = $this->data[$command]; unset($this->data[$command]); $request->setBody($xml->asXML()); if ($this->contentType) { $request->setHeader('Content-Type', $this->contentType); } } }
/** * {@inheritdoc} */ public function after(CommandInterface $command, RequestInterface $request) { if (isset($this->data[$command])) { $json = $this->data[$command]; unset($this->data[$command]); $request->setBody(json_encode($json))->removeHeader('Expect'); if ($this->jsonContentType) { $request->setHeader('Content-Type', $this->jsonContentType); } } }
/** * {@inheritdoc} */ public function after(CommandInterface $command, RequestInterface $request) { if (isset($this->data[$command])) { $request->setBody($this->data[$command]->asXML()); unset($this->data[$command]); // Don't overwrite the Content-Type if one is set if ($this->contentType && !$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->contentType); } } }
/** * {@inheritdoc} */ public function after(CommandInterface $command, RequestInterface $request) { if (isset($this->data[$command])) { $json = $this->data[$command]; unset($this->data[$command]); $request->setBody(json_encode($json)); // Don't overwrite the Content-Type if one is set if ($this->jsonContentType && !$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->jsonContentType); } } }
/** * {@inheritdoc} */ public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) { $filteredValue = $param->filter($value); if (null !== $this->serializer && (is_object($filteredValue) || is_array($filteredValue))) { switch ($param->getSentAs()) { case 'json': $request->setHeader('Content-Type', 'application/json'); $contentType = 'json'; break; case 'yml': case 'yaml': $request->setHeader('Content-Type', 'application/yaml'); $contentType = 'yml'; break; default: $request->setHeader('Content-Type', 'application/xml'); $contentType = 'xml'; break; } $context = SerializationContext::create(); if (null !== ($groups = $param->getData('jms_serializer.groups'))) { $context->setGroups($groups); } if (null !== ($version = $param->getData('jms_serializer.version'))) { $context->setVersion($version); } if (null !== ($nulls = $param->getData('jms_serializer.serialize_nulls'))) { $context->setSerializeNull($nulls); } if (true === $param->getData('jms_serializer.max_depth_checks')) { $context->enableMaxDepthChecks(); } $value = $this->serializer->serialize($filteredValue, $contentType, $context); } parent::visit($command, $request, $param, $value); }
/** * Sends a request * * @param RequestInterface $request * @return Response * @throws ForbiddenException * @throws MetricaException */ protected function sendRequest(RequestInterface $request) { try { $request->setHeader('User-Agent', $this->getUserAgent()); $response = $request->send(); } catch (ClientErrorResponseException $ex) { $result = $request->getResponse(); $code = $result->getStatusCode(); $message = $result->getReasonPhrase(); if ($code === 403) { throw new ForbiddenException($message); } throw new MetricaException('Service responded with error code: "' . $code . '" and message: "' . $message . '"'); } return $response; }
/** * {@inheritdoc} */ protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { if ($response && $response->getStatusCode() == 400 && strpos($response->getBody(), self::ERR)) { // Check if the request is sending a local file, and if so, clear the stat cache and recalculate the size. if ($request instanceof EntityEnclosingRequestInterface) { if ($request->getBody()->getWrapper() == 'plainfile') { $filename = $request->getBody()->getUri(); // Clear the cache so that we send accurate file sizes clearstatcache(true, $filename); $length = filesize($filename); $request->getBody()->setSize($length); $request->setHeader('Content-Length', $length); } } return true; } }
public function after(CommandInterface $command, RequestInterface $request) { $xml = null; // If data was found that needs to be serialized, then do so if (isset($this->data[$command])) { $xml = $this->data[$command]->asXML(); unset($this->data[$command]); } else { // Check if XML should always be sent for the command $operation = $command->getOperation(); if ($operation->getData('xmlAllowEmpty')) { $xml = $this->createRootElement($operation)->asXML(); } } if ($xml) { $request->setBody($xml); // Don't overwrite the Content-Type if one is set if ($this->contentType && !$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->contentType); } } }
/** * Send datas trough HTTP client * * @param HttpRequestInterface $request * * @param bool $stopOnException * * @return HttpResponse * @throws \Exception */ protected function send(HttpRequestInterface $request, $stopOnException = false) { $request->setHeader('Content-Type', 'application/json')->setHeader('X-Auth-Token', array($this->token))->setHeader('X-Auth-UserId', array($this->userId)); try { $response = $request->send(); } catch (ClientErrorResponseException $e) { if (!$stopOnException && 401 == $e->getResponse()->getStatusCode() && null != $this->username) { // If the HTTP error is 401 Unauthorized, the session is cleared $username = $this->username; $password = $this->password; $this->clearSession(); // Then we try a new authentication $this->getUserToken($username, $password); // Then we resend the request once $response = $this->send($request, true); } else { throw $e; } } if (!$response) { throw new \Exception(__NAMESPACE__ . '\\' . __CLASS__ . ' : Bad response while sending the request'); } return $response; }
/** * Update a request based on the log messages of the CurlHandle * * @param RequestInterface $request Request to update */ public function updateRequestFromTransfer(RequestInterface $request) { if (!$request->getResponse()) { return; } // Update the transfer stats of the response $request->getResponse()->setInfo($this->getInfo()); if (!($log = $this->getStderr(true))) { return; } // Parse the cURL stderr output for outgoing requests $headers = ''; fseek($log, 0); while (($line = fgets($log)) !== false) { if ($line && $line[0] == '>') { $headers = substr(trim($line), 2) . "\r\n"; while (($line = fgets($log)) !== false) { if ($line[0] == '*' || $line[0] == '<') { break; } else { $headers .= trim($line) . "\r\n"; } } } } // Add request headers to the request exactly as they were sent if ($headers) { $parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($headers); if (!empty($parsed['headers'])) { $request->setHeaders(array()); foreach ($parsed['headers'] as $name => $value) { $request->setHeader($name, $value); } } if (!empty($parsed['version'])) { $request->setProtocolVersion($parsed['version']); } } }
/** * Prepare a request to be sent from the Client by adding client specific behaviors and properties to the request. * * @param RequestInterface $request Request to prepare for the client * @param array $options Options to apply to the request * * @return RequestInterface */ protected function prepareRequest(RequestInterface $request, array $options = array()) { $request->setClient($this)->setEventDispatcher(clone $this->getEventDispatcher()); if ($curl = $this->config[self::CURL_OPTIONS]) { $request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($curl)); } if ($params = $this->config[self::REQUEST_PARAMS]) { Version::warn('request.params is deprecated. Use request.options to add default request options.'); $request->getParams()->overwriteWith($params); } if ($this->userAgent && !$request->hasHeader('User-Agent')) { $request->setHeader('User-Agent', $this->userAgent); } if ($defaults = $this->config[self::REQUEST_OPTIONS]) { $this->requestFactory->applyOptions($request, $defaults, RequestFactoryInterface::OPTIONS_AS_DEFAULTS); } if ($options) { $this->requestFactory->applyOptions($request, $options); } $this->dispatch('client.create_request', array('client' => $this, 'request' => $request)); return $request; }
public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { $timestamp = $this->getTimestamp(); $longDate = gmdate(DateFormat::ISO8601, $timestamp); $shortDate = substr($longDate, 0, 8); // Remove any previously set Authorization headers so that retries work $request->removeHeader('Authorization'); // Requires a x-amz-date header or Date if ($request->hasHeader('x-amz-date') || !$request->hasHeader('Date')) { $request->setHeader('x-amz-date', $longDate); } else { $request->setHeader('Date', gmdate(DateFormat::RFC1123, $timestamp)); } // Add the security token if one is present if ($credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $credentials->getSecurityToken()); } // Parse the service and region or use one that is explicitly set $region = $this->regionName; $service = $this->serviceName; if (!$region || !$service) { $url = Url::factory($request->getUrl()); $region = $region ?: HostNameUtils::parseRegionName($url); $service = $service ?: HostNameUtils::parseServiceName($url); } $credentialScope = "{$shortDate}/{$region}/{$service}/aws4_request"; // Calculate the request signature payload if ($request->hasHeader('x-amz-content-sha256')) { // Handle streaming operations (e.g. Glacier.UploadArchive) $payload = $request->getHeader('x-amz-content-sha256'); } elseif ($request instanceof EntityEnclosingRequestInterface) { $payload = hash('sha256', $request->getMethod() == 'POST' && count($request->getPostFields()) ? (string) $request->getPostFields() : (string) $request->getBody()); } else { // Use the default payload if there is no body $payload = self::DEFAULT_PAYLOAD; } $signingContext = $this->createSigningContext($request, $payload); $signingContext['string_to_sign'] = "AWS4-HMAC-SHA256\n{$longDate}\n{$credentialScope}\n" . hash('sha256', $signingContext['canonical_request']); // Calculate the signing key using a series of derived keys $signingKey = $this->getSigningKey($shortDate, $region, $service, $credentials->getSecretKey()); $signature = hash_hmac('sha256', $signingContext['string_to_sign'], $signingKey); $request->setHeader('Authorization', "AWS4-HMAC-SHA256 " . "Credential={$credentials->getAccessKeyId()}/{$credentialScope}, " . "SignedHeaders={$signingContext['signed_headers']}, Signature={$signature}"); // Add debug information to the request $request->getParams()->set('aws.signature', $signingContext); }
/** * @param string $name * @param string|string[] $value * @return static * @throws \InvalidArgumentException */ public function withAddedHeader($name, $value) { $this->request->setHeader($name, $value); return $this; }
/** * {@inheritdoc} */ public function visit(CommandInterface $command, RequestInterface $request, $key, $value) { $request->setHeader($key, $value); }
protected function visit_headers(RequestInterface $request, $value, $flags) { if (!is_array($value)) { throw new InvalidArgumentException('headers value must be an array'); } if ($flags & self::OPTIONS_AS_DEFAULTS) { foreach ($value as $key => $header) { if (!$request->hasHeader($key)) { $request->setHeader($key, $header); } } } else { $request->addHeaders($value); } }
public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { $timestamp = $this->getTimestamp(); $longDate = gmdate(DateFormat::ISO8601, $timestamp); $shortDate = substr($longDate, 0, 8); // Remove any previously set Authorization headers so that retries work $request->removeHeader('Authorization'); // Requires a x-amz-date header or Date if ($request->hasHeader('x-amz-date') || !$request->hasHeader('Date')) { $request->setHeader('x-amz-date', $longDate); } else { $request->setHeader('Date', gmdate(DateFormat::RFC1123, $timestamp)); } // Add the security token if one is present if ($credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $credentials->getSecurityToken()); } // Parse the service and region or use one that is explicitly set $region = $this->regionName; $service = $this->serviceName; if (!$region || !$service) { $url = Url::factory($request->getUrl()); $region = $region ?: HostNameUtils::parseRegionName($url); $service = $service ?: HostNameUtils::parseServiceName($url); } $credentialScope = $this->createScope($shortDate, $region, $service); $payload = $this->getPayload($request); $signingContext = $this->createSigningContext($request, $payload); $signingContext['string_to_sign'] = $this->createStringToSign($longDate, $credentialScope, $signingContext['canonical_request']); // Calculate the signing key using a series of derived keys $signingKey = $this->getSigningKey($shortDate, $region, $service, $credentials->getSecretKey()); $signature = hash_hmac('sha256', $signingContext['string_to_sign'], $signingKey); $request->setHeader('Authorization', "AWS4-HMAC-SHA256 " . "Credential={$credentials->getAccessKeyId()}/{$credentialScope}, " . "SignedHeaders={$signingContext['signed_headers']}, Signature={$signature}"); // Add debug information to the request $request->getParams()->set('aws.signature', $signingContext); }