-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathImpersonatedServiceAccountCredentialsTest.php
More file actions
488 lines (432 loc) · 21.9 KB
/
ImpersonatedServiceAccountCredentialsTest.php
File metadata and controls
488 lines (432 loc) · 21.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
<?php
/*
* Copyright 2022 Google Inc.
*
* 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\Auth\Tests\Credentials;
use Google\Auth\Credentials\ExternalAccountCredentials;
use Google\Auth\Credentials\ImpersonatedServiceAccountCredentials;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Credentials\UserRefreshCredentials;
use Google\Auth\FetchAuthTokenInterface;
use Google\Auth\GetUniverseDomainInterface;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Auth\OAuth2;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use InvalidArgumentException;
use LogicException;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Psr\Http\Message\RequestInterface;
use ReflectionClass;
class ImpersonatedServiceAccountCredentialsTest extends TestCase
{
use ProphecyTrait;
private const SCOPE = ['scope/1', 'scope/2'];
private const TARGET_AUDIENCE = 'test-target-audience';
private const IMPERSONATION_URL = 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/test@test-project.iam.gserviceaccount.com:generateAccessToken';
private const UNIVERSE_DOMAIN = 'example.com';
// User Refresh to Service Account Impersonation JSON Credentials
private const USER_TO_SERVICE_ACCOUNT_JSON = [
'type' => 'impersonated_service_account',
'service_account_impersonation_url' => self::IMPERSONATION_URL,
'source_credentials' => [
'client_id' => 'client123',
'client_secret' => 'clientSecret123',
'refresh_token' => 'refreshToken123',
'type' => 'authorized_user',
]
];
// Service Account to Service Account Impersonation JSON Credentials
private const SERVICE_ACCOUNT_TO_SERVICE_ACCOUNT_JSON = [
'type' => 'impersonated_service_account',
'service_account_impersonation_url' => self::IMPERSONATION_URL,
'source_credentials' => [
'client_email' => 'clientemail@clientemail.com',
'private_key' => "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgGhw1WMos5gp2YjV7+fNwXN1tI4/DFXKzwY6TDWsPxkbyfjHgunX\n/sijlnJt3Qs1gBxiwEEjzFFlp39O3/gEbIoYWHR/4sZdqNRFzbhJcTpnUvRlZDBL\nE5h8f5uu4aL4D32WyiELF/vpr533lZCBwWsnN3zIYJxThgRF9i/R7F8tAgMBAAEC\ngYAgUyv4cNSFOA64J18FY82IKtojXKg4tXi1+L01r4YoA03TzgxazBtzhg4+hHpx\nybFJF9dhUe8fElNxN7xiSxw8i5MnfPl+piwbfoENhgrzU0/N14AV/4Pq+WAJQe2M\nxPcI1DPYMEwGjX2PmxqnkC47MyR9agX21YZVc9rpRCgPgQJBALodH492I0ydvEUs\ngT+3DkNqoWx3O3vut7a0+6k+RkM1Yu+hGI8RQDCGwcGhQlOpqJkYGsVegZbxT+AF\nvvIFrIUCQQCPqJbRalHK/QnVj4uovj6JvjTkqFSugfztB4Zm/BPT2eEpjLt+851d\nIJ4brK/HVkQT2zk9eb0YzIBfeQi9WpyJAkB9+BRSf72or+KsV1EsFPScgOG9jn4+\nhfbmvVzQ0ouwFcRfOQRsYVq2/Z7LNiC0i9LHvF7yU+MWjUJo+LqjCWAZAkBHearo\nMIzXgQRGlC/5WgZFhDRO3A2d8aDE0eymCp9W1V24zYNwC4dtEVB5Fncyp5Ihiv40\nvwA9eWoZll+pzo55AkBMMdk95skWeaRv8T0G1duv5VQ7q4us2S2TKbEbC8j83BTP\nNefc3KEugylyAjx24ydxARZXznPi1SFeYVx1KCMZ\n-----END RSA PRIVATE KEY-----\n",
'type' => 'service_account',
]
];
// Service Account to Service Account Impersonation JSON Credentials
private const EXTERNAL_ACCOUNT_TO_SERVICE_ACCOUNT_JSON = [
'type' => 'impersonated_service_account',
'service_account_impersonation_url' => self::IMPERSONATION_URL,
'source_credentials' => [
'type' => 'external_account',
'audience' => 'some_audience',
'subject_token_type' => 'access_token',
'token_url' => 'https://sts.googleapis.com/v1/token',
'credential_source' => [
'url' => 'https://some.url/token'
]
]
];
public function testGetServiceAccountNameEmail()
{
$json = self::USER_TO_SERVICE_ACCOUNT_JSON;
$creds = new ImpersonatedServiceAccountCredentials(self::SCOPE, $json);
$this->assertEquals('test@test-project.iam.gserviceaccount.com', $creds->getClientName());
}
public function testGetServiceAccountNameID()
{
$json = self::USER_TO_SERVICE_ACCOUNT_JSON;
$json['service_account_impersonation_url'] = 'https://some/arbitrary/url/serviceAccounts/1234567890987654321:generateAccessToken';
$creds = new ImpersonatedServiceAccountCredentials(self::SCOPE, $json);
$this->assertEquals('1234567890987654321', $creds->getClientName());
}
public function testGetCacheKey()
{
$creds = new ImpersonatedServiceAccountCredentials(self::SCOPE, [
'service_account_impersonation_url' => 'foo',
'source_credentials' => [
'type' => 'service_account',
'client_email' => '123',
'private_key' => 'abc'
]
]);
$this->assertEquals('foo123.scope1scope2', $creds->getCacheKey());
}
public function testMissingImpersonationUriThrowsException()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('json key is missing the service_account_impersonation_url field');
new ImpersonatedServiceAccountCredentials(self::SCOPE, []);
}
public function testMissingSourceCredentialTypeThrowsException()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('json key source credentials are missing the type field');
new ImpersonatedServiceAccountCredentials(self::SCOPE, [
'service_account_impersonation_url' => 'https//google.com',
'source_credentials' => []
]);
}
/**
* @dataProvider provideSourceCredentialsClass
*/
public function testSourceCredentialsClass(array $json, string $credClass)
{
$creds = new ImpersonatedServiceAccountCredentials(['scope/1', 'scope/2'], $json);
$sourceCredentialsProperty = (new ReflectionClass($creds))->getProperty('sourceCredentials');
$sourceCredentialsProperty->setAccessible(true);
$this->assertInstanceOf($credClass, $sourceCredentialsProperty->getValue($creds));
}
public function provideSourceCredentialsClass()
{
return [
[self::USER_TO_SERVICE_ACCOUNT_JSON, UserRefreshCredentials::class],
[self::SERVICE_ACCOUNT_TO_SERVICE_ACCOUNT_JSON, ServiceAccountCredentials::class],
[self::EXTERNAL_ACCOUNT_TO_SERVICE_ACCOUNT_JSON, ExternalAccountCredentials::class],
];
}
/**
* Test access token impersonation for Service Account and User Refresh Credentials.
*
* @dataProvider provideAuthTokenJson
*/
public function testGetAccessTokenWithServiceAccountAndUserRefreshCredentials(array $json, string $grantType)
{
$requestCount = 0;
// getting an id token will take two requests
$httpHandler = function (RequestInterface $request) use (&$requestCount, $json, $grantType) {
if (++$requestCount == 1) {
// the call to swap the refresh token for an access token
$this->assertEquals(UserRefreshCredentials::TOKEN_CREDENTIAL_URI, (string) $request->getUri());
parse_str((string) $request->getBody(), $result);
$this->assertEquals($grantType, $result['grant_type']);
} elseif ($requestCount == 2) {
// the call to swap the access token for an id token
$this->assertEquals($json['service_account_impersonation_url'], (string) $request->getUri());
$this->assertEquals(self::SCOPE, json_decode($request->getBody(), true)['scope'] ?? '');
$this->assertEquals('Bearer test-access-token', $request->getHeader('authorization')[0] ?? null);
}
return new Response(
200,
['Content-Type' => 'application/json'],
json_encode(match ($requestCount) {
1 => ['access_token' => 'test-access-token'],
2 => ['accessToken' => 'test-impersonated-access-token', 'expireTime' => 123]
})
);
};
$creds = new ImpersonatedServiceAccountCredentials(self::SCOPE, $json);
$token = $creds->fetchAuthToken($httpHandler);
$this->assertEquals('test-impersonated-access-token', $token['access_token']);
$this->assertEquals(2, $requestCount);
}
/**
* Test access token impersonation for Exernal Account Credentials.
*/
public function testGetAccessTokenWithExternalAccountCredentials()
{
$json = self::EXTERNAL_ACCOUNT_TO_SERVICE_ACCOUNT_JSON;
$httpHandler = function (RequestInterface $request) use (&$requestCount, $json) {
if (++$requestCount == 1) {
// the call to swap the refresh token for an access token
$this->assertEquals(
$json['source_credentials']['credential_source']['url'],
(string) $request->getUri()
);
} elseif ($requestCount == 2) {
$this->assertEquals($json['source_credentials']['token_url'], (string) $request->getUri());
} elseif ($requestCount == 3) {
// the call to swap the access token for an id token
$this->assertEquals($json['service_account_impersonation_url'], (string) $request->getUri());
$this->assertEquals(self::SCOPE, json_decode($request->getBody(), true)['scope'] ?? '');
$this->assertEquals('Bearer test-access-token', $request->getHeader('authorization')[0] ?? null);
}
return new Response(
200,
['Content-Type' => 'application/json'],
json_encode(match ($requestCount) {
1 => ['access_token' => 'test-access-token'],
2 => ['access_token' => 'test-access-token'],
3 => ['accessToken' => 'test-impersonated-access-token', 'expireTime' => 123]
})
);
};
$creds = new ImpersonatedServiceAccountCredentials(self::SCOPE, $json);
$token = $creds->fetchAuthToken($httpHandler);
$this->assertEquals('test-impersonated-access-token', $token['access_token']);
$this->assertEquals(3, $requestCount);
}
/**
* Test ID token impersonation for Service Account and User Refresh Credentials.
*
* @dataProvider provideAuthTokenJson
*/
public function testGetIdTokenWithServiceAccountAndUserRefreshCredentials(array $json, string $grantType)
{
$requestCount = 0;
// getting an id token will take two requests
$httpHandler = function (RequestInterface $request) use (&$requestCount, $json, $grantType) {
if (++$requestCount == 1) {
// the call to swap the refresh token for an access token
$this->assertEquals(UserRefreshCredentials::TOKEN_CREDENTIAL_URI, (string) $request->getUri());
parse_str((string) $request->getBody(), $result);
$this->assertEquals($grantType, $result['grant_type']);
} elseif ($requestCount == 2) {
// the call to swap the access token for an id token
$this->assertEquals(
str_replace(':generateAccessToken', ':generateIdToken', $json['service_account_impersonation_url']),
(string) $request->getUri()
);
$this->assertEquals(self::TARGET_AUDIENCE, json_decode($request->getBody(), true)['audience'] ?? '');
$this->assertEquals('Bearer test-access-token', $request->getHeader('authorization')[0] ?? null);
}
return new Response(
200,
['Content-Type' => 'application/json'],
json_encode(match ($requestCount) {
1 => ['access_token' => 'test-access-token'],
2 => ['token' => 'test-impersonated-id-token']
})
);
};
$creds = new ImpersonatedServiceAccountCredentials(null, $json, self::TARGET_AUDIENCE);
$token = $creds->fetchAuthToken($httpHandler);
$this->assertEquals('test-impersonated-id-token', $token['id_token']);
$this->assertEquals(2, $requestCount);
}
public function provideAuthTokenJson()
{
return [
[self::USER_TO_SERVICE_ACCOUNT_JSON, 'refresh_token'],
[self::SERVICE_ACCOUNT_TO_SERVICE_ACCOUNT_JSON, OAuth2::JWT_URN],
];
}
/**
* Test ID token impersonation for Service Account Credentials with a universe domain.
*/
public function testGetIdTokenWithServiceAccountCredentialsAndUniverseDomain()
{
$json = self::SERVICE_ACCOUNT_TO_SERVICE_ACCOUNT_JSON;
$json['source_credentials']['universe_domain'] = self::UNIVERSE_DOMAIN;
// the expected URL should have the universe domain
$expectedUrl = str_replace(
['googleapis.com', ':generateAccessToken'],
[self::UNIVERSE_DOMAIN, ':generateIdToken'],
$json['service_account_impersonation_url'],
);
// getting an id token will take two requests
$httpHandler = function (RequestInterface $request) use ($expectedUrl) {
$this->assertEquals($expectedUrl, (string) $request->getUri());
$this->assertEquals(self::TARGET_AUDIENCE, json_decode($request->getBody(), true)['audience'] ?? '');
$this->assertStringStartsWith('Bearer ', $request->getHeader('authorization')[0] ?? null);
return new Response(
200,
['Content-Type' => 'application/json'],
json_encode(['token' => 'test-impersonated-id-token'])
);
};
$creds = new ImpersonatedServiceAccountCredentials(null, $json, self::TARGET_AUDIENCE);
$token = $creds->fetchAuthToken($httpHandler);
$this->assertEquals('test-impersonated-id-token', $token['id_token']);
}
/**
* Test invalid email throws exception
*/
public function testInvalidServiceAccountImpersonationUrlThrowsException()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Invalid service account impersonation URL - unable to parse service account email'
);
$json = self::SERVICE_ACCOUNT_TO_SERVICE_ACCOUNT_JSON;
$json['service_account_impersonation_url'] = 'https://invalid/url';
// mock access token call for source credentials
$httpHandler = fn () => new Response(
200,
['Content-Type' => 'application/json'],
json_encode(['access_token' => 'test-access-token'])
);
$creds = new ImpersonatedServiceAccountCredentials(null, $json, self::TARGET_AUDIENCE);
$creds->fetchAuthToken($httpHandler);
}
/**
* Test ID token impersonation for Exernal Account Credentials.
* @dataProvider provideUniverseDomain
*/
public function testGetIdTokenWithExternalAccountCredentials(?string $universeDomain = null)
{
$json = self::EXTERNAL_ACCOUNT_TO_SERVICE_ACCOUNT_JSON;
if ($universeDomain) {
$json['source_credentials']['universe_domain'] = $universeDomain;
}
$httpHandler = function (RequestInterface $request) use (&$requestCount, $json, $universeDomain) {
if (++$requestCount == 1) {
// the call to swap the refresh token for an access token
$this->assertEquals(
$json['source_credentials']['credential_source']['url'],
(string) $request->getUri()
);
} elseif ($requestCount == 2) {
$this->assertEquals($json['source_credentials']['token_url'], (string) $request->getUri());
} elseif ($requestCount == 3) {
// the call to swap the access token for an id token
$url = str_replace(':generateAccessToken', ':generateIdToken', $json['service_account_impersonation_url']);
if ($universeDomain) {
$url = str_replace('googleapis.com', $universeDomain, $url);
}
$this->assertEquals($url, (string) $request->getUri());
$this->assertEquals(self::TARGET_AUDIENCE, json_decode($request->getBody(), true)['audience'] ?? '');
$this->assertEquals('Bearer test-access-token', $request->getHeader('authorization')[0] ?? null);
}
return new Response(
200,
['Content-Type' => 'application/json'],
json_encode(match ($requestCount) {
1 => ['access_token' => 'test-access-token'],
2 => ['access_token' => 'test-access-token'],
3 => ['token' => 'test-impersonated-id-token']
})
);
};
$creds = new ImpersonatedServiceAccountCredentials(null, $json, self::TARGET_AUDIENCE);
$token = $creds->fetchAuthToken($httpHandler);
$this->assertEquals('test-impersonated-id-token', $token['id_token']);
$this->assertEquals(3, $requestCount);
}
/**
* Test ID token impersonation for an arbitrary credential fetcher.
* @dataProvider provideUniverseDomain
*/
public function testGetIdTokenWithArbitraryCredentials(?string $universeDomain = null)
{
$url = $universeDomain
? 'https://iamcredentials.' . self::UNIVERSE_DOMAIN . '/v1/projects/-/serviceAccounts/123:generateIdToken'
: 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/123:generateIdToken';
$httpHandler = function (RequestInterface $request) use ($url) {
// The URL is coerced to match the googleapis URL pattern
$this->assertEquals($url, (string) $request->getUri());
$this->assertEquals('Bearer test-access-token', $request->getHeader('authorization')[0] ?? null);
return new Response(200, [], json_encode(['token' => 'test-impersonated-id-token']));
};
$credentials = $this->prophesize(FetchAuthTokenInterface::class)
->willImplement(GetUniverseDomainInterface::class);
$credentials->fetchAuthToken($httpHandler, Argument::type('array'))
->shouldBeCalledOnce()
->willReturn(['access_token' => 'test-access-token']);
$credentials->getUniverseDomain()
->shouldBeCalledOnce()
->willReturn($universeDomain ?: GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN);
$json = [
'type' => 'impersonated_service_account',
'service_account_impersonation_url' => 'https://some/url/serviceAccounts/123:generateAccessToken',
'source_credentials' => $credentials->reveal(),
];
$creds = new ImpersonatedServiceAccountCredentials(null, $json, self::TARGET_AUDIENCE);
$token = $creds->fetchAuthToken($httpHandler);
$this->assertEquals('test-impersonated-id-token', $token['id_token']);
}
public function provideUniverseDomain()
{
return [
[null],
[self::UNIVERSE_DOMAIN],
];
}
/**
* Test access token impersonation for an arbitrary credential fetcher.
*/
public function testGetAccessTokenWithArbitraryCredentials()
{
$httpHandler = function (RequestInterface $request) {
$this->assertEquals('https://some/url', (string) $request->getUri());
$this->assertEquals('Bearer test-access-token', $request->getHeader('authorization')[0] ?? null);
return new Response(
200,
[],
json_encode(['accessToken' => 'test-impersonated-access-token', 'expireTime' => 123])
);
};
$credentials = $this->prophesize(FetchAuthTokenInterface::class);
$credentials->fetchAuthToken($httpHandler, Argument::type('array'))
->shouldBeCalledOnce()
->willReturn(['access_token' => 'test-access-token']);
$json = [
'type' => 'impersonated_service_account',
'service_account_impersonation_url' => 'https://some/url',
'source_credentials' => $credentials->reveal(),
];
$creds = new ImpersonatedServiceAccountCredentials(self::SCOPE, $json);
$token = $creds->fetchAuthToken($httpHandler);
$this->assertEquals('test-impersonated-access-token', $token['access_token']);
}
public function testIdTokenWithAuthTokenMiddleware()
{
$targetAudience = 'test-target-audience';
$credentials = new ImpersonatedServiceAccountCredentials(null, self::USER_TO_SERVICE_ACCOUNT_JSON, $targetAudience);
// this handler is for the middleware constructor, which will pass it to the ISAC to fetch tokens
$httpHandler = getHandler([
new Response(200, ['Content-Type' => 'application/json'], '{"access_token":"this.is.an.access.token"}'),
new Response(200, ['Content-Type' => 'application/json'], '{"token":"this.is.an.id.token"}'),
]);
$middleware = new AuthTokenMiddleware($credentials, $httpHandler);
// this handler is the actual handler that makes the authenticated request
$requestCount = 0;
$httpHandler = function (RequestInterface $request) use (&$requestCount) {
$requestCount++;
$this->assertTrue($request->hasHeader('authorization'));
$this->assertEquals('Bearer this.is.an.id.token', $request->getHeader('authorization')[0] ?? null);
};
$middleware($httpHandler)(
new Request('GET', 'https://www.google.com'),
['auth' => 'google_auth']
);
$this->assertEquals(1, $requestCount);
}
}