PluginProbe
Media Cloud Sync / 1.2.3
Media Cloud Sync v1.2.3
1.4.2 1.4.1 1.4.0 1.3.12 1.3.11 1.3.10 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.2.0 1.2.10 1.2.11 1.2.12 1.2.13 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 All 36 releases
media-cloud-sync / includes / sdk / google / google / auth / src / ApplicationDefaultCredentials.php

ApplicationDefaultCredentials.php in Media Cloud Sync 1.2.3, at includes/sdk/google/google/auth/src/ApplicationDefaultCredentials.php

302 lines 13.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /*
4 * Copyright 2015 Google Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 namespace Dudlewebs\WPMCS\Google\Auth;
19
20 use DomainException;
21 use Dudlewebs\WPMCS\Google\Auth\Credentials\AppIdentityCredentials;
22 use Dudlewebs\WPMCS\Google\Auth\Credentials\GCECredentials;
23 use Dudlewebs\WPMCS\Google\Auth\Credentials\ServiceAccountCredentials;
24 use Dudlewebs\WPMCS\Google\Auth\HttpHandler\HttpClientCache;
25 use Dudlewebs\WPMCS\Google\Auth\HttpHandler\HttpHandlerFactory;
26 use Dudlewebs\WPMCS\Google\Auth\Middleware\AuthTokenMiddleware;
27 use Dudlewebs\WPMCS\Google\Auth\Middleware\ProxyAuthTokenMiddleware;
28 use Dudlewebs\WPMCS\Google\Auth\Subscriber\AuthTokenSubscriber;
29 use Dudlewebs\WPMCS\GuzzleHttp\Client;
30 use InvalidArgumentException;
31 use Dudlewebs\WPMCS\Psr\Cache\CacheItemPoolInterface;
32 /**
33 * ApplicationDefaultCredentials obtains the default credentials for
34 * authorizing a request to a Google service.
35 *
36 * Application Default Credentials are described here:
37 * https://developers.google.com/accounts/docs/application-default-credentials
38 *
39 * This class implements the search for the application default credentials as
40 * described in the link.
41 *
42 * It provides three factory methods:
43 * - #get returns the computed credentials object
44 * - #getSubscriber returns an AuthTokenSubscriber built from the credentials object
45 * - #getMiddleware returns an AuthTokenMiddleware built from the credentials object
46 *
47 * This allows it to be used as follows with GuzzleHttp\Client:
48 *
49 * ```
50 * use Google\Auth\ApplicationDefaultCredentials;
51 * use GuzzleHttp\Client;
52 * use GuzzleHttp\HandlerStack;
53 *
54 * $middleware = ApplicationDefaultCredentials::getMiddleware(
55 * 'https://www.googleapis.com/auth/taskqueue'
56 * );
57 * $stack = HandlerStack::create();
58 * $stack->push($middleware);
59 *
60 * $client = new Client([
61 * 'handler' => $stack,
62 * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
63 * 'auth' => 'google_auth' // authorize all requests
64 * ]);
65 *
66 * $res = $client->get('myproject/taskqueues/myqueue');
67 * ```
68 */
69 class ApplicationDefaultCredentials
70 {
71 /**
72 * @deprecated
73 *
74 * Obtains an AuthTokenSubscriber that uses the default FetchAuthTokenInterface
75 * implementation to use in this environment.
76 *
77 * If supplied, $scope is used to in creating the credentials instance if
78 * this does not fallback to the compute engine defaults.
79 *
80 * @param string|string[] $scope the scope of the access request, expressed
81 * either as an Array or as a space-delimited String.
82 * @param callable $httpHandler callback which delivers psr7 request
83 * @param array<mixed> $cacheConfig configuration for the cache when it's present
84 * @param CacheItemPoolInterface $cache A cache implementation, may be
85 * provided if you have one already available for use.
86 * @return AuthTokenSubscriber
87 * @throws DomainException if no implementation can be obtained.
88 */
89 public static function getSubscriber(
90 // @phpstan-ignore-line
91 $scope = null,
92 callable $httpHandler = null,
93 array $cacheConfig = null,
94 CacheItemPoolInterface $cache = null
95 )
96 {
97 $creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache);
98 /** @phpstan-ignore-next-line */
99 return new AuthTokenSubscriber($creds, $httpHandler);
100 }
101 /**
102 * Obtains an AuthTokenMiddleware that uses the default FetchAuthTokenInterface
103 * implementation to use in this environment.
104 *
105 * If supplied, $scope is used to in creating the credentials instance if
106 * this does not fallback to the compute engine defaults.
107 *
108 * @param string|string[] $scope the scope of the access request, expressed
109 * either as an Array or as a space-delimited String.
110 * @param callable $httpHandler callback which delivers psr7 request
111 * @param array<mixed> $cacheConfig configuration for the cache when it's present
112 * @param CacheItemPoolInterface $cache A cache implementation, may be
113 * provided if you have one already available for use.
114 * @param string $quotaProject specifies a project to bill for access
115 * charges associated with the request.
116 * @return AuthTokenMiddleware
117 * @throws DomainException if no implementation can be obtained.
118 */
119 public static function getMiddleware($scope = null, callable $httpHandler = null, array $cacheConfig = null, CacheItemPoolInterface $cache = null, $quotaProject = null)
120 {
121 $creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache, $quotaProject);
122 return new AuthTokenMiddleware($creds, $httpHandler);
123 }
124 /**
125 * Obtains the default FetchAuthTokenInterface implementation to use
126 * in this environment.
127 *
128 * @param string|string[] $scope the scope of the access request, expressed
129 * either as an Array or as a space-delimited String.
130 * @param callable $httpHandler callback which delivers psr7 request
131 * @param array<mixed> $cacheConfig configuration for the cache when it's present
132 * @param CacheItemPoolInterface $cache A cache implementation, may be
133 * provided if you have one already available for use.
134 * @param string $quotaProject specifies a project to bill for access
135 * charges associated with the request.
136 * @param string|string[] $defaultScope The default scope to use if no
137 * user-defined scopes exist, expressed either as an Array or as a
138 * space-delimited string.
139 * @param string $universeDomain Specifies a universe domain to use for the
140 * calling client library
141 *
142 * @return FetchAuthTokenInterface
143 * @throws DomainException if no implementation can be obtained.
144 */
145 public static function getCredentials($scope = null, callable $httpHandler = null, array $cacheConfig = null, CacheItemPoolInterface $cache = null, $quotaProject = null, $defaultScope = null, string $universeDomain = null)
146 {
147 $creds = null;
148 $jsonKey = CredentialsLoader::fromEnv() ?: CredentialsLoader::fromWellKnownFile();
149 $anyScope = $scope ?: $defaultScope;
150 if (!$httpHandler) {
151 if (!$client = HttpClientCache::getHttpClient()) {
152 $client = new Client();
153 HttpClientCache::setHttpClient($client);
154 }
155 $httpHandler = HttpHandlerFactory::build($client);
156 }
157 if (is_null($quotaProject)) {
158 // if a quota project isn't specified, try to get one from the env var
159 $quotaProject = CredentialsLoader::quotaProjectFromEnv();
160 }
161 if (!is_null($jsonKey)) {
162 if ($quotaProject) {
163 $jsonKey['quota_project_id'] = $quotaProject;
164 }
165 if ($universeDomain) {
166 $jsonKey['universe_domain'] = $universeDomain;
167 }
168 $creds = CredentialsLoader::makeCredentials($scope, $jsonKey, $defaultScope);
169 } elseif (AppIdentityCredentials::onAppEngine() && !GCECredentials::onAppEngineFlexible()) {
170 $creds = new AppIdentityCredentials($anyScope);
171 } elseif (self::onGce($httpHandler, $cacheConfig, $cache)) {
172 $creds = new GCECredentials(null, $anyScope, null, $quotaProject, null, $universeDomain);
173 $creds->setIsOnGce(\true);
174 // save the credentials a trip to the metadata server
175 }
176 if (is_null($creds)) {
177 throw new DomainException(self::notFound());
178 }
179 if (!is_null($cache)) {
180 $creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache);
181 }
182 return $creds;
183 }
184 /**
185 * Obtains an AuthTokenMiddleware which will fetch an ID token to use in the
186 * Authorization header. The middleware is configured with the default
187 * FetchAuthTokenInterface implementation to use in this environment.
188 *
189 * If supplied, $targetAudience is used to set the "aud" on the resulting
190 * ID token.
191 *
192 * @param string $targetAudience The audience for the ID token.
193 * @param callable $httpHandler callback which delivers psr7 request
194 * @param array<mixed> $cacheConfig configuration for the cache when it's present
195 * @param CacheItemPoolInterface $cache A cache implementation, may be
196 * provided if you have one already available for use.
197 * @return AuthTokenMiddleware
198 * @throws DomainException if no implementation can be obtained.
199 */
200 public static function getIdTokenMiddleware($targetAudience, callable $httpHandler = null, array $cacheConfig = null, CacheItemPoolInterface $cache = null)
201 {
202 $creds = self::getIdTokenCredentials($targetAudience, $httpHandler, $cacheConfig, $cache);
203 return new AuthTokenMiddleware($creds, $httpHandler);
204 }
205 /**
206 * Obtains an ProxyAuthTokenMiddleware which will fetch an ID token to use in the
207 * Authorization header. The middleware is configured with the default
208 * FetchAuthTokenInterface implementation to use in this environment.
209 *
210 * If supplied, $targetAudience is used to set the "aud" on the resulting
211 * ID token.
212 *
213 * @param string $targetAudience The audience for the ID token.
214 * @param callable $httpHandler callback which delivers psr7 request
215 * @param array<mixed> $cacheConfig configuration for the cache when it's present
216 * @param CacheItemPoolInterface $cache A cache implementation, may be
217 * provided if you have one already available for use.
218 * @return ProxyAuthTokenMiddleware
219 * @throws DomainException if no implementation can be obtained.
220 */
221 public static function getProxyIdTokenMiddleware($targetAudience, callable $httpHandler = null, array $cacheConfig = null, CacheItemPoolInterface $cache = null)
222 {
223 $creds = self::getIdTokenCredentials($targetAudience, $httpHandler, $cacheConfig, $cache);
224 return new ProxyAuthTokenMiddleware($creds, $httpHandler);
225 }
226 /**
227 * Obtains the default FetchAuthTokenInterface implementation to use
228 * in this environment, configured with a $targetAudience for fetching an ID
229 * token.
230 *
231 * @param string $targetAudience The audience for the ID token.
232 * @param callable $httpHandler callback which delivers psr7 request
233 * @param array<mixed> $cacheConfig configuration for the cache when it's present
234 * @param CacheItemPoolInterface $cache A cache implementation, may be
235 * provided if you have one already available for use.
236 * @return FetchAuthTokenInterface
237 * @throws DomainException if no implementation can be obtained.
238 * @throws InvalidArgumentException if JSON "type" key is invalid
239 */
240 public static function getIdTokenCredentials($targetAudience, callable $httpHandler = null, array $cacheConfig = null, CacheItemPoolInterface $cache = null)
241 {
242 $creds = null;
243 $jsonKey = CredentialsLoader::fromEnv() ?: CredentialsLoader::fromWellKnownFile();
244 if (!$httpHandler) {
245 if (!$client = HttpClientCache::getHttpClient()) {
246 $client = new Client();
247 HttpClientCache::setHttpClient($client);
248 }
249 $httpHandler = HttpHandlerFactory::build($client);
250 }
251 if (!is_null($jsonKey)) {
252 if (!array_key_exists('type', $jsonKey)) {
253 throw new \InvalidArgumentException('json key is missing the type field');
254 }
255 if ($jsonKey['type'] == 'authorized_user') {
256 throw new InvalidArgumentException('ID tokens are not supported for end user credentials');
257 }
258 if ($jsonKey['type'] != 'service_account') {
259 throw new InvalidArgumentException('invalid value in the type field');
260 }
261 $creds = new ServiceAccountCredentials(null, $jsonKey, null, $targetAudience);
262 } elseif (self::onGce($httpHandler, $cacheConfig, $cache)) {
263 $creds = new GCECredentials(null, null, $targetAudience);
264 $creds->setIsOnGce(\true);
265 // save the credentials a trip to the metadata server
266 }
267 if (is_null($creds)) {
268 throw new DomainException(self::notFound());
269 }
270 if (!is_null($cache)) {
271 $creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache);
272 }
273 return $creds;
274 }
275 /**
276 * @return string
277 */
278 private static function notFound()
279 {
280 $msg = 'Your default credentials were not found. To set up ';
281 $msg .= 'Application Default Credentials, see ';
282 $msg .= 'https://cloud.google.com/docs/authentication/external/set-up-adc';
283 return $msg;
284 }
285 /**
286 * @param callable $httpHandler
287 * @param array<mixed> $cacheConfig
288 * @param CacheItemPoolInterface $cache
289 * @return bool
290 */
291 private static function onGce(callable $httpHandler = null, array $cacheConfig = null, CacheItemPoolInterface $cache = null)
292 {
293 $gceCacheConfig = [];
294 foreach (['lifetime', 'prefix'] as $key) {
295 if (isset($cacheConfig['gce_' . $key])) {
296 $gceCacheConfig[$key] = $cacheConfig['gce_' . $key];
297 }
298 }
299 return (new GCECache($gceCacheConfig, $cache))->onGce($httpHandler);
300 }
301 }
302