CredentialsLoader.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. namespace Google\Auth;
  18. use Google\Auth\Credentials\ExternalAccountCredentials;
  19. use Google\Auth\Credentials\ImpersonatedServiceAccountCredentials;
  20. use Google\Auth\Credentials\InsecureCredentials;
  21. use Google\Auth\Credentials\ServiceAccountCredentials;
  22. use Google\Auth\Credentials\UserRefreshCredentials;
  23. use RuntimeException;
  24. use UnexpectedValueException;
  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
  30. GetUniverseDomainInterface,
  31. FetchAuthTokenInterface,
  32. UpdateMetadataInterface
  33. {
  34. use UpdateMetadataTrait;
  35. const TOKEN_CREDENTIAL_URI = 'https://oauth2.googleapis.com/token';
  36. const ENV_VAR = 'GOOGLE_APPLICATION_CREDENTIALS';
  37. const QUOTA_PROJECT_ENV_VAR = 'GOOGLE_CLOUD_QUOTA_PROJECT';
  38. const WELL_KNOWN_PATH = 'gcloud/application_default_credentials.json';
  39. const NON_WINDOWS_WELL_KNOWN_PATH_BASE = '.config';
  40. const MTLS_WELL_KNOWN_PATH = '.secureConnect/context_aware_metadata.json';
  41. const MTLS_CERT_ENV_VAR = 'GOOGLE_API_USE_CLIENT_CERTIFICATE';
  42. /**
  43. * @param string $cause
  44. * @return string
  45. */
  46. private static function unableToReadEnv($cause)
  47. {
  48. $msg = 'Unable to read the credential file specified by ';
  49. $msg .= ' GOOGLE_APPLICATION_CREDENTIALS: ';
  50. $msg .= $cause;
  51. return $msg;
  52. }
  53. /**
  54. * @return bool
  55. */
  56. private static function isOnWindows()
  57. {
  58. return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
  59. }
  60. /**
  61. * Load a JSON key from the path specified in the environment.
  62. *
  63. * Load a JSON key from the path specified in the environment
  64. * variable GOOGLE_APPLICATION_CREDENTIALS. Return null if
  65. * GOOGLE_APPLICATION_CREDENTIALS is not specified.
  66. *
  67. * @return array<mixed>|null JSON key | null
  68. */
  69. public static function fromEnv()
  70. {
  71. $path = getenv(self::ENV_VAR);
  72. if (empty($path)) {
  73. return null;
  74. }
  75. if (!file_exists($path)) {
  76. $cause = 'file ' . $path . ' does not exist';
  77. throw new \DomainException(self::unableToReadEnv($cause));
  78. }
  79. $jsonKey = file_get_contents($path);
  80. return json_decode((string) $jsonKey, true);
  81. }
  82. /**
  83. * Load a JSON key from a well known path.
  84. *
  85. * The well known path is OS dependent:
  86. *
  87. * * windows: %APPDATA%/gcloud/application_default_credentials.json
  88. * * others: $HOME/.config/gcloud/application_default_credentials.json
  89. *
  90. * If the file does not exist, this returns null.
  91. *
  92. * @return array<mixed>|null JSON key | null
  93. */
  94. public static function fromWellKnownFile()
  95. {
  96. $rootEnv = self::isOnWindows() ? 'APPDATA' : 'HOME';
  97. $path = [getenv($rootEnv)];
  98. if (!self::isOnWindows()) {
  99. $path[] = self::NON_WINDOWS_WELL_KNOWN_PATH_BASE;
  100. }
  101. $path[] = self::WELL_KNOWN_PATH;
  102. $path = implode(DIRECTORY_SEPARATOR, $path);
  103. if (!file_exists($path)) {
  104. return null;
  105. }
  106. $jsonKey = file_get_contents($path);
  107. return json_decode((string) $jsonKey, true);
  108. }
  109. /**
  110. * Create a new Credentials instance.
  111. *
  112. * @param string|string[] $scope the scope of the access request, expressed
  113. * either as an Array or as a space-delimited String.
  114. * @param array<mixed> $jsonKey the JSON credentials.
  115. * @param string|string[] $defaultScope The default scope to use if no
  116. * user-defined scopes exist, expressed either as an Array or as a
  117. * space-delimited string.
  118. *
  119. * @return ServiceAccountCredentials|UserRefreshCredentials|ImpersonatedServiceAccountCredentials|ExternalAccountCredentials
  120. */
  121. public static function makeCredentials(
  122. $scope,
  123. array $jsonKey,
  124. $defaultScope = null
  125. ) {
  126. if (!array_key_exists('type', $jsonKey)) {
  127. throw new \InvalidArgumentException('json key is missing the type field');
  128. }
  129. if ($jsonKey['type'] == 'service_account') {
  130. // Do not pass $defaultScope to ServiceAccountCredentials
  131. return new ServiceAccountCredentials($scope, $jsonKey);
  132. }
  133. if ($jsonKey['type'] == 'authorized_user') {
  134. $anyScope = $scope ?: $defaultScope;
  135. return new UserRefreshCredentials($anyScope, $jsonKey);
  136. }
  137. if ($jsonKey['type'] == 'impersonated_service_account') {
  138. $anyScope = $scope ?: $defaultScope;
  139. return new ImpersonatedServiceAccountCredentials($anyScope, $jsonKey);
  140. }
  141. if ($jsonKey['type'] == 'external_account') {
  142. $anyScope = $scope ?: $defaultScope;
  143. return new ExternalAccountCredentials($anyScope, $jsonKey);
  144. }
  145. throw new \InvalidArgumentException('invalid value in the type field');
  146. }
  147. /**
  148. * Create an authorized HTTP Client from an instance of FetchAuthTokenInterface.
  149. *
  150. * @param FetchAuthTokenInterface $fetcher is used to fetch the auth token
  151. * @param array<mixed> $httpClientOptions (optional) Array of request options to apply.
  152. * @param callable $httpHandler (optional) http client to fetch the token.
  153. * @param callable $tokenCallback (optional) function to be called when a new token is fetched.
  154. * @return \GuzzleHttp\Client
  155. */
  156. public static function makeHttpClient(
  157. FetchAuthTokenInterface $fetcher,
  158. array $httpClientOptions = [],
  159. callable $httpHandler = null,
  160. callable $tokenCallback = null
  161. ) {
  162. $middleware = new Middleware\AuthTokenMiddleware(
  163. $fetcher,
  164. $httpHandler,
  165. $tokenCallback
  166. );
  167. $stack = \GuzzleHttp\HandlerStack::create();
  168. $stack->push($middleware);
  169. return new \GuzzleHttp\Client([
  170. 'handler' => $stack,
  171. 'auth' => 'google_auth',
  172. ] + $httpClientOptions);
  173. }
  174. /**
  175. * Create a new instance of InsecureCredentials.
  176. *
  177. * @return InsecureCredentials
  178. */
  179. public static function makeInsecureCredentials()
  180. {
  181. return new InsecureCredentials();
  182. }
  183. /**
  184. * Fetch a quota project from the environment variable
  185. * GOOGLE_CLOUD_QUOTA_PROJECT. Return null if
  186. * GOOGLE_CLOUD_QUOTA_PROJECT is not specified.
  187. *
  188. * @return string|null
  189. */
  190. public static function quotaProjectFromEnv()
  191. {
  192. return getenv(self::QUOTA_PROJECT_ENV_VAR) ?: null;
  193. }
  194. /**
  195. * Gets a callable which returns the default device certification.
  196. *
  197. * @throws UnexpectedValueException
  198. * @return callable|null
  199. */
  200. public static function getDefaultClientCertSource()
  201. {
  202. if (!$clientCertSourceJson = self::loadDefaultClientCertSourceFile()) {
  203. return null;
  204. }
  205. $clientCertSourceCmd = $clientCertSourceJson['cert_provider_command'];
  206. return function () use ($clientCertSourceCmd) {
  207. $cmd = array_map('escapeshellarg', $clientCertSourceCmd);
  208. exec(implode(' ', $cmd), $output, $returnVar);
  209. if (0 === $returnVar) {
  210. return implode(PHP_EOL, $output);
  211. }
  212. throw new RuntimeException(
  213. '"cert_provider_command" failed with a nonzero exit code'
  214. );
  215. };
  216. }
  217. /**
  218. * Determines whether or not the default device certificate should be loaded.
  219. *
  220. * @return bool
  221. */
  222. public static function shouldLoadClientCertSource()
  223. {
  224. return filter_var(getenv(self::MTLS_CERT_ENV_VAR), FILTER_VALIDATE_BOOLEAN);
  225. }
  226. /**
  227. * @return array{cert_provider_command:string[]}|null
  228. */
  229. private static function loadDefaultClientCertSourceFile()
  230. {
  231. $rootEnv = self::isOnWindows() ? 'APPDATA' : 'HOME';
  232. $path = sprintf('%s/%s', getenv($rootEnv), self::MTLS_WELL_KNOWN_PATH);
  233. if (!file_exists($path)) {
  234. return null;
  235. }
  236. $jsonKey = file_get_contents($path);
  237. $clientCertSourceJson = json_decode((string) $jsonKey, true);
  238. if (!$clientCertSourceJson) {
  239. throw new UnexpectedValueException('Invalid client cert source JSON');
  240. }
  241. if (!isset($clientCertSourceJson['cert_provider_command'])) {
  242. throw new UnexpectedValueException(
  243. 'cert source requires "cert_provider_command"'
  244. );
  245. }
  246. if (!is_array($clientCertSourceJson['cert_provider_command'])) {
  247. throw new UnexpectedValueException(
  248. 'cert source expects "cert_provider_command" to be an array'
  249. );
  250. }
  251. return $clientCertSourceJson;
  252. }
  253. /**
  254. * Get the universe domain from the credential. Defaults to "googleapis.com"
  255. * for all credential types which do not support universe domain.
  256. *
  257. * @return string
  258. */
  259. public function getUniverseDomain(): string
  260. {
  261. return self::DEFAULT_UNIVERSE_DOMAIN;
  262. }
  263. }