Skip to content

Commit

Permalink
ensure user agents are sent when using an API key (#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
dwsupplee authored and jdpedrie committed Mar 3, 2017
1 parent 9b06e34 commit 66f1789
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/RequestWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,29 +128,30 @@ public function send(RequestInterface $request, array $options = [])
$httpOptions = isset($options['httpOptions']) ? $options['httpOptions'] : $this->httpOptions;
$backoff = new ExponentialBackoff($retries, $this->getRetryFunction());

$signedRequest = $this->shouldSignRequest ? $this->signRequest($request) : $request;

try {
return $backoff->execute($this->httpHandler, [$signedRequest, $httpOptions]);
return $backoff->execute($this->httpHandler, [$this->applyHeaders($request), $httpOptions]);
} catch (\Exception $ex) {
throw $this->convertToGoogleException($ex);
}
}

/**
* Sign the request.
* Applies headers to the request.
*
* @param RequestInterface $request Psr7 request.
* @return RequestInterface
*/
private function signRequest(RequestInterface $request)
private function applyHeaders(RequestInterface $request)
{
$headers = [
'User-Agent' => 'gcloud-php/' . ServiceBuilder::VERSION,
'x-goog-api-client' => 'gl-php/' . phpversion() . ' gccl/' . ServiceBuilder::VERSION,
'Authorization' => 'Bearer ' . $this->getToken()
'x-goog-api-client' => 'gl-php/' . phpversion() . ' gccl/' . ServiceBuilder::VERSION
];

if ($this->shouldSignRequest) {
$headers['Authorization'] = 'Bearer ' . $this->getToken();
}

return Psr7\modify_request($request, ['set_headers' => $headers]);
}

Expand Down
20 changes: 20 additions & 0 deletions tests/unit/RequestWrapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,26 @@ public function testAddsTokenToRequest()
);
}

public function testRequestUsesApiKeyInsteadOfAuthHeader()
{
$requestWrapper = new RequestWrapper([
'httpHandler' => function ($request, $options = []) {
$authHeader = $request->getHeaderLine('Authorization');
$userAgent = $request->getHeaderLine('User-Agent');
$xGoogApiClient = $request->getHeaderLine('x-goog-api-client');
$this->assertEquals('gcloud-php/' . ServiceBuilder::VERSION, $userAgent);
$this->assertEquals('gl-php/' . phpversion() . ' gccl/' . ServiceBuilder::VERSION, $xGoogApiClient);
$this->assertEmpty($authHeader);
return new Response(200);
},
'shouldSignRequest' => false
]);

$requestWrapper->send(
new Request('GET', 'http://www.example.com')
);
}

/**
* @expectedException Google\Cloud\Exception\GoogleException
*/
Expand Down

0 comments on commit 66f1789

Please sign in to comment.