| 1 |
<?php |
| 2 |
/* |
| 3 |
* Copyright 2015 Google Inc. |
| 4 |
* |
| 5 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
* you may not use this file except in compliance with the License. |
| 7 |
* You may obtain a copy of the License at |
| 8 |
* |
| 9 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
* |
| 11 |
* Unless required by applicable law or agreed to in writing, software |
| 12 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
* See the License for the specific language governing permissions and |
| 15 |
* limitations under the License. |
| 16 |
*/ |
| 17 |
|
| 18 |
namespace Google\Auth; |
| 19 |
|
| 20 |
use Google\Auth\Credentials\InsecureCredentials; |
| 21 |
use Google\Auth\Credentials\ServiceAccountCredentials; |
| 22 |
use Google\Auth\Credentials\UserRefreshCredentials; |
| 23 |
use GuzzleHttp\ClientInterface; |
| 24 |
|
| 25 |
/** |
| 26 |
* CredentialsLoader contains the behaviour used to locate and find default |
| 27 |
* credentials files on the file system. |
| 28 |
*/ |
| 29 |
abstract class CredentialsLoader implements FetchAuthTokenInterface |
| 30 |
{ |
| 31 |
const TOKEN_CREDENTIAL_URI = 'https://oauth2.googleapis.com/token'; |
| 32 |
const ENV_VAR = 'GOOGLE_APPLICATION_CREDENTIALS'; |
| 33 |
const WELL_KNOWN_PATH = 'gcloud/application_default_credentials.json'; |
| 34 |
const NON_WINDOWS_WELL_KNOWN_PATH_BASE = '.config'; |
| 35 |
const AUTH_METADATA_KEY = 'authorization'; |
| 36 |
|
| 37 |
/** |
| 38 |
* @param string $cause |
| 39 |
* @return string |
| 40 |
*/ |
| 41 |
private static function unableToReadEnv($cause) |
| 42 |
{ |
| 43 |
$msg = 'Unable to read the credential file specified by '; |
| 44 |
$msg .= ' GOOGLE_APPLICATION_CREDENTIALS: '; |
| 45 |
$msg .= $cause; |
| 46 |
|
| 47 |
return $msg; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* @return bool |
| 52 |
*/ |
| 53 |
private static function isOnWindows() |
| 54 |
{ |
| 55 |
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Returns the currently available major Guzzle version. |
| 60 |
* |
| 61 |
* @return int |
| 62 |
*/ |
| 63 |
private static function getGuzzleMajorVersion() |
| 64 |
{ |
| 65 |
if (defined('GuzzleHttp\ClientInterface::MAJOR_VERSION')) { |
| 66 |
return ClientInterface::MAJOR_VERSION; |
| 67 |
} |
| 68 |
|
| 69 |
if (defined('GuzzleHttp\ClientInterface::VERSION')) { |
| 70 |
return (int) substr(ClientInterface::VERSION, 0, 1); |
| 71 |
} |
| 72 |
|
| 73 |
throw new \Exception('Version not supported'); |
| 74 |
} |
| 75 |
|
| 76 |
/** |
| 77 |
* Load a JSON key from the path specified in the environment. |
| 78 |
* |
| 79 |
* Load a JSON key from the path specified in the environment |
| 80 |
* variable GOOGLE_APPLICATION_CREDENTIALS. Return null if |
| 81 |
* GOOGLE_APPLICATION_CREDENTIALS is not specified. |
| 82 |
* |
| 83 |
* @return array|null JSON key | null |
| 84 |
*/ |
| 85 |
public static function fromEnv() |
| 86 |
{ |
| 87 |
$path = getenv(self::ENV_VAR); |
| 88 |
if (empty($path)) { |
| 89 |
return; |
| 90 |
} |
| 91 |
if (!file_exists($path)) { |
| 92 |
$cause = 'file ' . $path . ' does not exist'; |
| 93 |
throw new \DomainException(self::unableToReadEnv($cause)); |
| 94 |
} |
| 95 |
$jsonKey = file_get_contents($path); |
| 96 |
return json_decode($jsonKey, true); |
| 97 |
} |
| 98 |
|
| 99 |
/** |
| 100 |
* Load a JSON key from a well known path. |
| 101 |
* |
| 102 |
* The well known path is OS dependent: |
| 103 |
* |
| 104 |
* * windows: %APPDATA%/gcloud/application_default_credentials.json |
| 105 |
* * others: $HOME/.config/gcloud/application_default_credentials.json |
| 106 |
* |
| 107 |
* If the file does not exist, this returns null. |
| 108 |
* |
| 109 |
* @return array|null JSON key | null |
| 110 |
*/ |
| 111 |
public static function fromWellKnownFile() |
| 112 |
{ |
| 113 |
$rootEnv = self::isOnWindows() ? 'APPDATA' : 'HOME'; |
| 114 |
$path = [getenv($rootEnv)]; |
| 115 |
if (!self::isOnWindows()) { |
| 116 |
$path[] = self::NON_WINDOWS_WELL_KNOWN_PATH_BASE; |
| 117 |
} |
| 118 |
$path[] = self::WELL_KNOWN_PATH; |
| 119 |
$path = implode(DIRECTORY_SEPARATOR, $path); |
| 120 |
if (!file_exists($path)) { |
| 121 |
return; |
| 122 |
} |
| 123 |
$jsonKey = file_get_contents($path); |
| 124 |
return json_decode($jsonKey, true); |
| 125 |
} |
| 126 |
|
| 127 |
/** |
| 128 |
* Create a new Credentials instance. |
| 129 |
* |
| 130 |
* @param string|array $scope the scope of the access request, expressed |
| 131 |
* either as an Array or as a space-delimited String. |
| 132 |
* @param array $jsonKey the JSON credentials. |
| 133 |
* @return ServiceAccountCredentials|UserRefreshCredentials |
| 134 |
*/ |
| 135 |
public static function makeCredentials($scope, array $jsonKey) |
| 136 |
{ |
| 137 |
if (!array_key_exists('type', $jsonKey)) { |
| 138 |
throw new \InvalidArgumentException('json key is missing the type field'); |
| 139 |
} |
| 140 |
|
| 141 |
if ($jsonKey['type'] == 'service_account') { |
| 142 |
return new ServiceAccountCredentials($scope, $jsonKey); |
| 143 |
} |
| 144 |
|
| 145 |
if ($jsonKey['type'] == 'authorized_user') { |
| 146 |
return new UserRefreshCredentials($scope, $jsonKey); |
| 147 |
} |
| 148 |
|
| 149 |
throw new \InvalidArgumentException('invalid value in the type field'); |
| 150 |
} |
| 151 |
|
| 152 |
/** |
| 153 |
* Create an authorized HTTP Client from an instance of FetchAuthTokenInterface. |
| 154 |
* |
| 155 |
* @param FetchAuthTokenInterface $fetcher is used to fetch the auth token |
| 156 |
* @param array $httpClientOptions (optional) Array of request options to apply. |
| 157 |
* @param callable $httpHandler (optional) http client to fetch the token. |
| 158 |
* @param callable $tokenCallback (optional) function to be called when a new token is fetched. |
| 159 |
* @return \GuzzleHttp\Client |
| 160 |
*/ |
| 161 |
public static function makeHttpClient( |
| 162 |
FetchAuthTokenInterface $fetcher, |
| 163 |
array $httpClientOptions = [], |
| 164 |
callable $httpHandler = null, |
| 165 |
callable $tokenCallback = null |
| 166 |
) { |
| 167 |
if (self::getGuzzleMajorVersion() === 5) { |
| 168 |
$client = new \GuzzleHttp\Client($httpClientOptions); |
| 169 |
$client->setDefaultOption('auth', 'google_auth'); |
| 170 |
$subscriber = new Subscriber\AuthTokenSubscriber( |
| 171 |
$fetcher, |
| 172 |
$httpHandler, |
| 173 |
$tokenCallback |
| 174 |
); |
| 175 |
$client->getEmitter()->attach($subscriber); |
| 176 |
return $client; |
| 177 |
} |
| 178 |
|
| 179 |
$middleware = new Middleware\AuthTokenMiddleware( |
| 180 |
$fetcher, |
| 181 |
$httpHandler, |
| 182 |
$tokenCallback |
| 183 |
); |
| 184 |
$stack = \GuzzleHttp\HandlerStack::create(); |
| 185 |
$stack->push($middleware); |
| 186 |
|
| 187 |
return new \GuzzleHttp\Client([ |
| 188 |
'handler' => $stack, |
| 189 |
'auth' => 'google_auth', |
| 190 |
] + $httpClientOptions); |
| 191 |
} |
| 192 |
|
| 193 |
/** |
| 194 |
* Create a new instance of InsecureCredentials. |
| 195 |
* |
| 196 |
* @return InsecureCredentials |
| 197 |
*/ |
| 198 |
public static function makeInsecureCredentials() |
| 199 |
{ |
| 200 |
return new InsecureCredentials(); |
| 201 |
} |
| 202 |
|
| 203 |
/** |
| 204 |
* export a callback function which updates runtime metadata. |
| 205 |
* |
| 206 |
* @return array updateMetadata function |
| 207 |
*/ |
| 208 |
public function getUpdateMetadataFunc() |
| 209 |
{ |
| 210 |
return array($this, 'updateMetadata'); |
| 211 |
} |
| 212 |
|
| 213 |
/** |
| 214 |
* Updates metadata with the authorization token. |
| 215 |
* |
| 216 |
* @param array $metadata metadata hashmap |
| 217 |
* @param string $authUri optional auth uri |
| 218 |
* @param callable $httpHandler callback which delivers psr7 request |
| 219 |
* @return array updated metadata hashmap |
| 220 |
*/ |
| 221 |
public function updateMetadata( |
| 222 |
$metadata, |
| 223 |
$authUri = null, |
| 224 |
callable $httpHandler = null |
| 225 |
) { |
| 226 |
$result = $this->fetchAuthToken($httpHandler); |
| 227 |
if (!isset($result['access_token'])) { |
| 228 |
return $metadata; |
| 229 |
} |
| 230 |
$metadata_copy = $metadata; |
| 231 |
$metadata_copy[self::AUTH_METADATA_KEY] = array('Bearer ' . $result['access_token']); |
| 232 |
|
| 233 |
return $metadata_copy; |
| 234 |
} |
| 235 |
} |
| 236 |
|