test_pluggable.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. # Copyright 2022 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import os
  16. import subprocess
  17. import mock
  18. import pytest # type: ignore
  19. from google.auth import exceptions
  20. from google.auth import pluggable
  21. from .test__default import WORKFORCE_AUDIENCE
  22. CLIENT_ID = "username"
  23. CLIENT_SECRET = "password"
  24. # Base64 encoding of "username:password".
  25. BASIC_AUTH_ENCODING = "dXNlcm5hbWU6cGFzc3dvcmQ="
  26. SERVICE_ACCOUNT_EMAIL = "service-1234@service-name.iam.gserviceaccount.com"
  27. SERVICE_ACCOUNT_IMPERSONATION_URL_BASE = (
  28. "https://us-east1-iamcredentials.googleapis.com"
  29. )
  30. SERVICE_ACCOUNT_IMPERSONATION_URL_ROUTE = "/v1/projects/-/serviceAccounts/{}:generateAccessToken".format(
  31. SERVICE_ACCOUNT_EMAIL
  32. )
  33. SERVICE_ACCOUNT_IMPERSONATION_URL = (
  34. SERVICE_ACCOUNT_IMPERSONATION_URL_BASE + SERVICE_ACCOUNT_IMPERSONATION_URL_ROUTE
  35. )
  36. QUOTA_PROJECT_ID = "QUOTA_PROJECT_ID"
  37. SCOPES = ["scope1", "scope2"]
  38. SUBJECT_TOKEN_FIELD_NAME = "access_token"
  39. TOKEN_URL = "https://sts.googleapis.com/v1/token"
  40. TOKEN_INFO_URL = "https://sts.googleapis.com/v1/introspect"
  41. SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt"
  42. AUDIENCE = "//iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID"
  43. DEFAULT_UNIVERSE_DOMAIN = "googleapis.com"
  44. VALID_TOKEN_URLS = [
  45. "https://sts.googleapis.com",
  46. "https://us-east-1.sts.googleapis.com",
  47. "https://US-EAST-1.sts.googleapis.com",
  48. "https://sts.us-east-1.googleapis.com",
  49. "https://sts.US-WEST-1.googleapis.com",
  50. "https://us-east-1-sts.googleapis.com",
  51. "https://US-WEST-1-sts.googleapis.com",
  52. "https://us-west-1-sts.googleapis.com/path?query",
  53. "https://sts-us-east-1.p.googleapis.com",
  54. ]
  55. INVALID_TOKEN_URLS = [
  56. "https://iamcredentials.googleapis.com",
  57. "sts.googleapis.com",
  58. "https://",
  59. "http://sts.googleapis.com",
  60. "https://st.s.googleapis.com",
  61. "https://us-eas\t-1.sts.googleapis.com",
  62. "https:/us-east-1.sts.googleapis.com",
  63. "https://US-WE/ST-1-sts.googleapis.com",
  64. "https://sts-us-east-1.googleapis.com",
  65. "https://sts-US-WEST-1.googleapis.com",
  66. "testhttps://us-east-1.sts.googleapis.com",
  67. "https://us-east-1.sts.googleapis.comevil.com",
  68. "https://us-east-1.us-east-1.sts.googleapis.com",
  69. "https://us-ea.s.t.sts.googleapis.com",
  70. "https://sts.googleapis.comevil.com",
  71. "hhttps://us-east-1.sts.googleapis.com",
  72. "https://us- -1.sts.googleapis.com",
  73. "https://-sts.googleapis.com",
  74. "https://us-east-1.sts.googleapis.com.evil.com",
  75. "https://sts.pgoogleapis.com",
  76. "https://p.googleapis.com",
  77. "https://sts.p.com",
  78. "http://sts.p.googleapis.com",
  79. "https://xyz-sts.p.googleapis.com",
  80. "https://sts-xyz.123.p.googleapis.com",
  81. "https://sts-xyz.p1.googleapis.com",
  82. "https://sts-xyz.p.foo.com",
  83. "https://sts-xyz.p.foo.googleapis.com",
  84. ]
  85. VALID_SERVICE_ACCOUNT_IMPERSONATION_URLS = [
  86. "https://iamcredentials.googleapis.com",
  87. "https://us-east-1.iamcredentials.googleapis.com",
  88. "https://US-EAST-1.iamcredentials.googleapis.com",
  89. "https://iamcredentials.us-east-1.googleapis.com",
  90. "https://iamcredentials.US-WEST-1.googleapis.com",
  91. "https://us-east-1-iamcredentials.googleapis.com",
  92. "https://US-WEST-1-iamcredentials.googleapis.com",
  93. "https://us-west-1-iamcredentials.googleapis.com/path?query",
  94. "https://iamcredentials-us-east-1.p.googleapis.com",
  95. ]
  96. INVALID_SERVICE_ACCOUNT_IMPERSONATION_URLS = [
  97. "https://sts.googleapis.com",
  98. "iamcredentials.googleapis.com",
  99. "https://",
  100. "http://iamcredentials.googleapis.com",
  101. "https://iamcre.dentials.googleapis.com",
  102. "https://us-eas\t-1.iamcredentials.googleapis.com",
  103. "https:/us-east-1.iamcredentials.googleapis.com",
  104. "https://US-WE/ST-1-iamcredentials.googleapis.com",
  105. "https://iamcredentials-us-east-1.googleapis.com",
  106. "https://iamcredentials-US-WEST-1.googleapis.com",
  107. "testhttps://us-east-1.iamcredentials.googleapis.com",
  108. "https://us-east-1.iamcredentials.googleapis.comevil.com",
  109. "https://us-east-1.us-east-1.iamcredentials.googleapis.com",
  110. "https://us-ea.s.t.iamcredentials.googleapis.com",
  111. "https://iamcredentials.googleapis.comevil.com",
  112. "hhttps://us-east-1.iamcredentials.googleapis.com",
  113. "https://us- -1.iamcredentials.googleapis.com",
  114. "https://-iamcredentials.googleapis.com",
  115. "https://us-east-1.iamcredentials.googleapis.com.evil.com",
  116. "https://iamcredentials.pgoogleapis.com",
  117. "https://p.googleapis.com",
  118. "https://iamcredentials.p.com",
  119. "http://iamcredentials.p.googleapis.com",
  120. "https://xyz-iamcredentials.p.googleapis.com",
  121. "https://iamcredentials-xyz.123.p.googleapis.com",
  122. "https://iamcredentials-xyz.p1.googleapis.com",
  123. "https://iamcredentials-xyz.p.foo.com",
  124. "https://iamcredentials-xyz.p.foo.googleapis.com",
  125. ]
  126. class TestCredentials(object):
  127. CREDENTIAL_SOURCE_EXECUTABLE_COMMAND = (
  128. "/fake/external/excutable --arg1=value1 --arg2=value2"
  129. )
  130. CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE = "fake_output_file"
  131. CREDENTIAL_SOURCE_EXECUTABLE = {
  132. "command": CREDENTIAL_SOURCE_EXECUTABLE_COMMAND,
  133. "timeout_millis": 30000,
  134. "interactive_timeout_millis": 300000,
  135. "output_file": CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  136. }
  137. CREDENTIAL_SOURCE = {"executable": CREDENTIAL_SOURCE_EXECUTABLE}
  138. EXECUTABLE_OIDC_TOKEN = "FAKE_ID_TOKEN"
  139. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN = {
  140. "version": 1,
  141. "success": True,
  142. "token_type": "urn:ietf:params:oauth:token-type:id_token",
  143. "id_token": EXECUTABLE_OIDC_TOKEN,
  144. "expiration_time": 9999999999,
  145. }
  146. EXECUTABLE_SUCCESSFUL_OIDC_NO_EXPIRATION_TIME_RESPONSE_ID_TOKEN = {
  147. "version": 1,
  148. "success": True,
  149. "token_type": "urn:ietf:params:oauth:token-type:id_token",
  150. "id_token": EXECUTABLE_OIDC_TOKEN,
  151. }
  152. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_JWT = {
  153. "version": 1,
  154. "success": True,
  155. "token_type": "urn:ietf:params:oauth:token-type:jwt",
  156. "id_token": EXECUTABLE_OIDC_TOKEN,
  157. "expiration_time": 9999999999,
  158. }
  159. EXECUTABLE_SUCCESSFUL_OIDC_NO_EXPIRATION_TIME_RESPONSE_JWT = {
  160. "version": 1,
  161. "success": True,
  162. "token_type": "urn:ietf:params:oauth:token-type:jwt",
  163. "id_token": EXECUTABLE_OIDC_TOKEN,
  164. }
  165. EXECUTABLE_SAML_TOKEN = "FAKE_SAML_RESPONSE"
  166. EXECUTABLE_SUCCESSFUL_SAML_RESPONSE = {
  167. "version": 1,
  168. "success": True,
  169. "token_type": "urn:ietf:params:oauth:token-type:saml2",
  170. "saml_response": EXECUTABLE_SAML_TOKEN,
  171. "expiration_time": 9999999999,
  172. }
  173. EXECUTABLE_SUCCESSFUL_SAML_NO_EXPIRATION_TIME_RESPONSE = {
  174. "version": 1,
  175. "success": True,
  176. "token_type": "urn:ietf:params:oauth:token-type:saml2",
  177. "saml_response": EXECUTABLE_SAML_TOKEN,
  178. }
  179. EXECUTABLE_FAILED_RESPONSE = {
  180. "version": 1,
  181. "success": False,
  182. "code": "401",
  183. "message": "Permission denied. Caller not authorized",
  184. }
  185. CREDENTIAL_URL = "http://fakeurl.com"
  186. @classmethod
  187. def make_pluggable(
  188. cls,
  189. audience=AUDIENCE,
  190. subject_token_type=SUBJECT_TOKEN_TYPE,
  191. token_url=TOKEN_URL,
  192. token_info_url=TOKEN_INFO_URL,
  193. client_id=None,
  194. client_secret=None,
  195. quota_project_id=None,
  196. scopes=None,
  197. default_scopes=None,
  198. service_account_impersonation_url=None,
  199. credential_source=None,
  200. workforce_pool_user_project=None,
  201. interactive=None,
  202. ):
  203. return pluggable.Credentials(
  204. audience=audience,
  205. subject_token_type=subject_token_type,
  206. token_url=token_url,
  207. token_info_url=token_info_url,
  208. service_account_impersonation_url=service_account_impersonation_url,
  209. credential_source=credential_source,
  210. client_id=client_id,
  211. client_secret=client_secret,
  212. quota_project_id=quota_project_id,
  213. scopes=scopes,
  214. default_scopes=default_scopes,
  215. workforce_pool_user_project=workforce_pool_user_project,
  216. interactive=interactive,
  217. )
  218. def test_from_constructor_and_injection(self):
  219. credentials = pluggable.Credentials(
  220. audience=AUDIENCE,
  221. subject_token_type=SUBJECT_TOKEN_TYPE,
  222. token_url=TOKEN_URL,
  223. token_info_url=TOKEN_INFO_URL,
  224. credential_source=self.CREDENTIAL_SOURCE,
  225. interactive=True,
  226. )
  227. setattr(credentials, "_tokeninfo_username", "mock_external_account_id")
  228. assert isinstance(credentials, pluggable.Credentials)
  229. assert credentials.interactive
  230. assert credentials.external_account_id == "mock_external_account_id"
  231. @mock.patch.object(pluggable.Credentials, "__init__", return_value=None)
  232. def test_from_info_full_options(self, mock_init):
  233. credentials = pluggable.Credentials.from_info(
  234. {
  235. "audience": AUDIENCE,
  236. "subject_token_type": SUBJECT_TOKEN_TYPE,
  237. "token_url": TOKEN_URL,
  238. "token_info_url": TOKEN_INFO_URL,
  239. "service_account_impersonation_url": SERVICE_ACCOUNT_IMPERSONATION_URL,
  240. "service_account_impersonation": {"token_lifetime_seconds": 2800},
  241. "client_id": CLIENT_ID,
  242. "client_secret": CLIENT_SECRET,
  243. "quota_project_id": QUOTA_PROJECT_ID,
  244. "credential_source": self.CREDENTIAL_SOURCE,
  245. }
  246. )
  247. # Confirm pluggable.Credentials instantiated with expected attributes.
  248. assert isinstance(credentials, pluggable.Credentials)
  249. mock_init.assert_called_once_with(
  250. audience=AUDIENCE,
  251. subject_token_type=SUBJECT_TOKEN_TYPE,
  252. token_url=TOKEN_URL,
  253. token_info_url=TOKEN_INFO_URL,
  254. service_account_impersonation_url=SERVICE_ACCOUNT_IMPERSONATION_URL,
  255. service_account_impersonation_options={"token_lifetime_seconds": 2800},
  256. client_id=CLIENT_ID,
  257. client_secret=CLIENT_SECRET,
  258. credential_source=self.CREDENTIAL_SOURCE,
  259. quota_project_id=QUOTA_PROJECT_ID,
  260. workforce_pool_user_project=None,
  261. universe_domain=DEFAULT_UNIVERSE_DOMAIN,
  262. )
  263. @mock.patch.object(pluggable.Credentials, "__init__", return_value=None)
  264. def test_from_info_required_options_only(self, mock_init):
  265. credentials = pluggable.Credentials.from_info(
  266. {
  267. "audience": AUDIENCE,
  268. "subject_token_type": SUBJECT_TOKEN_TYPE,
  269. "token_url": TOKEN_URL,
  270. "credential_source": self.CREDENTIAL_SOURCE,
  271. }
  272. )
  273. # Confirm pluggable.Credentials instantiated with expected attributes.
  274. assert isinstance(credentials, pluggable.Credentials)
  275. mock_init.assert_called_once_with(
  276. audience=AUDIENCE,
  277. subject_token_type=SUBJECT_TOKEN_TYPE,
  278. token_url=TOKEN_URL,
  279. token_info_url=None,
  280. service_account_impersonation_url=None,
  281. service_account_impersonation_options={},
  282. client_id=None,
  283. client_secret=None,
  284. credential_source=self.CREDENTIAL_SOURCE,
  285. quota_project_id=None,
  286. workforce_pool_user_project=None,
  287. universe_domain=DEFAULT_UNIVERSE_DOMAIN,
  288. )
  289. @mock.patch.object(pluggable.Credentials, "__init__", return_value=None)
  290. def test_from_file_full_options(self, mock_init, tmpdir):
  291. info = {
  292. "audience": AUDIENCE,
  293. "subject_token_type": SUBJECT_TOKEN_TYPE,
  294. "token_url": TOKEN_URL,
  295. "token_info_url": TOKEN_INFO_URL,
  296. "service_account_impersonation_url": SERVICE_ACCOUNT_IMPERSONATION_URL,
  297. "service_account_impersonation": {"token_lifetime_seconds": 2800},
  298. "client_id": CLIENT_ID,
  299. "client_secret": CLIENT_SECRET,
  300. "quota_project_id": QUOTA_PROJECT_ID,
  301. "credential_source": self.CREDENTIAL_SOURCE,
  302. }
  303. config_file = tmpdir.join("config.json")
  304. config_file.write(json.dumps(info))
  305. credentials = pluggable.Credentials.from_file(str(config_file))
  306. # Confirm pluggable.Credentials instantiated with expected attributes.
  307. assert isinstance(credentials, pluggable.Credentials)
  308. mock_init.assert_called_once_with(
  309. audience=AUDIENCE,
  310. subject_token_type=SUBJECT_TOKEN_TYPE,
  311. token_url=TOKEN_URL,
  312. token_info_url=TOKEN_INFO_URL,
  313. service_account_impersonation_url=SERVICE_ACCOUNT_IMPERSONATION_URL,
  314. service_account_impersonation_options={"token_lifetime_seconds": 2800},
  315. client_id=CLIENT_ID,
  316. client_secret=CLIENT_SECRET,
  317. credential_source=self.CREDENTIAL_SOURCE,
  318. quota_project_id=QUOTA_PROJECT_ID,
  319. workforce_pool_user_project=None,
  320. universe_domain=DEFAULT_UNIVERSE_DOMAIN,
  321. )
  322. @mock.patch.object(pluggable.Credentials, "__init__", return_value=None)
  323. def test_from_file_required_options_only(self, mock_init, tmpdir):
  324. info = {
  325. "audience": AUDIENCE,
  326. "subject_token_type": SUBJECT_TOKEN_TYPE,
  327. "token_url": TOKEN_URL,
  328. "credential_source": self.CREDENTIAL_SOURCE,
  329. }
  330. config_file = tmpdir.join("config.json")
  331. config_file.write(json.dumps(info))
  332. credentials = pluggable.Credentials.from_file(str(config_file))
  333. # Confirm pluggable.Credentials instantiated with expected attributes.
  334. assert isinstance(credentials, pluggable.Credentials)
  335. mock_init.assert_called_once_with(
  336. audience=AUDIENCE,
  337. subject_token_type=SUBJECT_TOKEN_TYPE,
  338. token_url=TOKEN_URL,
  339. token_info_url=None,
  340. service_account_impersonation_url=None,
  341. service_account_impersonation_options={},
  342. client_id=None,
  343. client_secret=None,
  344. credential_source=self.CREDENTIAL_SOURCE,
  345. quota_project_id=None,
  346. workforce_pool_user_project=None,
  347. universe_domain=DEFAULT_UNIVERSE_DOMAIN,
  348. )
  349. def test_constructor_invalid_options(self):
  350. credential_source = {"unsupported": "value"}
  351. with pytest.raises(ValueError) as excinfo:
  352. self.make_pluggable(credential_source=credential_source)
  353. assert excinfo.match(r"Missing credential_source")
  354. def test_constructor_invalid_credential_source(self):
  355. with pytest.raises(ValueError) as excinfo:
  356. self.make_pluggable(credential_source="non-dict")
  357. assert excinfo.match(r"Missing credential_source")
  358. def test_info_with_credential_source(self):
  359. credentials = self.make_pluggable(
  360. credential_source=self.CREDENTIAL_SOURCE.copy()
  361. )
  362. assert credentials.info == {
  363. "type": "external_account",
  364. "audience": AUDIENCE,
  365. "subject_token_type": SUBJECT_TOKEN_TYPE,
  366. "token_url": TOKEN_URL,
  367. "token_info_url": TOKEN_INFO_URL,
  368. "credential_source": self.CREDENTIAL_SOURCE,
  369. "universe_domain": DEFAULT_UNIVERSE_DOMAIN,
  370. }
  371. def test_token_info_url(self):
  372. credentials = self.make_pluggable(
  373. credential_source=self.CREDENTIAL_SOURCE.copy()
  374. )
  375. assert credentials.token_info_url == TOKEN_INFO_URL
  376. def test_token_info_url_custom(self):
  377. for url in VALID_TOKEN_URLS:
  378. credentials = self.make_pluggable(
  379. credential_source=self.CREDENTIAL_SOURCE.copy(),
  380. token_info_url=(url + "/introspect"),
  381. )
  382. assert credentials.token_info_url == url + "/introspect"
  383. def test_token_info_url_negative(self):
  384. credentials = self.make_pluggable(
  385. credential_source=self.CREDENTIAL_SOURCE.copy(), token_info_url=None
  386. )
  387. assert not credentials.token_info_url
  388. def test_token_url_custom(self):
  389. for url in VALID_TOKEN_URLS:
  390. credentials = self.make_pluggable(
  391. credential_source=self.CREDENTIAL_SOURCE.copy(),
  392. token_url=(url + "/token"),
  393. )
  394. assert credentials._token_url == (url + "/token")
  395. def test_service_account_impersonation_url_custom(self):
  396. for url in VALID_SERVICE_ACCOUNT_IMPERSONATION_URLS:
  397. credentials = self.make_pluggable(
  398. credential_source=self.CREDENTIAL_SOURCE.copy(),
  399. service_account_impersonation_url=(
  400. url + SERVICE_ACCOUNT_IMPERSONATION_URL_ROUTE
  401. ),
  402. )
  403. assert credentials._service_account_impersonation_url == (
  404. url + SERVICE_ACCOUNT_IMPERSONATION_URL_ROUTE
  405. )
  406. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  407. def test_retrieve_subject_token_successfully(self, tmpdir):
  408. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE = tmpdir.join(
  409. "actual_output_file"
  410. )
  411. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE = {
  412. "command": "command",
  413. "interactive_timeout_millis": 300000,
  414. "output_file": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  415. }
  416. ACTUAL_CREDENTIAL_SOURCE = {"executable": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE}
  417. testData = {
  418. "subject_token_oidc_id_token": {
  419. "stdout": json.dumps(
  420. self.EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN
  421. ).encode("UTF-8"),
  422. "impersonation_url": SERVICE_ACCOUNT_IMPERSONATION_URL,
  423. "file_content": self.EXECUTABLE_SUCCESSFUL_OIDC_NO_EXPIRATION_TIME_RESPONSE_ID_TOKEN,
  424. "expect_token": self.EXECUTABLE_OIDC_TOKEN,
  425. },
  426. "subject_token_oidc_id_token_interacitve_mode": {
  427. "audience": WORKFORCE_AUDIENCE,
  428. "file_content": self.EXECUTABLE_SUCCESSFUL_OIDC_NO_EXPIRATION_TIME_RESPONSE_ID_TOKEN,
  429. "interactive": True,
  430. "expect_token": self.EXECUTABLE_OIDC_TOKEN,
  431. },
  432. "subject_token_oidc_jwt": {
  433. "stdout": json.dumps(
  434. self.EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_JWT
  435. ).encode("UTF-8"),
  436. "impersonation_url": SERVICE_ACCOUNT_IMPERSONATION_URL,
  437. "file_content": self.EXECUTABLE_SUCCESSFUL_OIDC_NO_EXPIRATION_TIME_RESPONSE_JWT,
  438. "expect_token": self.EXECUTABLE_OIDC_TOKEN,
  439. },
  440. "subject_token_oidc_jwt_interactive_mode": {
  441. "audience": WORKFORCE_AUDIENCE,
  442. "file_content": self.EXECUTABLE_SUCCESSFUL_OIDC_NO_EXPIRATION_TIME_RESPONSE_JWT,
  443. "interactive": True,
  444. "expect_token": self.EXECUTABLE_OIDC_TOKEN,
  445. },
  446. "subject_token_saml": {
  447. "stdout": json.dumps(self.EXECUTABLE_SUCCESSFUL_SAML_RESPONSE).encode(
  448. "UTF-8"
  449. ),
  450. "impersonation_url": SERVICE_ACCOUNT_IMPERSONATION_URL,
  451. "file_content": self.EXECUTABLE_SUCCESSFUL_SAML_NO_EXPIRATION_TIME_RESPONSE,
  452. "expect_token": self.EXECUTABLE_SAML_TOKEN,
  453. },
  454. "subject_token_saml_interactive_mode": {
  455. "audience": WORKFORCE_AUDIENCE,
  456. "file_content": self.EXECUTABLE_SUCCESSFUL_SAML_NO_EXPIRATION_TIME_RESPONSE,
  457. "interactive": True,
  458. "expect_token": self.EXECUTABLE_SAML_TOKEN,
  459. },
  460. }
  461. for data in testData.values():
  462. with open(
  463. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE, "w"
  464. ) as output_file:
  465. json.dump(data.get("file_content"), output_file)
  466. with mock.patch(
  467. "subprocess.run",
  468. return_value=subprocess.CompletedProcess(
  469. args=[], stdout=data.get("stdout"), returncode=0
  470. ),
  471. ):
  472. credentials = self.make_pluggable(
  473. audience=data.get("audience", AUDIENCE),
  474. service_account_impersonation_url=data.get("impersonation_url"),
  475. credential_source=ACTUAL_CREDENTIAL_SOURCE,
  476. interactive=data.get("interactive", False),
  477. )
  478. subject_token = credentials.retrieve_subject_token(None)
  479. assert subject_token == data.get("expect_token")
  480. os.remove(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE)
  481. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  482. def test_retrieve_subject_token_saml(self):
  483. with mock.patch(
  484. "subprocess.run",
  485. return_value=subprocess.CompletedProcess(
  486. args=[],
  487. stdout=json.dumps(self.EXECUTABLE_SUCCESSFUL_SAML_RESPONSE).encode(
  488. "UTF-8"
  489. ),
  490. returncode=0,
  491. ),
  492. ):
  493. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  494. subject_token = credentials.retrieve_subject_token(None)
  495. assert subject_token == self.EXECUTABLE_SAML_TOKEN
  496. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  497. def test_retrieve_subject_token_saml_interactive_mode(self, tmpdir):
  498. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE = tmpdir.join(
  499. "actual_output_file"
  500. )
  501. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE = {
  502. "command": "command",
  503. "interactive_timeout_millis": 300000,
  504. "output_file": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  505. }
  506. ACTUAL_CREDENTIAL_SOURCE = {"executable": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE}
  507. with open(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE, "w") as output_file:
  508. json.dump(
  509. self.EXECUTABLE_SUCCESSFUL_SAML_NO_EXPIRATION_TIME_RESPONSE, output_file
  510. )
  511. with mock.patch(
  512. "subprocess.run",
  513. return_value=subprocess.CompletedProcess(args=[], returncode=0),
  514. ):
  515. credentials = self.make_pluggable(
  516. audience=WORKFORCE_AUDIENCE,
  517. credential_source=ACTUAL_CREDENTIAL_SOURCE,
  518. interactive=True,
  519. )
  520. subject_token = credentials.retrieve_subject_token(None)
  521. assert subject_token == self.EXECUTABLE_SAML_TOKEN
  522. os.remove(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE)
  523. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  524. def test_retrieve_subject_token_failed(self):
  525. with mock.patch(
  526. "subprocess.run",
  527. return_value=subprocess.CompletedProcess(
  528. args=[],
  529. stdout=json.dumps(self.EXECUTABLE_FAILED_RESPONSE).encode("UTF-8"),
  530. returncode=0,
  531. ),
  532. ):
  533. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  534. with pytest.raises(exceptions.RefreshError) as excinfo:
  535. _ = credentials.retrieve_subject_token(None)
  536. assert excinfo.match(
  537. r"Executable returned unsuccessful response: code: 401, message: Permission denied. Caller not authorized."
  538. )
  539. @mock.patch.dict(
  540. os.environ,
  541. {
  542. "GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1",
  543. "GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE": "1",
  544. },
  545. )
  546. def test_retrieve_subject_token_failed_interactive_mode(self, tmpdir):
  547. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE = tmpdir.join(
  548. "actual_output_file"
  549. )
  550. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE = {
  551. "command": "command",
  552. "interactive_timeout_millis": 300000,
  553. "output_file": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  554. }
  555. ACTUAL_CREDENTIAL_SOURCE = {"executable": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE}
  556. with open(
  557. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE, "w", encoding="utf-8"
  558. ) as output_file:
  559. json.dump(self.EXECUTABLE_FAILED_RESPONSE, output_file)
  560. with mock.patch(
  561. "subprocess.run",
  562. return_value=subprocess.CompletedProcess(args=[], returncode=0),
  563. ):
  564. credentials = self.make_pluggable(
  565. audience=WORKFORCE_AUDIENCE,
  566. credential_source=ACTUAL_CREDENTIAL_SOURCE,
  567. interactive=True,
  568. )
  569. with pytest.raises(exceptions.RefreshError) as excinfo:
  570. _ = credentials.retrieve_subject_token(None)
  571. assert excinfo.match(
  572. r"Executable returned unsuccessful response: code: 401, message: Permission denied. Caller not authorized."
  573. )
  574. os.remove(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE)
  575. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "0"})
  576. def test_retrieve_subject_token_not_allowd(self):
  577. with mock.patch(
  578. "subprocess.run",
  579. return_value=subprocess.CompletedProcess(
  580. args=[],
  581. stdout=json.dumps(
  582. self.EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN
  583. ).encode("UTF-8"),
  584. returncode=0,
  585. ),
  586. ):
  587. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  588. with pytest.raises(ValueError) as excinfo:
  589. _ = credentials.retrieve_subject_token(None)
  590. assert excinfo.match(r"Executables need to be explicitly allowed")
  591. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  592. def test_retrieve_subject_token_invalid_version(self):
  593. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_VERSION_2 = {
  594. "version": 2,
  595. "success": True,
  596. "token_type": "urn:ietf:params:oauth:token-type:id_token",
  597. "id_token": self.EXECUTABLE_OIDC_TOKEN,
  598. "expiration_time": 9999999999,
  599. }
  600. with mock.patch(
  601. "subprocess.run",
  602. return_value=subprocess.CompletedProcess(
  603. args=[],
  604. stdout=json.dumps(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_VERSION_2).encode(
  605. "UTF-8"
  606. ),
  607. returncode=0,
  608. ),
  609. ):
  610. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  611. with pytest.raises(exceptions.RefreshError) as excinfo:
  612. _ = credentials.retrieve_subject_token(None)
  613. assert excinfo.match(r"Executable returned unsupported version.")
  614. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  615. def test_retrieve_subject_token_expired_token(self):
  616. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_EXPIRED = {
  617. "version": 1,
  618. "success": True,
  619. "token_type": "urn:ietf:params:oauth:token-type:id_token",
  620. "id_token": self.EXECUTABLE_OIDC_TOKEN,
  621. "expiration_time": 0,
  622. }
  623. with mock.patch(
  624. "subprocess.run",
  625. return_value=subprocess.CompletedProcess(
  626. args=[],
  627. stdout=json.dumps(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_EXPIRED).encode(
  628. "UTF-8"
  629. ),
  630. returncode=0,
  631. ),
  632. ):
  633. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  634. with pytest.raises(exceptions.RefreshError) as excinfo:
  635. _ = credentials.retrieve_subject_token(None)
  636. assert excinfo.match(r"The token returned by the executable is expired.")
  637. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  638. def test_retrieve_subject_token_file_cache(self, tmpdir):
  639. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE = tmpdir.join(
  640. "actual_output_file"
  641. )
  642. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE = {
  643. "command": "command",
  644. "timeout_millis": 30000,
  645. "output_file": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  646. }
  647. ACTUAL_CREDENTIAL_SOURCE = {"executable": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE}
  648. with open(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE, "w") as output_file:
  649. json.dump(self.EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN, output_file)
  650. credentials = self.make_pluggable(credential_source=ACTUAL_CREDENTIAL_SOURCE)
  651. subject_token = credentials.retrieve_subject_token(None)
  652. assert subject_token == self.EXECUTABLE_OIDC_TOKEN
  653. os.remove(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE)
  654. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  655. def test_retrieve_subject_token_no_file_cache(self):
  656. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE = {
  657. "command": "command",
  658. "timeout_millis": 30000,
  659. }
  660. ACTUAL_CREDENTIAL_SOURCE = {"executable": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE}
  661. with mock.patch(
  662. "subprocess.run",
  663. return_value=subprocess.CompletedProcess(
  664. args=[],
  665. stdout=json.dumps(
  666. self.EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN
  667. ).encode("UTF-8"),
  668. returncode=0,
  669. ),
  670. ):
  671. credentials = self.make_pluggable(
  672. credential_source=ACTUAL_CREDENTIAL_SOURCE
  673. )
  674. subject_token = credentials.retrieve_subject_token(None)
  675. assert subject_token == self.EXECUTABLE_OIDC_TOKEN
  676. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  677. def test_retrieve_subject_token_file_cache_value_error_report(self, tmpdir):
  678. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE = tmpdir.join(
  679. "actual_output_file"
  680. )
  681. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE = {
  682. "command": "command",
  683. "timeout_millis": 30000,
  684. "output_file": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  685. }
  686. ACTUAL_CREDENTIAL_SOURCE = {"executable": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE}
  687. ACTUAL_EXECUTABLE_RESPONSE = {
  688. "success": True,
  689. "token_type": "urn:ietf:params:oauth:token-type:id_token",
  690. "id_token": self.EXECUTABLE_OIDC_TOKEN,
  691. "expiration_time": 9999999999,
  692. }
  693. with open(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE, "w") as output_file:
  694. json.dump(ACTUAL_EXECUTABLE_RESPONSE, output_file)
  695. credentials = self.make_pluggable(credential_source=ACTUAL_CREDENTIAL_SOURCE)
  696. with pytest.raises(ValueError) as excinfo:
  697. _ = credentials.retrieve_subject_token(None)
  698. assert excinfo.match(r"The executable response is missing the version field.")
  699. os.remove(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE)
  700. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  701. def test_retrieve_subject_token_file_cache_refresh_error_retry(self, tmpdir):
  702. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE = tmpdir.join(
  703. "actual_output_file"
  704. )
  705. ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE = {
  706. "command": "command",
  707. "timeout_millis": 30000,
  708. "output_file": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  709. }
  710. ACTUAL_CREDENTIAL_SOURCE = {"executable": ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE}
  711. ACTUAL_EXECUTABLE_RESPONSE = {
  712. "version": 2,
  713. "success": True,
  714. "token_type": "urn:ietf:params:oauth:token-type:id_token",
  715. "id_token": self.EXECUTABLE_OIDC_TOKEN,
  716. "expiration_time": 9999999999,
  717. }
  718. with open(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE, "w") as output_file:
  719. json.dump(ACTUAL_EXECUTABLE_RESPONSE, output_file)
  720. with mock.patch(
  721. "subprocess.run",
  722. return_value=subprocess.CompletedProcess(
  723. args=[],
  724. stdout=json.dumps(
  725. self.EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE_ID_TOKEN
  726. ).encode("UTF-8"),
  727. returncode=0,
  728. ),
  729. ):
  730. credentials = self.make_pluggable(
  731. credential_source=ACTUAL_CREDENTIAL_SOURCE
  732. )
  733. subject_token = credentials.retrieve_subject_token(None)
  734. assert subject_token == self.EXECUTABLE_OIDC_TOKEN
  735. os.remove(ACTUAL_CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE)
  736. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  737. def test_retrieve_subject_token_unsupported_token_type(self):
  738. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE = {
  739. "version": 1,
  740. "success": True,
  741. "token_type": "unsupported_token_type",
  742. "id_token": self.EXECUTABLE_OIDC_TOKEN,
  743. "expiration_time": 9999999999,
  744. }
  745. with mock.patch(
  746. "subprocess.run",
  747. return_value=subprocess.CompletedProcess(
  748. args=[],
  749. stdout=json.dumps(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE).encode("UTF-8"),
  750. returncode=0,
  751. ),
  752. ):
  753. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  754. with pytest.raises(exceptions.RefreshError) as excinfo:
  755. _ = credentials.retrieve_subject_token(None)
  756. assert excinfo.match(r"Executable returned unsupported token type.")
  757. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  758. def test_retrieve_subject_token_missing_version(self):
  759. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE = {
  760. "success": True,
  761. "token_type": "urn:ietf:params:oauth:token-type:id_token",
  762. "id_token": self.EXECUTABLE_OIDC_TOKEN,
  763. "expiration_time": 9999999999,
  764. }
  765. with mock.patch(
  766. "subprocess.run",
  767. return_value=subprocess.CompletedProcess(
  768. args=[],
  769. stdout=json.dumps(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE).encode("UTF-8"),
  770. returncode=0,
  771. ),
  772. ):
  773. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  774. with pytest.raises(ValueError) as excinfo:
  775. _ = credentials.retrieve_subject_token(None)
  776. assert excinfo.match(
  777. r"The executable response is missing the version field."
  778. )
  779. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  780. def test_retrieve_subject_token_missing_success(self):
  781. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE = {
  782. "version": 1,
  783. "token_type": "urn:ietf:params:oauth:token-type:id_token",
  784. "id_token": self.EXECUTABLE_OIDC_TOKEN,
  785. "expiration_time": 9999999999,
  786. }
  787. with mock.patch(
  788. "subprocess.run",
  789. return_value=subprocess.CompletedProcess(
  790. args=[],
  791. stdout=json.dumps(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE).encode("UTF-8"),
  792. returncode=0,
  793. ),
  794. ):
  795. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  796. with pytest.raises(ValueError) as excinfo:
  797. _ = credentials.retrieve_subject_token(None)
  798. assert excinfo.match(
  799. r"The executable response is missing the success field."
  800. )
  801. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  802. def test_retrieve_subject_token_missing_error_code_message(self):
  803. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE = {"version": 1, "success": False}
  804. with mock.patch(
  805. "subprocess.run",
  806. return_value=subprocess.CompletedProcess(
  807. args=[],
  808. stdout=json.dumps(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE).encode("UTF-8"),
  809. returncode=0,
  810. ),
  811. ):
  812. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  813. with pytest.raises(ValueError) as excinfo:
  814. _ = credentials.retrieve_subject_token(None)
  815. assert excinfo.match(
  816. r"Error code and message fields are required in the response."
  817. )
  818. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  819. def test_retrieve_subject_token_without_expiration_time_should_pass_when_output_file_not_specified(
  820. self,
  821. ):
  822. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE = {
  823. "version": 1,
  824. "success": True,
  825. "token_type": "urn:ietf:params:oauth:token-type:id_token",
  826. "id_token": self.EXECUTABLE_OIDC_TOKEN,
  827. }
  828. CREDENTIAL_SOURCE = {
  829. "executable": {"command": "command", "timeout_millis": 30000}
  830. }
  831. with mock.patch(
  832. "subprocess.run",
  833. return_value=subprocess.CompletedProcess(
  834. args=[],
  835. stdout=json.dumps(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE).encode("UTF-8"),
  836. returncode=0,
  837. ),
  838. ):
  839. credentials = self.make_pluggable(credential_source=CREDENTIAL_SOURCE)
  840. subject_token = credentials.retrieve_subject_token(None)
  841. assert subject_token == self.EXECUTABLE_OIDC_TOKEN
  842. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  843. def test_retrieve_subject_token_missing_token_type(self):
  844. EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE = {
  845. "version": 1,
  846. "success": True,
  847. "id_token": self.EXECUTABLE_OIDC_TOKEN,
  848. "expiration_time": 9999999999,
  849. }
  850. with mock.patch(
  851. "subprocess.run",
  852. return_value=subprocess.CompletedProcess(
  853. args=[],
  854. stdout=json.dumps(EXECUTABLE_SUCCESSFUL_OIDC_RESPONSE).encode("UTF-8"),
  855. returncode=0,
  856. ),
  857. ):
  858. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  859. with pytest.raises(ValueError) as excinfo:
  860. _ = credentials.retrieve_subject_token(None)
  861. assert excinfo.match(
  862. r"The executable response is missing the token_type field."
  863. )
  864. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  865. def test_credential_source_missing_command(self):
  866. with pytest.raises(ValueError) as excinfo:
  867. CREDENTIAL_SOURCE = {
  868. "executable": {
  869. "timeout_millis": 30000,
  870. "output_file": self.CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  871. }
  872. }
  873. _ = self.make_pluggable(credential_source=CREDENTIAL_SOURCE)
  874. assert excinfo.match(
  875. r"Missing command field. Executable command must be provided."
  876. )
  877. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  878. def test_credential_source_missing_output_interactive_mode(self):
  879. CREDENTIAL_SOURCE = {
  880. "executable": {"command": self.CREDENTIAL_SOURCE_EXECUTABLE_COMMAND}
  881. }
  882. credentials = self.make_pluggable(
  883. credential_source=CREDENTIAL_SOURCE, interactive=True
  884. )
  885. with pytest.raises(ValueError) as excinfo:
  886. _ = credentials.retrieve_subject_token(None)
  887. assert excinfo.match(
  888. r"An output_file must be specified in the credential configuration for interactive mode."
  889. )
  890. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  891. def test_credential_source_timeout_missing_will_use_default_timeout_value(self):
  892. CREDENTIAL_SOURCE = {
  893. "executable": {
  894. "command": self.CREDENTIAL_SOURCE_EXECUTABLE_COMMAND,
  895. "output_file": self.CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  896. }
  897. }
  898. credentials = self.make_pluggable(credential_source=CREDENTIAL_SOURCE)
  899. assert (
  900. credentials._credential_source_executable_timeout_millis
  901. == pluggable.EXECUTABLE_TIMEOUT_MILLIS_DEFAULT
  902. )
  903. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  904. def test_credential_source_timeout_small(self):
  905. with pytest.raises(ValueError) as excinfo:
  906. CREDENTIAL_SOURCE = {
  907. "executable": {
  908. "command": self.CREDENTIAL_SOURCE_EXECUTABLE_COMMAND,
  909. "timeout_millis": 5000 - 1,
  910. "output_file": self.CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  911. }
  912. }
  913. _ = self.make_pluggable(credential_source=CREDENTIAL_SOURCE)
  914. assert excinfo.match(r"Timeout must be between 5 and 120 seconds.")
  915. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  916. def test_credential_source_timeout_large(self):
  917. with pytest.raises(ValueError) as excinfo:
  918. CREDENTIAL_SOURCE = {
  919. "executable": {
  920. "command": self.CREDENTIAL_SOURCE_EXECUTABLE_COMMAND,
  921. "timeout_millis": 120000 + 1,
  922. "output_file": self.CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  923. }
  924. }
  925. _ = self.make_pluggable(credential_source=CREDENTIAL_SOURCE)
  926. assert excinfo.match(r"Timeout must be between 5 and 120 seconds.")
  927. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  928. def test_credential_source_interactive_timeout_small(self):
  929. with pytest.raises(ValueError) as excinfo:
  930. CREDENTIAL_SOURCE = {
  931. "executable": {
  932. "command": self.CREDENTIAL_SOURCE_EXECUTABLE_COMMAND,
  933. "interactive_timeout_millis": 30000 - 1,
  934. "output_file": self.CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  935. }
  936. }
  937. _ = self.make_pluggable(credential_source=CREDENTIAL_SOURCE)
  938. assert excinfo.match(
  939. r"Interactive timeout must be between 30 seconds and 30 minutes."
  940. )
  941. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  942. def test_credential_source_interactive_timeout_large(self):
  943. with pytest.raises(ValueError) as excinfo:
  944. CREDENTIAL_SOURCE = {
  945. "executable": {
  946. "command": self.CREDENTIAL_SOURCE_EXECUTABLE_COMMAND,
  947. "interactive_timeout_millis": 1800000 + 1,
  948. "output_file": self.CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  949. }
  950. }
  951. _ = self.make_pluggable(credential_source=CREDENTIAL_SOURCE)
  952. assert excinfo.match(
  953. r"Interactive timeout must be between 30 seconds and 30 minutes."
  954. )
  955. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  956. def test_retrieve_subject_token_executable_fail(self):
  957. with mock.patch(
  958. "subprocess.run",
  959. return_value=subprocess.CompletedProcess(
  960. args=[], stdout=None, returncode=1
  961. ),
  962. ):
  963. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  964. with pytest.raises(exceptions.RefreshError) as excinfo:
  965. _ = credentials.retrieve_subject_token(None)
  966. assert excinfo.match(
  967. r"Executable exited with non-zero return code 1. Error: None"
  968. )
  969. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  970. def test_retrieve_subject_token_non_workforce_fail_interactive_mode(self):
  971. credentials = self.make_pluggable(
  972. credential_source=self.CREDENTIAL_SOURCE, interactive=True
  973. )
  974. with pytest.raises(ValueError) as excinfo:
  975. _ = credentials.retrieve_subject_token(None)
  976. assert excinfo.match(r"Interactive mode is only enabled for workforce pool.")
  977. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  978. def test_retrieve_subject_token_fail_on_validation_missing_interactive_timeout(
  979. self
  980. ):
  981. CREDENTIAL_SOURCE_EXECUTABLE = {
  982. "command": self.CREDENTIAL_SOURCE_EXECUTABLE_COMMAND,
  983. "output_file": self.CREDENTIAL_SOURCE_EXECUTABLE_OUTPUT_FILE,
  984. }
  985. CREDENTIAL_SOURCE = {"executable": CREDENTIAL_SOURCE_EXECUTABLE}
  986. credentials = self.make_pluggable(
  987. credential_source=CREDENTIAL_SOURCE, interactive=True
  988. )
  989. with pytest.raises(ValueError) as excinfo:
  990. _ = credentials.retrieve_subject_token(None)
  991. assert excinfo.match(
  992. r"Interactive mode cannot run without an interactive timeout."
  993. )
  994. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  995. def test_retrieve_subject_token_executable_fail_interactive_mode(self):
  996. with mock.patch(
  997. "subprocess.run",
  998. return_value=subprocess.CompletedProcess(
  999. args=[], stdout=None, returncode=1
  1000. ),
  1001. ):
  1002. credentials = self.make_pluggable(
  1003. audience=WORKFORCE_AUDIENCE,
  1004. credential_source=self.CREDENTIAL_SOURCE,
  1005. interactive=True,
  1006. )
  1007. with pytest.raises(exceptions.RefreshError) as excinfo:
  1008. _ = credentials.retrieve_subject_token(None)
  1009. assert excinfo.match(
  1010. r"Executable exited with non-zero return code 1. Error: None"
  1011. )
  1012. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "0"})
  1013. def test_revoke_failed_executable_not_allowed(self):
  1014. credentials = self.make_pluggable(
  1015. credential_source=self.CREDENTIAL_SOURCE, interactive=True
  1016. )
  1017. with pytest.raises(ValueError) as excinfo:
  1018. _ = credentials.revoke(None)
  1019. assert excinfo.match(r"Executables need to be explicitly allowed")
  1020. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  1021. def test_revoke_failed(self):
  1022. testData = {
  1023. "non_interactive_mode": {
  1024. "interactive": False,
  1025. "expectErrType": ValueError,
  1026. "expectErrPattern": r"Revoke is only enabled under interactive mode.",
  1027. },
  1028. "executable_failed": {
  1029. "returncode": 1,
  1030. "expectErrType": exceptions.RefreshError,
  1031. "expectErrPattern": r"Auth revoke failed on executable.",
  1032. },
  1033. "response_validation_missing_version": {
  1034. "response": {},
  1035. "expectErrType": ValueError,
  1036. "expectErrPattern": r"The executable response is missing the version field.",
  1037. },
  1038. "response_validation_invalid_version": {
  1039. "response": {"version": 2},
  1040. "expectErrType": exceptions.RefreshError,
  1041. "expectErrPattern": r"Executable returned unsupported version.",
  1042. },
  1043. "response_validation_missing_success": {
  1044. "response": {"version": 1},
  1045. "expectErrType": ValueError,
  1046. "expectErrPattern": r"The executable response is missing the success field.",
  1047. },
  1048. "response_validation_failed_with_success_field_is_false": {
  1049. "response": {"version": 1, "success": False},
  1050. "expectErrType": exceptions.RefreshError,
  1051. "expectErrPattern": r"Revoke failed with unsuccessful response.",
  1052. },
  1053. }
  1054. for data in testData.values():
  1055. with mock.patch(
  1056. "subprocess.run",
  1057. return_value=subprocess.CompletedProcess(
  1058. args=[],
  1059. stdout=json.dumps(data.get("response")).encode("UTF-8"),
  1060. returncode=data.get("returncode", 0),
  1061. ),
  1062. ):
  1063. credentials = self.make_pluggable(
  1064. audience=WORKFORCE_AUDIENCE,
  1065. service_account_impersonation_url=SERVICE_ACCOUNT_IMPERSONATION_URL,
  1066. credential_source=self.CREDENTIAL_SOURCE,
  1067. interactive=data.get("interactive", True),
  1068. )
  1069. with pytest.raises(data.get("expectErrType")) as excinfo:
  1070. _ = credentials.revoke(None)
  1071. assert excinfo.match(data.get("expectErrPattern"))
  1072. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  1073. def test_revoke_successfully(self):
  1074. ACTUAL_RESPONSE = {"version": 1, "success": True}
  1075. with mock.patch(
  1076. "subprocess.run",
  1077. return_value=subprocess.CompletedProcess(
  1078. args=[],
  1079. stdout=json.dumps(ACTUAL_RESPONSE).encode("utf-8"),
  1080. returncode=0,
  1081. ),
  1082. ):
  1083. credentials = self.make_pluggable(
  1084. audience=WORKFORCE_AUDIENCE,
  1085. credential_source=self.CREDENTIAL_SOURCE,
  1086. interactive=True,
  1087. )
  1088. _ = credentials.revoke(None)
  1089. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  1090. def test_retrieve_subject_token_python_2(self):
  1091. with mock.patch("sys.version_info", (2, 7)):
  1092. credentials = self.make_pluggable(credential_source=self.CREDENTIAL_SOURCE)
  1093. with pytest.raises(exceptions.RefreshError) as excinfo:
  1094. _ = credentials.retrieve_subject_token(None)
  1095. assert excinfo.match(r"Pluggable auth is only supported for python 3.7+")
  1096. @mock.patch.dict(os.environ, {"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES": "1"})
  1097. def test_revoke_subject_token_python_2(self):
  1098. with mock.patch("sys.version_info", (2, 7)):
  1099. credentials = self.make_pluggable(
  1100. audience=WORKFORCE_AUDIENCE,
  1101. credential_source=self.CREDENTIAL_SOURCE,
  1102. interactive=True,
  1103. )
  1104. with pytest.raises(exceptions.RefreshError) as excinfo:
  1105. _ = credentials.revoke(None)
  1106. assert excinfo.match(r"Pluggable auth is only supported for python 3.7+")