PluginProbe
Gmail SMTP / trunk
Gmail SMTP vtrunk
1.2.3.21 1.2.3.20 trunk 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.9 1.2.0 1.2.3.14 1.2.3.15 1.2.3.16 1.2.3.18 1.2.3.5
gmail-smtp / google-api-php-client / vendor / google / auth / src / Credentials / AppIdentityCredentials.php

AppIdentityCredentials.php in Gmail SMTP trunk, at google-api-php-client/vendor/google/auth/src/Credentials/AppIdentityCredentials.php

238 lines 6.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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\Credentials;
19
20 /*
21 * The AppIdentityService class is automatically defined on App Engine,
22 * so including this dependency is not necessary, and will result in a
23 * PHP fatal error in the App Engine environment.
24 */
25 use google\appengine\api\app_identity\AppIdentityService;
26 use Google\Auth\CredentialsLoader;
27 use Google\Auth\ProjectIdProviderInterface;
28 use Google\Auth\SignBlobInterface;
29
30 /**
31 * AppIdentityCredentials supports authorization on Google App Engine.
32 *
33 * It can be used to authorize requests using the AuthTokenMiddleware or
34 * AuthTokenSubscriber, but will only succeed if being run on App Engine:
35 *
36 * Example:
37 * ```
38 * use Google\Auth\Credentials\AppIdentityCredentials;
39 * use Google\Auth\Middleware\AuthTokenMiddleware;
40 * use GuzzleHttp\Client;
41 * use GuzzleHttp\HandlerStack;
42 *
43 * $gae = new AppIdentityCredentials('https://www.googleapis.com/auth/books');
44 * $middleware = new AuthTokenMiddleware($gae);
45 * $stack = HandlerStack::create();
46 * $stack->push($middleware);
47 *
48 * $client = new Client([
49 * 'handler' => $stack,
50 * 'base_uri' => 'https://www.googleapis.com/books/v1',
51 * 'auth' => 'google_auth'
52 * ]);
53 *
54 * $res = $client->get('volumes?q=Henry+David+Thoreau&country=US');
55 * ```
56 * @deprecated
57 */
58 class AppIdentityCredentials extends CredentialsLoader implements
59 SignBlobInterface,
60 ProjectIdProviderInterface
61 {
62 /**
63 * Result of fetchAuthToken.
64 *
65 * @var array<mixed>
66 */
67 protected $lastReceivedToken;
68
69 /**
70 * Array of OAuth2 scopes to be requested.
71 *
72 * @var string[]
73 */
74 private $scope;
75
76 /**
77 * @var string
78 */
79 private $clientName;
80
81 /**
82 * @param string|string[] $scope One or more scopes.
83 */
84 public function __construct($scope = [])
85 {
86 $this->scope = is_array($scope) ? $scope : explode(' ', (string) $scope);
87 }
88
89 /**
90 * Determines if this an App Engine instance, by accessing the
91 * SERVER_SOFTWARE environment variable (prod) or the APPENGINE_RUNTIME
92 * environment variable (dev).
93 *
94 * @return bool true if this an App Engine Instance, false otherwise
95 */
96 public static function onAppEngine()
97 {
98 $appEngineProduction = isset($_SERVER['SERVER_SOFTWARE']) &&
99 0 === strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine');
100 if ($appEngineProduction) {
101 return true;
102 }
103 $appEngineDevAppServer = isset($_SERVER['APPENGINE_RUNTIME']) &&
104 $_SERVER['APPENGINE_RUNTIME'] == 'php';
105 if ($appEngineDevAppServer) {
106 return true;
107 }
108 return false;
109 }
110
111 /**
112 * Implements FetchAuthTokenInterface#fetchAuthToken.
113 *
114 * Fetches the auth tokens using the AppIdentityService if available.
115 * As the AppIdentityService uses protobufs to fetch the access token,
116 * the GuzzleHttp\ClientInterface instance passed in will not be used.
117 *
118 * @param callable|null $httpHandler callback which delivers psr7 request
119 * @return array<mixed> {
120 * A set of auth related metadata, containing the following
121 *
122 * @type string $access_token
123 * @type string $expiration_time
124 * }
125 */
126 public function fetchAuthToken(?callable $httpHandler = null)
127 {
128 try {
129 $this->checkAppEngineContext();
130 } catch (\Exception $e) {
131 return [];
132 }
133
134 /** @phpstan-ignore-next-line */
135 $token = AppIdentityService::getAccessToken($this->scope);
136 $this->lastReceivedToken = $token;
137
138 return $token;
139 }
140
141 /**
142 * Sign a string using AppIdentityService.
143 *
144 * @param string $stringToSign The string to sign.
145 * @param bool $forceOpenSsl [optional] Does not apply to this credentials
146 * type.
147 * @return string The signature, base64-encoded.
148 * @throws \Exception If AppEngine SDK or mock is not available.
149 */
150 public function signBlob($stringToSign, $forceOpenSsl = false)
151 {
152 $this->checkAppEngineContext();
153
154 /** @phpstan-ignore-next-line */
155 return base64_encode(AppIdentityService::signForApp($stringToSign)['signature']);
156 }
157
158 /**
159 * Get the project ID from AppIdentityService.
160 *
161 * Returns null if AppIdentityService is unavailable.
162 *
163 * @param callable|null $httpHandler Not used by this type.
164 * @return string|null
165 */
166 public function getProjectId(?callable $httpHandler = null)
167 {
168 try {
169 $this->checkAppEngineContext();
170 } catch (\Exception $e) {
171 return null;
172 }
173
174 /** @phpstan-ignore-next-line */
175 return AppIdentityService::getApplicationId();
176 }
177
178 /**
179 * Get the client name from AppIdentityService.
180 *
181 * Subsequent calls to this method will return a cached value.
182 *
183 * @param callable|null $httpHandler Not used in this implementation.
184 * @return string
185 * @throws \Exception If AppEngine SDK or mock is not available.
186 */
187 public function getClientName(?callable $httpHandler = null)
188 {
189 $this->checkAppEngineContext();
190
191 if (!$this->clientName) {
192 /** @phpstan-ignore-next-line */
193 $this->clientName = AppIdentityService::getServiceAccountName();
194 }
195
196 return $this->clientName;
197 }
198
199 /**
200 * @return array{access_token:string,expires_at:int}|null
201 */
202 public function getLastReceivedToken()
203 {
204 if ($this->lastReceivedToken) {
205 return [
206 'access_token' => $this->lastReceivedToken['access_token'],
207 'expires_at' => $this->lastReceivedToken['expiration_time'],
208 ];
209 }
210
211 return null;
212 }
213
214 /**
215 * Caching is handled by the underlying AppIdentityService, return empty string
216 * to prevent caching.
217 *
218 * @return string
219 */
220 public function getCacheKey()
221 {
222 return '';
223 }
224
225 /**
226 * @return void
227 */
228 private function checkAppEngineContext()
229 {
230 if (!self::onAppEngine() || !class_exists('google\appengine\api\app_identity\AppIdentityService')) {
231 throw new \Exception(
232 'This class must be run in App Engine, or you must include the AppIdentityService '
233 . 'mock class defined in tests/mocks/AppIdentityService.php'
234 );
235 }
236 }
237 }
238