No Description

ServiceAccountCredentialsTest.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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\Tests;
  18. use Google\Auth\ApplicationDefaultCredentials;
  19. use Google\Auth\Credentials\ServiceAccountCredentials;
  20. use Google\Auth\Credentials\ServiceAccountJwtAccessCredentials;
  21. use Google\Auth\CredentialsLoader;
  22. use Google\Auth\OAuth2;
  23. use GuzzleHttp\Psr7;
  24. use PHPUnit\Framework\TestCase;
  25. // Creates a standard JSON auth object for testing.
  26. function createTestJson()
  27. {
  28. return [
  29. 'private_key_id' => 'key123',
  30. 'private_key' => 'privatekey',
  31. 'client_email' => 'test@example.com',
  32. 'client_id' => 'client123',
  33. 'type' => 'service_account',
  34. ];
  35. }
  36. class SACGetCacheKeyTest extends TestCase
  37. {
  38. public function testShouldBeTheSameAsOAuth2WithTheSameScope()
  39. {
  40. $testJson = createTestJson();
  41. $scope = ['scope/1', 'scope/2'];
  42. $sa = new ServiceAccountCredentials(
  43. $scope,
  44. $testJson);
  45. $o = new OAuth2(['scope' => $scope]);
  46. $this->assertSame(
  47. $testJson['client_email'] . ':' . $o->getCacheKey(),
  48. $sa->getCacheKey()
  49. );
  50. }
  51. public function testShouldBeTheSameAsOAuth2WithTheSameScopeWithSub()
  52. {
  53. $testJson = createTestJson();
  54. $scope = ['scope/1', 'scope/2'];
  55. $sub = 'sub123';
  56. $sa = new ServiceAccountCredentials(
  57. $scope,
  58. $testJson,
  59. $sub);
  60. $o = new OAuth2(['scope' => $scope]);
  61. $this->assertSame(
  62. $testJson['client_email'] . ':' . $o->getCacheKey() . ':' . $sub,
  63. $sa->getCacheKey()
  64. );
  65. }
  66. public function testShouldBeTheSameAsOAuth2WithTheSameScopeWithSubAddedLater()
  67. {
  68. $testJson = createTestJson();
  69. $scope = ['scope/1', 'scope/2'];
  70. $sub = 'sub123';
  71. $sa = new ServiceAccountCredentials(
  72. $scope,
  73. $testJson,
  74. null);
  75. $sa->setSub($sub);
  76. $o = new OAuth2(['scope' => $scope]);
  77. $this->assertSame(
  78. $testJson['client_email'] . ':' . $o->getCacheKey() . ':' . $sub,
  79. $sa->getCacheKey()
  80. );
  81. }
  82. }
  83. class SACConstructorTest extends TestCase
  84. {
  85. /**
  86. * @expectedException InvalidArgumentException
  87. */
  88. public function testShouldFailIfScopeIsNotAValidType()
  89. {
  90. $testJson = createTestJson();
  91. $notAnArrayOrString = new \stdClass();
  92. $sa = new ServiceAccountCredentials(
  93. $notAnArrayOrString,
  94. $testJson
  95. );
  96. }
  97. /**
  98. * @expectedException InvalidArgumentException
  99. */
  100. public function testShouldFailIfJsonDoesNotHaveClientEmail()
  101. {
  102. $testJson = createTestJson();
  103. unset($testJson['client_email']);
  104. $scope = ['scope/1', 'scope/2'];
  105. $sa = new ServiceAccountCredentials(
  106. $scope,
  107. $testJson
  108. );
  109. }
  110. /**
  111. * @expectedException InvalidArgumentException
  112. */
  113. public function testShouldFailIfJsonDoesNotHavePrivateKey()
  114. {
  115. $testJson = createTestJson();
  116. unset($testJson['private_key']);
  117. $scope = ['scope/1', 'scope/2'];
  118. $sa = new ServiceAccountCredentials(
  119. $scope,
  120. $testJson
  121. );
  122. }
  123. /**
  124. * @expectedException InvalidArgumentException
  125. */
  126. public function testFailsToInitalizeFromANonExistentFile()
  127. {
  128. $keyFile = __DIR__ . '/../fixtures' . '/does-not-exist-private.json';
  129. new ServiceAccountCredentials('scope/1', $keyFile);
  130. }
  131. public function testInitalizeFromAFile()
  132. {
  133. $keyFile = __DIR__ . '/../fixtures' . '/private.json';
  134. $this->assertNotNull(
  135. new ServiceAccountCredentials('scope/1', $keyFile)
  136. );
  137. }
  138. }
  139. class SACFromEnvTest extends TestCase
  140. {
  141. protected function tearDown()
  142. {
  143. putenv(ServiceAccountCredentials::ENV_VAR); // removes it from
  144. }
  145. public function testIsNullIfEnvVarIsNotSet()
  146. {
  147. $this->assertNull(ServiceAccountCredentials::fromEnv());
  148. }
  149. /**
  150. * @expectedException DomainException
  151. */
  152. public function testFailsIfEnvSpecifiesNonExistentFile()
  153. {
  154. $keyFile = __DIR__ . '/../fixtures' . '/does-not-exist-private.json';
  155. putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
  156. ApplicationDefaultCredentials::getCredentials('a scope');
  157. }
  158. public function testSucceedIfFileExists()
  159. {
  160. $keyFile = __DIR__ . '/../fixtures' . '/private.json';
  161. putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
  162. $this->assertNotNull(ApplicationDefaultCredentials::getCredentials('a scope'));
  163. }
  164. }
  165. class SACFromWellKnownFileTest extends TestCase
  166. {
  167. private $originalHome;
  168. protected function setUp()
  169. {
  170. $this->originalHome = getenv('HOME');
  171. }
  172. protected function tearDown()
  173. {
  174. if ($this->originalHome != getenv('HOME')) {
  175. putenv('HOME=' . $this->originalHome);
  176. }
  177. }
  178. public function testIsNullIfFileDoesNotExist()
  179. {
  180. putenv('HOME=' . __DIR__ . '/../not_exists_fixtures');
  181. $this->assertNull(
  182. ServiceAccountCredentials::fromWellKnownFile()
  183. );
  184. }
  185. public function testSucceedIfFileIsPresent()
  186. {
  187. putenv('HOME=' . __DIR__ . '/../fixtures');
  188. $this->assertNotNull(
  189. ApplicationDefaultCredentials::getCredentials('a scope')
  190. );
  191. }
  192. }
  193. class SACFetchAuthTokenTest extends TestCase
  194. {
  195. private $privateKey;
  196. public function setUp()
  197. {
  198. $this->privateKey =
  199. file_get_contents(__DIR__ . '/../fixtures' . '/private.pem');
  200. }
  201. private function createTestJson()
  202. {
  203. $testJson = createTestJson();
  204. $testJson['private_key'] = $this->privateKey;
  205. return $testJson;
  206. }
  207. /**
  208. * @expectedException GuzzleHttp\Exception\ClientException
  209. */
  210. public function testFailsOnClientErrors()
  211. {
  212. $testJson = $this->createTestJson();
  213. $scope = ['scope/1', 'scope/2'];
  214. $httpHandler = getHandler([
  215. buildResponse(400),
  216. ]);
  217. $sa = new ServiceAccountCredentials(
  218. $scope,
  219. $testJson
  220. );
  221. $sa->fetchAuthToken($httpHandler);
  222. }
  223. /**
  224. * @expectedException GuzzleHttp\Exception\ServerException
  225. */
  226. public function testFailsOnServerErrors()
  227. {
  228. $testJson = $this->createTestJson();
  229. $scope = ['scope/1', 'scope/2'];
  230. $httpHandler = getHandler([
  231. buildResponse(500),
  232. ]);
  233. $sa = new ServiceAccountCredentials(
  234. $scope,
  235. $testJson
  236. );
  237. $sa->fetchAuthToken($httpHandler);
  238. }
  239. public function testCanFetchCredsOK()
  240. {
  241. $testJson = $this->createTestJson();
  242. $testJsonText = json_encode($testJson);
  243. $scope = ['scope/1', 'scope/2'];
  244. $httpHandler = getHandler([
  245. buildResponse(200, [], Psr7\stream_for($testJsonText)),
  246. ]);
  247. $sa = new ServiceAccountCredentials(
  248. $scope,
  249. $testJson
  250. );
  251. $tokens = $sa->fetchAuthToken($httpHandler);
  252. $this->assertEquals($testJson, $tokens);
  253. }
  254. public function testUpdateMetadataFunc()
  255. {
  256. $testJson = $this->createTestJson();
  257. $scope = ['scope/1', 'scope/2'];
  258. $access_token = 'accessToken123';
  259. $responseText = json_encode(array('access_token' => $access_token));
  260. $httpHandler = getHandler([
  261. buildResponse(200, [], Psr7\stream_for($responseText)),
  262. ]);
  263. $sa = new ServiceAccountCredentials(
  264. $scope,
  265. $testJson
  266. );
  267. $update_metadata = $sa->getUpdateMetadataFunc();
  268. $this->assertInternalType('callable', $update_metadata);
  269. $actual_metadata = call_user_func($update_metadata,
  270. $metadata = array('foo' => 'bar'),
  271. $authUri = null,
  272. $httpHandler);
  273. $this->assertArrayHasKey(
  274. CredentialsLoader::AUTH_METADATA_KEY,
  275. $actual_metadata
  276. );
  277. $this->assertEquals(
  278. $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY],
  279. array('Bearer ' . $access_token));
  280. }
  281. }
  282. class SACJwtAccessTest extends TestCase
  283. {
  284. private $privateKey;
  285. public function setUp()
  286. {
  287. $this->privateKey =
  288. file_get_contents(__DIR__ . '/../fixtures' . '/private.pem');
  289. }
  290. private function createTestJson()
  291. {
  292. $testJson = createTestJson();
  293. $testJson['private_key'] = $this->privateKey;
  294. return $testJson;
  295. }
  296. /**
  297. * @expectedException InvalidArgumentException
  298. */
  299. public function testFailsOnMissingClientEmail()
  300. {
  301. $testJson = $this->createTestJson();
  302. unset($testJson['client_email']);
  303. $sa = new ServiceAccountJwtAccessCredentials(
  304. $testJson
  305. );
  306. }
  307. /**
  308. * @expectedException InvalidArgumentException
  309. */
  310. public function testFailsOnMissingPrivateKey()
  311. {
  312. $testJson = $this->createTestJson();
  313. unset($testJson['private_key']);
  314. $sa = new ServiceAccountJwtAccessCredentials(
  315. $testJson
  316. );
  317. }
  318. public function testCanInitializeFromJson()
  319. {
  320. $testJson = $this->createTestJson();
  321. $sa = new ServiceAccountJwtAccessCredentials(
  322. $testJson
  323. );
  324. $this->assertNotNull($sa);
  325. }
  326. public function testNoOpOnFetchAuthToken()
  327. {
  328. $testJson = $this->createTestJson();
  329. $sa = new ServiceAccountJwtAccessCredentials(
  330. $testJson
  331. );
  332. $this->assertNotNull($sa);
  333. $httpHandler = getHandler([
  334. buildResponse(200),
  335. ]);
  336. $result = $sa->fetchAuthToken($httpHandler); // authUri has not been set
  337. $this->assertNull($result);
  338. }
  339. public function testAuthUriIsNotSet()
  340. {
  341. $testJson = $this->createTestJson();
  342. $sa = new ServiceAccountJwtAccessCredentials(
  343. $testJson
  344. );
  345. $this->assertNotNull($sa);
  346. $update_metadata = $sa->getUpdateMetadataFunc();
  347. $this->assertInternalType('callable', $update_metadata);
  348. $actual_metadata = call_user_func($update_metadata,
  349. $metadata = array('foo' => 'bar'),
  350. $authUri = null);
  351. $this->assertArrayNotHasKey(
  352. CredentialsLoader::AUTH_METADATA_KEY,
  353. $actual_metadata
  354. );
  355. }
  356. public function testUpdateMetadataFunc()
  357. {
  358. $testJson = $this->createTestJson();
  359. $sa = new ServiceAccountJwtAccessCredentials(
  360. $testJson
  361. );
  362. $this->assertNotNull($sa);
  363. $update_metadata = $sa->getUpdateMetadataFunc();
  364. $this->assertInternalType('callable', $update_metadata);
  365. $actual_metadata = call_user_func($update_metadata,
  366. $metadata = array('foo' => 'bar'),
  367. $authUri = 'https://example.com/service');
  368. $this->assertArrayHasKey(
  369. CredentialsLoader::AUTH_METADATA_KEY,
  370. $actual_metadata
  371. );
  372. $authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
  373. $this->assertInternalType('array', $authorization);
  374. $bearer_token = current($authorization);
  375. $this->assertInternalType('string', $bearer_token);
  376. $this->assertEquals(0, strpos($bearer_token, 'Bearer '));
  377. $this->assertGreaterThan(30, strlen($bearer_token));
  378. $actual_metadata2 = call_user_func($update_metadata,
  379. $metadata = array('foo' => 'bar'),
  380. $authUri = 'https://example.com/anotherService');
  381. $this->assertArrayHasKey(
  382. CredentialsLoader::AUTH_METADATA_KEY,
  383. $actual_metadata2
  384. );
  385. $authorization2 = $actual_metadata2[CredentialsLoader::AUTH_METADATA_KEY];
  386. $this->assertInternalType('array', $authorization2);
  387. $bearer_token2 = current($authorization2);
  388. $this->assertInternalType('string', $bearer_token2);
  389. $this->assertEquals(0, strpos($bearer_token2, 'Bearer '));
  390. $this->assertGreaterThan(30, strlen($bearer_token2));
  391. $this->assertNotEquals($bearer_token2, $bearer_token);
  392. }
  393. }
  394. class SACJwtAccessComboTest extends TestCase
  395. {
  396. private $privateKey;
  397. public function setUp()
  398. {
  399. $this->privateKey =
  400. file_get_contents(__DIR__ . '/../fixtures' . '/private.pem');
  401. }
  402. private function createTestJson()
  403. {
  404. $testJson = createTestJson();
  405. $testJson['private_key'] = $this->privateKey;
  406. return $testJson;
  407. }
  408. public function testNoScopeUseJwtAccess()
  409. {
  410. $testJson = $this->createTestJson();
  411. // no scope, jwt access should be used, no outbound
  412. // call should be made
  413. $scope = null;
  414. $sa = new ServiceAccountCredentials(
  415. $scope,
  416. $testJson
  417. );
  418. $this->assertNotNull($sa);
  419. $update_metadata = $sa->getUpdateMetadataFunc();
  420. $this->assertInternalType('callable', $update_metadata);
  421. $actual_metadata = call_user_func($update_metadata,
  422. $metadata = array('foo' => 'bar'),
  423. $authUri = 'https://example.com/service');
  424. $this->assertArrayHasKey(
  425. CredentialsLoader::AUTH_METADATA_KEY,
  426. $actual_metadata
  427. );
  428. $authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
  429. $this->assertInternalType('array', $authorization);
  430. $bearer_token = current($authorization);
  431. $this->assertInternalType('string', $bearer_token);
  432. $this->assertEquals(0, strpos($bearer_token, 'Bearer '));
  433. $this->assertGreaterThan(30, strlen($bearer_token));
  434. }
  435. public function testNoScopeAndNoAuthUri()
  436. {
  437. $testJson = $this->createTestJson();
  438. // no scope, jwt access should be used, no outbound
  439. // call should be made
  440. $scope = null;
  441. $sa = new ServiceAccountCredentials(
  442. $scope,
  443. $testJson
  444. );
  445. $this->assertNotNull($sa);
  446. $update_metadata = $sa->getUpdateMetadataFunc();
  447. $this->assertInternalType('callable', $update_metadata);
  448. $actual_metadata = call_user_func($update_metadata,
  449. $metadata = array('foo' => 'bar'),
  450. $authUri = null);
  451. // no access_token is added to the metadata hash
  452. // but also, no error should be thrown
  453. $this->assertInternalType('array', $actual_metadata);
  454. $this->assertArrayNotHasKey(
  455. CredentialsLoader::AUTH_METADATA_KEY,
  456. $actual_metadata
  457. );
  458. }
  459. }