Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow unauthenticated requests and do not always require project ID #735

Merged
merged 3 commits into from
Nov 11, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/BigQuery/BigQueryClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ public function __construct(array $config = [])
]);
$config += [
'scopes' => [self::SCOPE],
'projectIdRequired' => true,
'returnInt64AsObject' => false,
'restRetryFunction' => $this->getRetryFunction(),
'restDelayFunction' => function ($attempt) {
Expand Down
67 changes: 67 additions & 0 deletions src/Core/AnonymousCredentials.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Cloud\Core;

use Google\Auth\FetchAuthTokenInterface;

/**
* Provides an anonymous set of credentials, which is useful for APIs which do
* not require authentication.
*/
class AnonymousCredentials implements FetchAuthTokenInterface
{
/**
* @var array
*/
private $token = [
'access_token' => null
];

/**
* Fetches the auth token. In this case it returns a null value.
*
* @param callable $httpHandler
* @return array
*/
public function fetchAuthToken(callable $httpHandler = null)
{
return $this->token;
}

/**
* Returns the cache key. In this case it returns a null value, disabling
* caching.
*
* @return string|null
*/
public function getCacheKey()
{
return null;
}

/**
* Fetches the last received token. In this case, it returns the same null
* auth token.
*
* @return array
*/
public function getLastReceivedToken()
{
return $this->token;
}
}
29 changes: 17 additions & 12 deletions src/Core/ClientTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ trait ClientTrait
use JsonTrait;

/**
* @var string The project ID created in the Google Developers Console.
* @var string|null The project ID created in the Google Developers Console.
*/
private $projectId;

Expand Down Expand Up @@ -75,14 +75,17 @@ private function getConnectionType(array $config)
private function configureAuthentication(array $config)
{
$config['keyFile'] = $this->getKeyFile($config);

$this->projectId = $this->detectProjectId($config);

if (!$config['keyFile'] && !isset($config['credentialsFetcher'])) {

This comment was marked as spam.

$config['credentialsFetcher'] = new AnonymousCredentials();
}

return $config;
}

/**
* Get a keyfile.
* Get a keyfile if it exists.
*
* Process:
* 1. If $config['keyFile'] is set, use that.
Expand All @@ -91,10 +94,9 @@ private function configureAuthentication(array $config)
* from that location and use that.
* 4. If OS-specific well-known-file is set, load from that location and use
* that.
* 5. Exception. :(
*
* @param array $config
* @return array Key data
* @return array|null Key data
* @throws GoogleException
*/
private function getKeyFile(array $config = [])
Expand All @@ -120,7 +122,7 @@ private function getKeyFile(array $config = [])
$keyFileData = $this->jsonDecode(file_get_contents($config['keyFilePath']), true);
} catch (\InvalidArgumentException $ex) {
throw new GoogleException(sprintf(
'Given keyfile at path %swas invalid',
'Given keyfile at path %s was invalid',
$config['keyFilePath']
));
}
Expand All @@ -140,7 +142,7 @@ private function getKeyFile(array $config = [])
* 2. If $config['keyFile'] is set, attempt to retrieve a project ID from
* that.
* 3. If code is running on compute engine, try to get the project ID from
* the metadata store
* the metadata store.
* 4. Throw exception.
*
* @param array $config
Expand All @@ -150,8 +152,9 @@ private function getKeyFile(array $config = [])
private function detectProjectId(array $config)
{
$config += [
'projectId' => null,
'httpHandler' => null,
'projectId' => null,
'projectIdRequired' => false
];

if ($config['projectId']) {
Expand All @@ -174,10 +177,12 @@ private function detectProjectId(array $config)
}
}

throw new GoogleException(
'No project ID was provided, ' .
'and we were unable to detect a default project ID.'
);
if ($config['projectIdRequired']) {
throw new GoogleException(
'No project ID was provided, ' .
'and we were unable to detect a default project ID.'
);
}
}

/**
Expand Down
8 changes: 6 additions & 2 deletions src/Core/RequestWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ public function __construct(array $config = [])
$this->shouldSignRequest = $config['shouldSignRequest'];
$this->retryFunction = $config['restRetryFunction'] ?: $this->getRetryFunction();
$this->delayFunction = $config['restDelayFunction'];

if ($this->credentialsFetcher instanceof AnonymousCredentials) {
$this->shouldSignRequest = false;
}
}

/**
Expand Down Expand Up @@ -215,8 +219,8 @@ private function fetchCredentials()
/**
* Convert any exception to a Google Exception.
*
* @param \Exception $ex
* @return ServiceException
* @param \Exception $ex
* @return ServiceException
*/
private function convertToGoogleException(\Exception $ex)
{
Expand Down
3 changes: 2 additions & 1 deletion src/Datastore/DatastoreClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ public function __construct(array $config = [])
$config += [
'namespaceId' => null,
'returnInt64AsObject' => false,
'scopes' => [self::FULL_CONTROL_SCOPE]
'scopes' => [self::FULL_CONTROL_SCOPE],
'projectIdRequired' => true
];

$this->connection = new Rest($this->configureAuthentication($config));
Expand Down
7 changes: 4 additions & 3 deletions src/Logging/LoggingClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,10 @@ public function __construct(array $config = [])
{
$this->config = $config;
$connectionType = $this->getConnectionType($config);
if (!isset($config['scopes'])) {
$config['scopes'] = [self::FULL_CONTROL_SCOPE];
}
$config += [
'scopes' => [self::FULL_CONTROL_SCOPE],
'projectIdRequired' => true
];

$this->connection = $connectionType === 'grpc'
? new Grpc($this->configureAuthentication($config))
Expand Down
7 changes: 4 additions & 3 deletions src/PubSub/PubSubClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,10 @@ public function __construct(array $config = [])
{
$this->clientConfig = $config;
$connectionType = $this->getConnectionType($config);
if (!isset($config['scopes'])) {
$config['scopes'] = [self::FULL_CONTROL_SCOPE];
}
$config += [
'scopes' => [self::FULL_CONTROL_SCOPE],
'projectIdRequired' => true
];

if ($connectionType === 'grpc') {
$this->connection = new Grpc($this->configureAuthentication($config));
Expand Down
3 changes: 2 additions & 1 deletion src/Spanner/SpannerClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ public function __construct(array $config = [])
self::FULL_CONTROL_SCOPE,
self::ADMIN_SCOPE
],
'returnInt64AsObject' => false
'returnInt64AsObject' => false,
'projectIdRequired' => true
];

$this->connection = new Grpc($this->configureAuthentication($config));
Expand Down
10 changes: 10 additions & 0 deletions src/Storage/Bucket.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
namespace Google\Cloud\Storage;

use Google\Cloud\Core\ArrayTrait;
use Google\Cloud\Core\Exception\GoogleException;
use Google\Cloud\Core\Exception\NotFoundException;
use Google\Cloud\Core\Exception\ServiceException;
use Google\Cloud\Core\Iam\Iam;
Expand Down Expand Up @@ -585,6 +586,7 @@ function (array $object) {
* @return Notification
* @throws \InvalidArgumentException When providing a type other than string
* or {@see Google\Cloud\PubSub\Topic} as $topic.
* @throws GoogleException When a project ID has not been detected.
* @experimental The experimental flag means that while we believe this
* method or class is ready for use, it may change before release in
* backwards-incompatible ways. Please use with caution, and test
Expand Down Expand Up @@ -1043,6 +1045,7 @@ private function isObjectNameRequired($data)
* @param Topic|string $topic
* @return string
* @throws \InvalidArgumentException
* @throws GoogleException
*/
private function getFormattedTopic($topic)
{
Expand All @@ -1060,6 +1063,13 @@ private function getFormattedTopic($topic)
return sprintf(self::NOTIFICATION_TEMPLATE, $topic);
}

if (!$this->projectId) {
throw new GoogleException(
'No project ID was provided, ' .
'and we were unable to detect a default project ID.'
);
}

return sprintf(
self::NOTIFICATION_TEMPLATE,
sprintf(self::TOPIC_TEMPLATE, $this->projectId, $topic)
Expand Down
22 changes: 17 additions & 5 deletions src/Storage/StorageClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

use Google\Cloud\Core\ArrayTrait;
use Google\Cloud\Core\ClientTrait;
use Google\Cloud\Core\Exception\GoogleException;
use Google\Cloud\Core\Iterator\ItemIterator;
use Google\Cloud\Core\Iterator\PageIterator;
use Google\Cloud\Core\Timestamp;
Expand Down Expand Up @@ -177,17 +178,22 @@ public function bucket($name, $userProject = false)
* this option has no effect. **Defaults to** `true`.
* }
* @return ItemIterator<Google\Cloud\Storage\Bucket>
* @throws GoogleException When a project ID has not been detected.
*/
public function buckets(array $options = [])
{
$resultLimit = $this->pluck('resultLimit', $options, false);
if (!$this->projectId) {
throw new GoogleException(
'No project ID was provided, ' .
'and we were unable to detect a default project ID.'
);
}

$resultLimit = $this->pluck('resultLimit', $options, false);
$bucketUserProject = $this->pluck('bucketUserProject', $options, false);

$bucketUserProject = !is_null($bucketUserProject)
? $bucketUserProject
: true;

$userProject = (isset($options['userProject']) && $bucketUserProject)
? $options['userProject']
: null;
Expand Down Expand Up @@ -281,15 +287,21 @@ function (array $bucket) use ($userProject) {
* this option has no effect. **Defaults to** `true`.
* }
* @return Bucket
* @throws GoogleException When a project ID has not been detected.
*/
public function createBucket($name, array $options = [])
{
$bucketUserProject = $this->pluck('bucketUserProject', $options, false);
if (!$this->projectId) {
throw new GoogleException(
'No project ID was provided, ' .
'and we were unable to detect a default project ID.'
);
}

$bucketUserProject = $this->pluck('bucketUserProject', $options, false);
$bucketUserProject = !is_null($bucketUserProject)
? $bucketUserProject
: true;

$userProject = (isset($options['userProject']) && $bucketUserProject)
? $options['userProject']
: null;
Expand Down
7 changes: 4 additions & 3 deletions src/Trace/TraceClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,10 @@ class TraceClient
public function __construct(array $config = [])
{
$this->clientConfig = $config;
if (!isset($config['scopes'])) {
$config['scopes'] = [self::FULL_CONTROL_SCOPE];
}
$config += [
'scopes' => [self::FULL_CONTROL_SCOPE],
'projectIdRequired' => true
];

$this->connection = new Rest($this->configureAuthentication($config));
}
Expand Down
Loading