File size: 85,812 Bytes
065fee7 |
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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 |
# Copyright 2020 Google LLC
#
# 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.
import datetime
import http.client as http_client
import json
import urllib
import mock
import pytest # type: ignore
from google.auth import _helpers
from google.auth import exceptions
from google.auth import external_account
from google.auth import transport
from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN
from google.auth.credentials import TokenState
IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE = (
"gl-python/3.7 auth/1.1 auth-request-type/at cred-type/imp"
)
LANG_LIBRARY_METRICS_HEADER_VALUE = "gl-python/3.7 auth/1.1"
CLIENT_ID = "username"
CLIENT_SECRET = "password"
# Base64 encoding of "username:password"
BASIC_AUTH_ENCODING = "dXNlcm5hbWU6cGFzc3dvcmQ="
SERVICE_ACCOUNT_EMAIL = "service-1234@service-name.iam.gserviceaccount.com"
# List of valid workforce pool audiences.
TEST_USER_AUDIENCES = [
"//iam.googleapis.com/locations/global/workforcePools/pool-id/providers/provider-id",
"//iam.googleapis.com/locations/eu/workforcePools/pool-id/providers/provider-id",
"//iam.googleapis.com/locations/eu/workforcePools/workloadIdentityPools/providers/provider-id",
]
# Workload identity pool audiences or invalid workforce pool audiences.
TEST_NON_USER_AUDIENCES = [
# Legacy K8s audience format.
"identitynamespace:1f12345:my_provider",
(
"//iam.googleapis.com/projects/123456/locations/"
"global/workloadIdentityPools/pool-id/providers/"
"provider-id"
),
(
"//iam.googleapis.com/projects/123456/locations/"
"eu/workloadIdentityPools/pool-id/providers/"
"provider-id"
),
# Pool ID with workforcePools string.
(
"//iam.googleapis.com/projects/123456/locations/"
"global/workloadIdentityPools/workforcePools/providers/"
"provider-id"
),
# Unrealistic / incorrect workforce pool audiences.
"//iamgoogleapis.com/locations/eu/workforcePools/pool-id/providers/provider-id",
"//iam.googleapiscom/locations/eu/workforcePools/pool-id/providers/provider-id",
"//iam.googleapis.com/locations/workforcePools/pool-id/providers/provider-id",
"//iam.googleapis.com/locations/eu/workforcePool/pool-id/providers/provider-id",
"//iam.googleapis.com/locations//workforcePool/pool-id/providers/provider-id",
]
class CredentialsImpl(external_account.Credentials):
def __init__(self, **kwargs):
super(CredentialsImpl, self).__init__(**kwargs)
self._counter = 0
def retrieve_subject_token(self, request):
counter = self._counter
self._counter += 1
return "subject_token_{}".format(counter)
class TestCredentials(object):
TOKEN_URL = "https://sts.googleapis.com/v1/token"
TOKEN_INFO_URL = "https://sts.googleapis.com/v1/introspect"
PROJECT_NUMBER = "123456"
POOL_ID = "POOL_ID"
PROVIDER_ID = "PROVIDER_ID"
AUDIENCE = (
"//iam.googleapis.com/projects/{}"
"/locations/global/workloadIdentityPools/{}"
"/providers/{}"
).format(PROJECT_NUMBER, POOL_ID, PROVIDER_ID)
WORKFORCE_AUDIENCE = (
"//iam.googleapis.com/locations/global/workforcePools/{}/providers/{}"
).format(POOL_ID, PROVIDER_ID)
WORKFORCE_POOL_USER_PROJECT = "WORKFORCE_POOL_USER_PROJECT_NUMBER"
SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt"
WORKFORCE_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id_token"
CREDENTIAL_SOURCE = {"file": "/var/run/secrets/goog.id/token"}
SUCCESS_RESPONSE = {
"access_token": "ACCESS_TOKEN",
"issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "scope1 scope2",
}
ERROR_RESPONSE = {
"error": "invalid_request",
"error_description": "Invalid subject token",
"error_uri": "https://tools.ietf.org/html/rfc6749",
}
QUOTA_PROJECT_ID = "QUOTA_PROJECT_ID"
SERVICE_ACCOUNT_IMPERSONATION_URL = (
"https://us-east1-iamcredentials.googleapis.com/v1/projects/-"
+ "/serviceAccounts/{}:generateAccessToken".format(SERVICE_ACCOUNT_EMAIL)
)
SCOPES = ["scope1", "scope2"]
IMPERSONATION_ERROR_RESPONSE = {
"error": {
"code": 400,
"message": "Request contains an invalid argument",
"status": "INVALID_ARGUMENT",
}
}
PROJECT_ID = "my-proj-id"
CLOUD_RESOURCE_MANAGER_URL = (
"https://cloudresourcemanager.googleapis.com/v1/projects/"
)
CLOUD_RESOURCE_MANAGER_SUCCESS_RESPONSE = {
"projectNumber": PROJECT_NUMBER,
"projectId": PROJECT_ID,
"lifecycleState": "ACTIVE",
"name": "project-name",
"createTime": "2018-11-06T04:42:54.109Z",
"parent": {"type": "folder", "id": "12345678901"},
}
@classmethod
def make_credentials(
cls,
client_id=None,
client_secret=None,
quota_project_id=None,
token_info_url=None,
scopes=None,
default_scopes=None,
service_account_impersonation_url=None,
service_account_impersonation_options={},
universe_domain=DEFAULT_UNIVERSE_DOMAIN,
):
return CredentialsImpl(
audience=cls.AUDIENCE,
subject_token_type=cls.SUBJECT_TOKEN_TYPE,
token_url=cls.TOKEN_URL,
token_info_url=token_info_url,
service_account_impersonation_url=service_account_impersonation_url,
service_account_impersonation_options=service_account_impersonation_options,
credential_source=cls.CREDENTIAL_SOURCE,
client_id=client_id,
client_secret=client_secret,
quota_project_id=quota_project_id,
scopes=scopes,
default_scopes=default_scopes,
universe_domain=universe_domain,
)
@classmethod
def make_workforce_pool_credentials(
cls,
client_id=None,
client_secret=None,
quota_project_id=None,
scopes=None,
default_scopes=None,
service_account_impersonation_url=None,
workforce_pool_user_project=None,
):
return CredentialsImpl(
audience=cls.WORKFORCE_AUDIENCE,
subject_token_type=cls.WORKFORCE_SUBJECT_TOKEN_TYPE,
token_url=cls.TOKEN_URL,
service_account_impersonation_url=service_account_impersonation_url,
credential_source=cls.CREDENTIAL_SOURCE,
client_id=client_id,
client_secret=client_secret,
quota_project_id=quota_project_id,
scopes=scopes,
default_scopes=default_scopes,
workforce_pool_user_project=workforce_pool_user_project,
)
@classmethod
def make_mock_request(
cls,
status=http_client.OK,
data=None,
impersonation_status=None,
impersonation_data=None,
cloud_resource_manager_status=None,
cloud_resource_manager_data=None,
):
# STS token exchange request.
token_response = mock.create_autospec(transport.Response, instance=True)
token_response.status = status
token_response.data = json.dumps(data).encode("utf-8")
responses = [token_response]
# If service account impersonation is requested, mock the expected response.
if impersonation_status:
impersonation_response = mock.create_autospec(
transport.Response, instance=True
)
impersonation_response.status = impersonation_status
impersonation_response.data = json.dumps(impersonation_data).encode("utf-8")
responses.append(impersonation_response)
# If cloud resource manager is requested, mock the expected response.
if cloud_resource_manager_status:
cloud_resource_manager_response = mock.create_autospec(
transport.Response, instance=True
)
cloud_resource_manager_response.status = cloud_resource_manager_status
cloud_resource_manager_response.data = json.dumps(
cloud_resource_manager_data
).encode("utf-8")
responses.append(cloud_resource_manager_response)
request = mock.create_autospec(transport.Request)
request.side_effect = responses
return request
@classmethod
def assert_token_request_kwargs(
cls, request_kwargs, headers, request_data, cert=None
):
assert request_kwargs["url"] == cls.TOKEN_URL
assert request_kwargs["method"] == "POST"
assert request_kwargs["headers"] == headers
if cert is not None:
assert request_kwargs["cert"] == cert
else:
assert "cert" not in request_kwargs
assert request_kwargs["body"] is not None
body_tuples = urllib.parse.parse_qsl(request_kwargs["body"])
for (k, v) in body_tuples:
assert v.decode("utf-8") == request_data[k.decode("utf-8")]
assert len(body_tuples) == len(request_data.keys())
@classmethod
def assert_impersonation_request_kwargs(
cls, request_kwargs, headers, request_data, cert=None
):
assert request_kwargs["url"] == cls.SERVICE_ACCOUNT_IMPERSONATION_URL
assert request_kwargs["method"] == "POST"
assert request_kwargs["headers"] == headers
if cert is not None:
assert request_kwargs["cert"] == cert
else:
assert "cert" not in request_kwargs
assert request_kwargs["body"] is not None
body_json = json.loads(request_kwargs["body"].decode("utf-8"))
assert body_json == request_data
@classmethod
def assert_resource_manager_request_kwargs(
cls, request_kwargs, project_number, headers
):
assert request_kwargs["url"] == cls.CLOUD_RESOURCE_MANAGER_URL + project_number
assert request_kwargs["method"] == "GET"
assert request_kwargs["headers"] == headers
assert "body" not in request_kwargs
def test_default_state(self):
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL
)
# Token url and service account impersonation url should be set
assert credentials._token_url
assert credentials._service_account_impersonation_url
# Not token acquired yet
assert not credentials.token
assert not credentials.valid
# Expiration hasn't been set yet
assert not credentials.expiry
assert not credentials.expired
# Scopes are required
assert not credentials.scopes
assert credentials.requires_scopes
assert not credentials.quota_project_id
# Token info url not set yet
assert not credentials.token_info_url
def test_nonworkforce_with_workforce_pool_user_project(self):
with pytest.raises(ValueError) as excinfo:
CredentialsImpl(
audience=self.AUDIENCE,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT,
)
assert excinfo.match(
"workforce_pool_user_project should not be set for non-workforce "
"pool credentials"
)
def test_with_scopes(self):
credentials = self.make_credentials()
assert not credentials.scopes
assert credentials.requires_scopes
scoped_credentials = credentials.with_scopes(["email"])
assert scoped_credentials.has_scopes(["email"])
assert not scoped_credentials.requires_scopes
def test_with_scopes_workforce_pool(self):
credentials = self.make_workforce_pool_credentials(
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT
)
assert not credentials.scopes
assert credentials.requires_scopes
scoped_credentials = credentials.with_scopes(["email"])
assert scoped_credentials.has_scopes(["email"])
assert not scoped_credentials.requires_scopes
assert (
scoped_credentials.info.get("workforce_pool_user_project")
== self.WORKFORCE_POOL_USER_PROJECT
)
def test_with_scopes_using_user_and_default_scopes(self):
credentials = self.make_credentials()
assert not credentials.scopes
assert credentials.requires_scopes
scoped_credentials = credentials.with_scopes(
["email"], default_scopes=["profile"]
)
assert scoped_credentials.has_scopes(["email"])
assert not scoped_credentials.has_scopes(["profile"])
assert not scoped_credentials.requires_scopes
assert scoped_credentials.scopes == ["email"]
assert scoped_credentials.default_scopes == ["profile"]
def test_with_scopes_using_default_scopes_only(self):
credentials = self.make_credentials()
assert not credentials.scopes
assert credentials.requires_scopes
scoped_credentials = credentials.with_scopes(None, default_scopes=["profile"])
assert scoped_credentials.has_scopes(["profile"])
assert not scoped_credentials.requires_scopes
def test_with_scopes_full_options_propagated(self):
credentials = self.make_credentials(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
quota_project_id=self.QUOTA_PROJECT_ID,
scopes=self.SCOPES,
token_info_url=self.TOKEN_INFO_URL,
default_scopes=["default1"],
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
service_account_impersonation_options={"token_lifetime_seconds": 2800},
)
with mock.patch.object(
external_account.Credentials, "__init__", return_value=None
) as mock_init:
credentials.with_scopes(["email"], ["default2"])
# Confirm with_scopes initialized the credential with the expected
# parameters and scopes.
mock_init.assert_called_once_with(
audience=self.AUDIENCE,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
token_info_url=self.TOKEN_INFO_URL,
credential_source=self.CREDENTIAL_SOURCE,
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
service_account_impersonation_options={"token_lifetime_seconds": 2800},
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
quota_project_id=self.QUOTA_PROJECT_ID,
scopes=["email"],
default_scopes=["default2"],
universe_domain=DEFAULT_UNIVERSE_DOMAIN,
)
def test_with_token_uri(self):
credentials = self.make_credentials()
new_token_uri = "https://eu-sts.googleapis.com/v1/token"
assert credentials._token_url == self.TOKEN_URL
creds_with_new_token_uri = credentials.with_token_uri(new_token_uri)
assert creds_with_new_token_uri._token_url == new_token_uri
def test_with_token_uri_workforce_pool(self):
credentials = self.make_workforce_pool_credentials(
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT
)
new_token_uri = "https://eu-sts.googleapis.com/v1/token"
assert credentials._token_url == self.TOKEN_URL
creds_with_new_token_uri = credentials.with_token_uri(new_token_uri)
assert creds_with_new_token_uri._token_url == new_token_uri
assert (
creds_with_new_token_uri.info.get("workforce_pool_user_project")
== self.WORKFORCE_POOL_USER_PROJECT
)
def test_with_quota_project(self):
credentials = self.make_credentials()
assert not credentials.scopes
assert not credentials.quota_project_id
quota_project_creds = credentials.with_quota_project("project-foo")
assert quota_project_creds.quota_project_id == "project-foo"
def test_with_quota_project_workforce_pool(self):
credentials = self.make_workforce_pool_credentials(
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT
)
assert not credentials.scopes
assert not credentials.quota_project_id
quota_project_creds = credentials.with_quota_project("project-foo")
assert quota_project_creds.quota_project_id == "project-foo"
assert (
quota_project_creds.info.get("workforce_pool_user_project")
== self.WORKFORCE_POOL_USER_PROJECT
)
def test_with_quota_project_full_options_propagated(self):
credentials = self.make_credentials(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
token_info_url=self.TOKEN_INFO_URL,
quota_project_id=self.QUOTA_PROJECT_ID,
scopes=self.SCOPES,
default_scopes=["default1"],
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
service_account_impersonation_options={"token_lifetime_seconds": 2800},
)
with mock.patch.object(
external_account.Credentials, "__init__", return_value=None
) as mock_init:
credentials.with_quota_project("project-foo")
# Confirm with_quota_project initialized the credential with the
# expected parameters and quota project ID.
mock_init.assert_called_once_with(
audience=self.AUDIENCE,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
token_info_url=self.TOKEN_INFO_URL,
credential_source=self.CREDENTIAL_SOURCE,
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
service_account_impersonation_options={"token_lifetime_seconds": 2800},
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
quota_project_id="project-foo",
scopes=self.SCOPES,
default_scopes=["default1"],
universe_domain=DEFAULT_UNIVERSE_DOMAIN,
)
def test_info(self):
credentials = self.make_credentials(universe_domain="dummy_universe.com")
assert credentials.info == {
"type": "external_account",
"audience": self.AUDIENCE,
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"token_url": self.TOKEN_URL,
"credential_source": self.CREDENTIAL_SOURCE.copy(),
"universe_domain": "dummy_universe.com",
}
def test_universe_domain(self):
credentials = self.make_credentials(universe_domain="dummy_universe.com")
assert credentials.universe_domain == "dummy_universe.com"
credentials = self.make_credentials()
assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN
def test_with_universe_domain(self):
credentials = self.make_credentials()
new_credentials = credentials.with_universe_domain("dummy_universe.com")
assert new_credentials.universe_domain == "dummy_universe.com"
def test_info_workforce_pool(self):
credentials = self.make_workforce_pool_credentials(
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT
)
assert credentials.info == {
"type": "external_account",
"audience": self.WORKFORCE_AUDIENCE,
"subject_token_type": self.WORKFORCE_SUBJECT_TOKEN_TYPE,
"token_url": self.TOKEN_URL,
"credential_source": self.CREDENTIAL_SOURCE.copy(),
"workforce_pool_user_project": self.WORKFORCE_POOL_USER_PROJECT,
"universe_domain": DEFAULT_UNIVERSE_DOMAIN,
}
def test_info_with_full_options(self):
credentials = self.make_credentials(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
quota_project_id=self.QUOTA_PROJECT_ID,
token_info_url=self.TOKEN_INFO_URL,
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
service_account_impersonation_options={"token_lifetime_seconds": 2800},
)
assert credentials.info == {
"type": "external_account",
"audience": self.AUDIENCE,
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"token_url": self.TOKEN_URL,
"token_info_url": self.TOKEN_INFO_URL,
"service_account_impersonation_url": self.SERVICE_ACCOUNT_IMPERSONATION_URL,
"service_account_impersonation": {"token_lifetime_seconds": 2800},
"credential_source": self.CREDENTIAL_SOURCE.copy(),
"quota_project_id": self.QUOTA_PROJECT_ID,
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"universe_domain": DEFAULT_UNIVERSE_DOMAIN,
}
def test_service_account_email_without_impersonation(self):
credentials = self.make_credentials()
assert credentials.service_account_email is None
def test_service_account_email_with_impersonation(self):
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL
)
assert credentials.service_account_email == SERVICE_ACCOUNT_EMAIL
@pytest.mark.parametrize("audience", TEST_NON_USER_AUDIENCES)
def test_is_user_with_non_users(self, audience):
credentials = CredentialsImpl(
audience=audience,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
)
assert credentials.is_user is False
@pytest.mark.parametrize("audience", TEST_USER_AUDIENCES)
def test_is_user_with_users(self, audience):
credentials = CredentialsImpl(
audience=audience,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
)
assert credentials.is_user is True
@pytest.mark.parametrize("audience", TEST_USER_AUDIENCES)
def test_is_user_with_users_and_impersonation(self, audience):
# Initialize the credentials with service account impersonation.
credentials = CredentialsImpl(
audience=audience,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
)
# Even though the audience is for a workforce pool, since service account
# impersonation is used, the credentials will represent a service account and
# not a user.
assert credentials.is_user is False
@pytest.mark.parametrize("audience", TEST_NON_USER_AUDIENCES)
def test_is_workforce_pool_with_non_users(self, audience):
credentials = CredentialsImpl(
audience=audience,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
)
assert credentials.is_workforce_pool is False
@pytest.mark.parametrize("audience", TEST_USER_AUDIENCES)
def test_is_workforce_pool_with_users(self, audience):
credentials = CredentialsImpl(
audience=audience,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
)
assert credentials.is_workforce_pool is True
@pytest.mark.parametrize("audience", TEST_USER_AUDIENCES)
def test_is_workforce_pool_with_users_and_impersonation(self, audience):
# Initialize the credentials with workforce audience and service account
# impersonation.
credentials = CredentialsImpl(
audience=audience,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
)
# Even though impersonation is used, is_workforce_pool should still return True.
assert credentials.is_workforce_pool is True
@pytest.mark.parametrize("mock_expires_in", [2800, "2800"])
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
@mock.patch("google.auth._helpers.utcnow", return_value=datetime.datetime.min)
def test_refresh_without_client_auth_success(
self, unused_utcnow, mock_auth_lib_value, mock_expires_in
):
response = self.SUCCESS_RESPONSE.copy()
# Test custom expiration to confirm expiry is set correctly.
response["expires_in"] = mock_expires_in
expected_expiry = datetime.datetime.min + datetime.timedelta(
seconds=int(mock_expires_in)
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/false config-lifetime/false",
}
request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
}
request = self.make_mock_request(status=http_client.OK, data=response)
credentials = self.make_credentials()
credentials.refresh(request)
self.assert_token_request_kwargs(request.call_args[1], headers, request_data)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == response["access_token"]
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
@mock.patch("google.auth._helpers.utcnow", return_value=datetime.datetime.min)
@mock.patch(
"google.auth.external_account.Credentials._mtls_required", return_value=True
)
@mock.patch(
"google.auth.external_account.Credentials._get_mtls_cert_and_key_paths",
return_value=("path/to/cert.pem", "path/to/key.pem"),
)
def test_refresh_with_mtls(
self,
mock_get_mtls_cert_and_key_paths,
mock_mtls_required,
unused_utcnow,
mock_auth_lib_value,
):
response = self.SUCCESS_RESPONSE.copy()
# Test custom expiration to confirm expiry is set correctly.
response["expires_in"] = 2800
expected_expiry = datetime.datetime.min + datetime.timedelta(
seconds=response["expires_in"]
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/false config-lifetime/false",
}
request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
}
request = self.make_mock_request(status=http_client.OK, data=response)
credentials = self.make_credentials()
credentials.refresh(request)
expected_cert_path = ("path/to/cert.pem", "path/to/key.pem")
self.assert_token_request_kwargs(
request.call_args[1], headers, request_data, expected_cert_path
)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == response["access_token"]
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
@mock.patch("google.auth._helpers.utcnow", return_value=datetime.datetime.min)
def test_refresh_workforce_without_client_auth_success(
self, unused_utcnow, test_auth_lib_value
):
response = self.SUCCESS_RESPONSE.copy()
# Test custom expiration to confirm expiry is set correctly.
response["expires_in"] = 2800
expected_expiry = datetime.datetime.min + datetime.timedelta(
seconds=response["expires_in"]
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/false config-lifetime/false",
}
request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.WORKFORCE_AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.WORKFORCE_SUBJECT_TOKEN_TYPE,
"options": urllib.parse.quote(
json.dumps({"userProject": self.WORKFORCE_POOL_USER_PROJECT})
),
}
request = self.make_mock_request(status=http_client.OK, data=response)
credentials = self.make_workforce_pool_credentials(
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT
)
credentials.refresh(request)
self.assert_token_request_kwargs(request.call_args[1], headers, request_data)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == response["access_token"]
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
@mock.patch("google.auth._helpers.utcnow", return_value=datetime.datetime.min)
def test_refresh_workforce_with_client_auth_success(
self, unused_utcnow, mock_auth_lib_value
):
response = self.SUCCESS_RESPONSE.copy()
# Test custom expiration to confirm expiry is set correctly.
response["expires_in"] = 2800
expected_expiry = datetime.datetime.min + datetime.timedelta(
seconds=response["expires_in"]
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic {}".format(BASIC_AUTH_ENCODING),
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/false config-lifetime/false",
}
request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.WORKFORCE_AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.WORKFORCE_SUBJECT_TOKEN_TYPE,
}
request = self.make_mock_request(status=http_client.OK, data=response)
# Client Auth will have higher priority over workforce_pool_user_project.
credentials = self.make_workforce_pool_credentials(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT,
)
credentials.refresh(request)
self.assert_token_request_kwargs(request.call_args[1], headers, request_data)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == response["access_token"]
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
@mock.patch("google.auth._helpers.utcnow", return_value=datetime.datetime.min)
def test_refresh_workforce_with_client_auth_and_no_workforce_project_success(
self, unused_utcnow, mock_lib_version_value
):
response = self.SUCCESS_RESPONSE.copy()
# Test custom expiration to confirm expiry is set correctly.
response["expires_in"] = 2800
expected_expiry = datetime.datetime.min + datetime.timedelta(
seconds=response["expires_in"]
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic {}".format(BASIC_AUTH_ENCODING),
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/false config-lifetime/false",
}
request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.WORKFORCE_AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.WORKFORCE_SUBJECT_TOKEN_TYPE,
}
request = self.make_mock_request(status=http_client.OK, data=response)
# Client Auth will be sufficient for user project determination.
credentials = self.make_workforce_pool_credentials(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
workforce_pool_user_project=None,
)
credentials.refresh(request)
self.assert_token_request_kwargs(request.call_args[1], headers, request_data)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == response["access_token"]
@mock.patch(
"google.auth.metrics.token_request_access_token_impersonate",
return_value=IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
)
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_refresh_impersonation_without_client_auth_success(
self, mock_metrics_header_value, mock_auth_lib_value
):
# Simulate service account access token expires in 2800 seconds.
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=2800)
).isoformat("T") + "Z"
expected_expiry = datetime.datetime.strptime(expire_time, "%Y-%m-%dT%H:%M:%SZ")
# STS token exchange request/response.
token_response = self.SUCCESS_RESPONSE.copy()
token_headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/true config-lifetime/false",
}
token_request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"scope": "https://www.googleapis.com/auth/iam",
}
# Service account impersonation request/response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
impersonation_headers = {
"Content-Type": "application/json",
"authorization": "Bearer {}".format(token_response["access_token"]),
"x-goog-api-client": IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
"x-allowed-locations": "0x0",
}
impersonation_request_data = {
"delegates": None,
"scope": self.SCOPES,
"lifetime": "3600s",
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=token_response,
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
# Initialize credentials with service account impersonation.
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
scopes=self.SCOPES,
)
credentials.refresh(request)
# Only 2 requests should be processed.
assert len(request.call_args_list) == 2
# Verify token exchange request parameters.
self.assert_token_request_kwargs(
request.call_args_list[0][1], token_headers, token_request_data
)
# Verify service account impersonation request parameters.
self.assert_impersonation_request_kwargs(
request.call_args_list[1][1],
impersonation_headers,
impersonation_request_data,
)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == impersonation_response["accessToken"]
@mock.patch(
"google.auth.metrics.token_request_access_token_impersonate",
return_value=IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
)
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
@mock.patch(
"google.auth.external_account.Credentials._mtls_required", return_value=True
)
@mock.patch(
"google.auth.external_account.Credentials._get_mtls_cert_and_key_paths",
return_value=("path/to/cert.pem", "path/to/key.pem"),
)
def test_refresh_impersonation_with_mtls_success(
self,
mock_get_mtls_cert_and_key_paths,
mock_mtls_required,
mock_metrics_header_value,
mock_auth_lib_value,
):
# Simulate service account access token expires in 2800 seconds.
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=2800)
).isoformat("T") + "Z"
expected_expiry = datetime.datetime.strptime(expire_time, "%Y-%m-%dT%H:%M:%SZ")
# STS token exchange request/response.
token_response = self.SUCCESS_RESPONSE.copy()
token_headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/true config-lifetime/false",
}
token_request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"scope": "https://www.googleapis.com/auth/iam",
}
# Service account impersonation request/response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
impersonation_headers = {
"Content-Type": "application/json",
"authorization": "Bearer {}".format(token_response["access_token"]),
"x-goog-api-client": IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
"x-allowed-locations": "0x0",
}
impersonation_request_data = {
"delegates": None,
"scope": self.SCOPES,
"lifetime": "3600s",
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=token_response,
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
# Initialize credentials with service account impersonation.
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
scopes=self.SCOPES,
)
credentials.refresh(request)
# Only 2 requests should be processed.
assert len(request.call_args_list) == 2
# Verify token exchange request parameters.
expected_cert_paths = ("path/to/cert.pem", "path/to/key.pem")
self.assert_token_request_kwargs(
request.call_args_list[0][1],
token_headers,
token_request_data,
expected_cert_paths,
)
# Verify service account impersonation request parameters.
self.assert_impersonation_request_kwargs(
request.call_args_list[1][1],
impersonation_headers,
impersonation_request_data,
expected_cert_paths,
)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == impersonation_response["accessToken"]
@mock.patch(
"google.auth.metrics.token_request_access_token_impersonate",
return_value=IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
)
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_refresh_workforce_impersonation_without_client_auth_success(
self, mock_metrics_header_value, mock_auth_lib_value
):
# Simulate service account access token expires in 2800 seconds.
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=2800)
).isoformat("T") + "Z"
expected_expiry = datetime.datetime.strptime(expire_time, "%Y-%m-%dT%H:%M:%SZ")
# STS token exchange request/response.
token_response = self.SUCCESS_RESPONSE.copy()
token_headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/true config-lifetime/false",
}
token_request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.WORKFORCE_AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.WORKFORCE_SUBJECT_TOKEN_TYPE,
"scope": "https://www.googleapis.com/auth/iam",
"options": urllib.parse.quote(
json.dumps({"userProject": self.WORKFORCE_POOL_USER_PROJECT})
),
}
# Service account impersonation request/response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
impersonation_headers = {
"Content-Type": "application/json",
"authorization": "Bearer {}".format(token_response["access_token"]),
"x-goog-api-client": IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
"x-allowed-locations": "0x0",
}
impersonation_request_data = {
"delegates": None,
"scope": self.SCOPES,
"lifetime": "3600s",
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=token_response,
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
# Initialize credentials with service account impersonation.
credentials = self.make_workforce_pool_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
scopes=self.SCOPES,
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT,
)
credentials.refresh(request)
# Only 2 requests should be processed.
assert len(request.call_args_list) == 2
# Verify token exchange request parameters.
self.assert_token_request_kwargs(
request.call_args_list[0][1], token_headers, token_request_data
)
# Verify service account impersonation request parameters.
self.assert_impersonation_request_kwargs(
request.call_args_list[1][1],
impersonation_headers,
impersonation_request_data,
)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == impersonation_response["accessToken"]
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_refresh_without_client_auth_success_explicit_user_scopes_ignore_default_scopes(
self, mock_auth_lib_value
):
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/false config-lifetime/false",
}
request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"scope": "scope1 scope2",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
}
request = self.make_mock_request(
status=http_client.OK, data=self.SUCCESS_RESPONSE
)
credentials = self.make_credentials(
scopes=["scope1", "scope2"],
# Default scopes will be ignored in favor of user scopes.
default_scopes=["ignored"],
)
credentials.refresh(request)
self.assert_token_request_kwargs(request.call_args[1], headers, request_data)
assert credentials.valid
assert not credentials.expired
assert credentials.token == self.SUCCESS_RESPONSE["access_token"]
assert credentials.has_scopes(["scope1", "scope2"])
assert not credentials.has_scopes(["ignored"])
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_refresh_without_client_auth_success_explicit_default_scopes_only(
self, mock_auth_lib_value
):
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/false config-lifetime/false",
}
request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"scope": "scope1 scope2",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
}
request = self.make_mock_request(
status=http_client.OK, data=self.SUCCESS_RESPONSE
)
credentials = self.make_credentials(
scopes=None,
# Default scopes will be used since user scopes are none.
default_scopes=["scope1", "scope2"],
)
credentials.refresh(request)
self.assert_token_request_kwargs(request.call_args[1], headers, request_data)
assert credentials.valid
assert not credentials.expired
assert credentials.token == self.SUCCESS_RESPONSE["access_token"]
assert credentials.has_scopes(["scope1", "scope2"])
def test_refresh_without_client_auth_error(self):
request = self.make_mock_request(
status=http_client.BAD_REQUEST, data=self.ERROR_RESPONSE
)
credentials = self.make_credentials()
with pytest.raises(exceptions.OAuthError) as excinfo:
credentials.refresh(request)
assert excinfo.match(
r"Error code invalid_request: Invalid subject token - https://tools.ietf.org/html/rfc6749"
)
assert not credentials.expired
assert credentials.token is None
def test_refresh_impersonation_without_client_auth_error(self):
request = self.make_mock_request(
status=http_client.OK,
data=self.SUCCESS_RESPONSE,
impersonation_status=http_client.BAD_REQUEST,
impersonation_data=self.IMPERSONATION_ERROR_RESPONSE,
)
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
scopes=self.SCOPES,
)
with pytest.raises(exceptions.RefreshError) as excinfo:
credentials.refresh(request)
assert excinfo.match(r"Unable to acquire impersonated credentials")
assert not credentials.expired
assert credentials.token is None
def test_refresh_impersonation_invalid_impersonated_url_error(self):
credentials = self.make_credentials(
service_account_impersonation_url="https://iamcredentials.googleapis.com/v1/invalid",
scopes=self.SCOPES,
)
with pytest.raises(exceptions.RefreshError) as excinfo:
credentials.refresh(None)
assert excinfo.match(
r"Unable to determine target principal from service account impersonation URL."
)
assert not credentials.expired
assert credentials.token is None
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_refresh_with_client_auth_success(self, mock_auth_lib_value):
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic {}".format(BASIC_AUTH_ENCODING),
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/false config-lifetime/false",
}
request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
}
request = self.make_mock_request(
status=http_client.OK, data=self.SUCCESS_RESPONSE
)
credentials = self.make_credentials(
client_id=CLIENT_ID, client_secret=CLIENT_SECRET
)
credentials.refresh(request)
self.assert_token_request_kwargs(request.call_args[1], headers, request_data)
assert credentials.valid
assert not credentials.expired
assert credentials.token == self.SUCCESS_RESPONSE["access_token"]
@mock.patch(
"google.auth.metrics.token_request_access_token_impersonate",
return_value=IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
)
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_refresh_impersonation_with_client_auth_success_ignore_default_scopes(
self, mock_metrics_header_value, mock_auth_lib_value
):
# Simulate service account access token expires in 2800 seconds.
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=2800)
).isoformat("T") + "Z"
expected_expiry = datetime.datetime.strptime(expire_time, "%Y-%m-%dT%H:%M:%SZ")
# STS token exchange request/response.
token_response = self.SUCCESS_RESPONSE.copy()
token_headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic {}".format(BASIC_AUTH_ENCODING),
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/true config-lifetime/false",
}
token_request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"scope": "https://www.googleapis.com/auth/iam",
}
# Service account impersonation request/response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
impersonation_headers = {
"Content-Type": "application/json",
"authorization": "Bearer {}".format(token_response["access_token"]),
"x-goog-api-client": IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
"x-allowed-locations": "0x0",
}
impersonation_request_data = {
"delegates": None,
"scope": self.SCOPES,
"lifetime": "3600s",
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=token_response,
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
# Initialize credentials with service account impersonation and basic auth.
credentials = self.make_credentials(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
scopes=self.SCOPES,
# Default scopes will be ignored since user scopes are specified.
default_scopes=["ignored"],
)
credentials.refresh(request)
# Only 2 requests should be processed.
assert len(request.call_args_list) == 2
# Verify token exchange request parameters.
self.assert_token_request_kwargs(
request.call_args_list[0][1], token_headers, token_request_data
)
# Verify service account impersonation request parameters.
self.assert_impersonation_request_kwargs(
request.call_args_list[1][1],
impersonation_headers,
impersonation_request_data,
)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == impersonation_response["accessToken"]
@mock.patch(
"google.auth.metrics.token_request_access_token_impersonate",
return_value=IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
)
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_refresh_impersonation_with_client_auth_success_use_default_scopes(
self, mock_metrics_header_value, mock_auth_lib_value
):
# Simulate service account access token expires in 2800 seconds.
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=2800)
).isoformat("T") + "Z"
expected_expiry = datetime.datetime.strptime(expire_time, "%Y-%m-%dT%H:%M:%SZ")
# STS token exchange request/response.
token_response = self.SUCCESS_RESPONSE.copy()
token_headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic {}".format(BASIC_AUTH_ENCODING),
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/true config-lifetime/false",
}
token_request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"scope": "https://www.googleapis.com/auth/iam",
}
# Service account impersonation request/response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
impersonation_headers = {
"Content-Type": "application/json",
"authorization": "Bearer {}".format(token_response["access_token"]),
"x-goog-api-client": IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
"x-allowed-locations": "0x0",
}
impersonation_request_data = {
"delegates": None,
"scope": self.SCOPES,
"lifetime": "3600s",
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=token_response,
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
# Initialize credentials with service account impersonation and basic auth.
credentials = self.make_credentials(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
scopes=None,
# Default scopes will be used since user specified scopes are none.
default_scopes=self.SCOPES,
)
credentials.refresh(request)
# Only 2 requests should be processed.
assert len(request.call_args_list) == 2
# Verify token exchange request parameters.
self.assert_token_request_kwargs(
request.call_args_list[0][1], token_headers, token_request_data
)
# Verify service account impersonation request parameters.
self.assert_impersonation_request_kwargs(
request.call_args_list[1][1],
impersonation_headers,
impersonation_request_data,
)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == impersonation_response["accessToken"]
def test_apply_without_quota_project_id(self):
headers = {}
request = self.make_mock_request(
status=http_client.OK, data=self.SUCCESS_RESPONSE
)
credentials = self.make_credentials()
credentials.refresh(request)
credentials.apply(headers)
assert headers == {
"authorization": "Bearer {}".format(self.SUCCESS_RESPONSE["access_token"]),
"x-allowed-locations": "0x0",
}
def test_apply_workforce_without_quota_project_id(self):
headers = {}
request = self.make_mock_request(
status=http_client.OK, data=self.SUCCESS_RESPONSE
)
credentials = self.make_workforce_pool_credentials(
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT
)
credentials.refresh(request)
credentials.apply(headers)
assert headers == {
"authorization": "Bearer {}".format(self.SUCCESS_RESPONSE["access_token"]),
"x-allowed-locations": "0x0",
}
def test_apply_impersonation_without_quota_project_id(self):
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=3600)
).isoformat("T") + "Z"
# Service account impersonation response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=self.SUCCESS_RESPONSE.copy(),
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
# Initialize credentials with service account impersonation.
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
scopes=self.SCOPES,
)
headers = {}
credentials.refresh(request)
credentials.apply(headers)
assert headers == {
"authorization": "Bearer {}".format(impersonation_response["accessToken"]),
"x-allowed-locations": "0x0",
}
def test_apply_with_quota_project_id(self):
headers = {"other": "header-value"}
request = self.make_mock_request(
status=http_client.OK, data=self.SUCCESS_RESPONSE
)
credentials = self.make_credentials(quota_project_id=self.QUOTA_PROJECT_ID)
credentials.refresh(request)
credentials.apply(headers)
assert headers == {
"other": "header-value",
"authorization": "Bearer {}".format(self.SUCCESS_RESPONSE["access_token"]),
"x-goog-user-project": self.QUOTA_PROJECT_ID,
"x-allowed-locations": "0x0",
}
def test_apply_impersonation_with_quota_project_id(self):
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=3600)
).isoformat("T") + "Z"
# Service account impersonation response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=self.SUCCESS_RESPONSE.copy(),
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
# Initialize credentials with service account impersonation.
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
scopes=self.SCOPES,
quota_project_id=self.QUOTA_PROJECT_ID,
)
headers = {"other": "header-value"}
credentials.refresh(request)
credentials.apply(headers)
assert headers == {
"other": "header-value",
"authorization": "Bearer {}".format(impersonation_response["accessToken"]),
"x-goog-user-project": self.QUOTA_PROJECT_ID,
"x-allowed-locations": "0x0",
}
def test_before_request(self):
headers = {"other": "header-value"}
request = self.make_mock_request(
status=http_client.OK, data=self.SUCCESS_RESPONSE
)
credentials = self.make_credentials()
# First call should call refresh, setting the token.
credentials.before_request(request, "POST", "https://example.com/api", headers)
assert headers == {
"other": "header-value",
"authorization": "Bearer {}".format(self.SUCCESS_RESPONSE["access_token"]),
"x-allowed-locations": "0x0",
}
# Second call shouldn't call refresh.
credentials.before_request(request, "POST", "https://example.com/api", headers)
assert headers == {
"other": "header-value",
"authorization": "Bearer {}".format(self.SUCCESS_RESPONSE["access_token"]),
"x-allowed-locations": "0x0",
}
def test_before_request_workforce(self):
headers = {"other": "header-value"}
request = self.make_mock_request(
status=http_client.OK, data=self.SUCCESS_RESPONSE
)
credentials = self.make_workforce_pool_credentials(
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT
)
# First call should call refresh, setting the token.
credentials.before_request(request, "POST", "https://example.com/api", headers)
assert headers == {
"other": "header-value",
"authorization": "Bearer {}".format(self.SUCCESS_RESPONSE["access_token"]),
"x-allowed-locations": "0x0",
}
# Second call shouldn't call refresh.
credentials.before_request(request, "POST", "https://example.com/api", headers)
assert headers == {
"other": "header-value",
"authorization": "Bearer {}".format(self.SUCCESS_RESPONSE["access_token"]),
"x-allowed-locations": "0x0",
}
def test_before_request_impersonation(self):
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=3600)
).isoformat("T") + "Z"
# Service account impersonation response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=self.SUCCESS_RESPONSE.copy(),
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
headers = {"other": "header-value"}
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL
)
# First call should call refresh, setting the token.
credentials.before_request(request, "POST", "https://example.com/api", headers)
assert headers == {
"other": "header-value",
"authorization": "Bearer {}".format(impersonation_response["accessToken"]),
"x-allowed-locations": "0x0",
}
# Second call shouldn't call refresh.
credentials.before_request(request, "POST", "https://example.com/api", headers)
assert headers == {
"other": "header-value",
"authorization": "Bearer {}".format(impersonation_response["accessToken"]),
"x-allowed-locations": "0x0",
}
@mock.patch("google.auth._helpers.utcnow")
def test_before_request_expired(self, utcnow):
headers = {}
request = self.make_mock_request(
status=http_client.OK, data=self.SUCCESS_RESPONSE
)
credentials = self.make_credentials()
credentials.token = "token"
utcnow.return_value = datetime.datetime.min
# Set the expiration to one second more than now plus the clock skew
# accomodation. These credentials should be valid.
credentials.expiry = (
datetime.datetime.min
+ _helpers.REFRESH_THRESHOLD
+ datetime.timedelta(seconds=1)
)
assert credentials.valid
assert not credentials.expired
assert credentials.token_state == TokenState.FRESH
credentials.before_request(request, "POST", "https://example.com/api", headers)
# Cached token should be used.
assert headers == {
"authorization": "Bearer token",
"x-allowed-locations": "0x0",
}
# Next call should simulate 1 second passed.
utcnow.return_value = datetime.datetime.min + datetime.timedelta(seconds=1)
assert not credentials.valid
assert credentials.expired
assert credentials.token_state == TokenState.STALE
credentials.before_request(request, "POST", "https://example.com/api", headers)
assert credentials.token_state == TokenState.FRESH
# New token should be retrieved.
assert headers == {
"authorization": "Bearer {}".format(self.SUCCESS_RESPONSE["access_token"]),
"x-allowed-locations": "0x0",
}
@mock.patch("google.auth._helpers.utcnow")
def test_before_request_impersonation_expired(self, utcnow):
headers = {}
expire_time = (
datetime.datetime.min + datetime.timedelta(seconds=3601)
).isoformat("T") + "Z"
# Service account impersonation response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=self.SUCCESS_RESPONSE.copy(),
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL
)
credentials.token = "token"
utcnow.return_value = datetime.datetime.min
# Set the expiration to one second more than now plus the clock skew
# accomodation. These credentials should be valid.
credentials.expiry = (
datetime.datetime.min
+ _helpers.REFRESH_THRESHOLD
+ datetime.timedelta(seconds=1)
)
assert credentials.valid
assert not credentials.expired
assert credentials.token_state == TokenState.FRESH
credentials.before_request(request, "POST", "https://example.com/api", headers)
assert credentials.token_state == TokenState.FRESH
# Cached token should be used.
assert headers == {
"authorization": "Bearer token",
"x-allowed-locations": "0x0",
}
# Next call should simulate 1 second passed. This will trigger the expiration
# threshold.
utcnow.return_value = datetime.datetime.min + datetime.timedelta(seconds=1)
assert not credentials.valid
assert credentials.expired
assert credentials.token_state == TokenState.STALE
credentials.before_request(request, "POST", "https://example.com/api", headers)
assert credentials.token_state == TokenState.FRESH
credentials.before_request(request, "POST", "https://example.com/api", headers)
# New token should be retrieved.
assert headers == {
"authorization": "Bearer {}".format(impersonation_response["accessToken"]),
"x-allowed-locations": "0x0",
}
@pytest.mark.parametrize(
"audience",
[
# Legacy K8s audience format.
"identitynamespace:1f12345:my_provider",
# Unrealistic audiences.
"//iam.googleapis.com/projects",
"//iam.googleapis.com/projects/",
"//iam.googleapis.com/project/123456",
"//iam.googleapis.com/projects//123456",
"//iam.googleapis.com/prefix_projects/123456",
"//iam.googleapis.com/projects_suffix/123456",
],
)
def test_project_number_indeterminable(self, audience):
credentials = CredentialsImpl(
audience=audience,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
)
assert credentials.project_number is None
assert credentials.get_project_id(None) is None
def test_project_number_determinable(self):
credentials = CredentialsImpl(
audience=self.AUDIENCE,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
)
assert credentials.project_number == self.PROJECT_NUMBER
def test_project_number_workforce(self):
credentials = CredentialsImpl(
audience=self.WORKFORCE_AUDIENCE,
subject_token_type=self.WORKFORCE_SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT,
)
assert credentials.project_number is None
def test_project_id_without_scopes(self):
# Initialize credentials with no scopes.
credentials = CredentialsImpl(
audience=self.AUDIENCE,
subject_token_type=self.SUBJECT_TOKEN_TYPE,
token_url=self.TOKEN_URL,
credential_source=self.CREDENTIAL_SOURCE,
)
assert credentials.get_project_id(None) is None
@mock.patch(
"google.auth.metrics.token_request_access_token_impersonate",
return_value=IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
)
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_get_project_id_cloud_resource_manager_success(
self, mock_metrics_header_value, mock_auth_lib_value
):
# STS token exchange request/response.
token_response = self.SUCCESS_RESPONSE.copy()
token_headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/true config-lifetime/false",
}
token_request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"scope": "https://www.googleapis.com/auth/iam",
}
# Service account impersonation request/response.
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=3600)
).isoformat("T") + "Z"
expected_expiry = datetime.datetime.strptime(expire_time, "%Y-%m-%dT%H:%M:%SZ")
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
impersonation_headers = {
"Content-Type": "application/json",
"x-goog-user-project": self.QUOTA_PROJECT_ID,
"authorization": "Bearer {}".format(token_response["access_token"]),
"x-goog-api-client": IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
"x-allowed-locations": "0x0",
}
impersonation_request_data = {
"delegates": None,
"scope": self.SCOPES,
"lifetime": "3600s",
}
# Initialize mock request to handle token exchange, service account
# impersonation and cloud resource manager request.
request = self.make_mock_request(
status=http_client.OK,
data=self.SUCCESS_RESPONSE.copy(),
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
cloud_resource_manager_status=http_client.OK,
cloud_resource_manager_data=self.CLOUD_RESOURCE_MANAGER_SUCCESS_RESPONSE,
)
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
scopes=self.SCOPES,
quota_project_id=self.QUOTA_PROJECT_ID,
)
# Expected project ID from cloud resource manager response should be returned.
project_id = credentials.get_project_id(request)
assert project_id == self.PROJECT_ID
# 3 requests should be processed.
assert len(request.call_args_list) == 3
# Verify token exchange request parameters.
self.assert_token_request_kwargs(
request.call_args_list[0][1], token_headers, token_request_data
)
# Verify service account impersonation request parameters.
self.assert_impersonation_request_kwargs(
request.call_args_list[1][1],
impersonation_headers,
impersonation_request_data,
)
# In the process of getting project ID, an access token should be
# retrieved.
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == impersonation_response["accessToken"]
# Verify cloud resource manager request parameters.
self.assert_resource_manager_request_kwargs(
request.call_args_list[2][1],
self.PROJECT_NUMBER,
{
"x-goog-user-project": self.QUOTA_PROJECT_ID,
"authorization": "Bearer {}".format(
impersonation_response["accessToken"]
),
"x-allowed-locations": "0x0",
},
)
# Calling get_project_id again should return the cached project_id.
project_id = credentials.get_project_id(request)
assert project_id == self.PROJECT_ID
# No additional requests.
assert len(request.call_args_list) == 3
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_workforce_pool_get_project_id_cloud_resource_manager_success(
self, mock_auth_lib_value
):
# STS token exchange request/response.
token_headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/false config-lifetime/false",
}
token_request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.WORKFORCE_AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.WORKFORCE_SUBJECT_TOKEN_TYPE,
"scope": "scope1 scope2",
"options": urllib.parse.quote(
json.dumps({"userProject": self.WORKFORCE_POOL_USER_PROJECT})
),
}
# Initialize mock request to handle token exchange and cloud resource
# manager request.
request = self.make_mock_request(
status=http_client.OK,
data=self.SUCCESS_RESPONSE.copy(),
cloud_resource_manager_status=http_client.OK,
cloud_resource_manager_data=self.CLOUD_RESOURCE_MANAGER_SUCCESS_RESPONSE,
)
credentials = self.make_workforce_pool_credentials(
scopes=self.SCOPES,
quota_project_id=self.QUOTA_PROJECT_ID,
workforce_pool_user_project=self.WORKFORCE_POOL_USER_PROJECT,
)
# Expected project ID from cloud resource manager response should be returned.
project_id = credentials.get_project_id(request)
assert project_id == self.PROJECT_ID
# 2 requests should be processed.
assert len(request.call_args_list) == 2
# Verify token exchange request parameters.
self.assert_token_request_kwargs(
request.call_args_list[0][1], token_headers, token_request_data
)
# In the process of getting project ID, an access token should be
# retrieved.
assert credentials.valid
assert not credentials.expired
assert credentials.token == self.SUCCESS_RESPONSE["access_token"]
# Verify cloud resource manager request parameters.
self.assert_resource_manager_request_kwargs(
request.call_args_list[1][1],
self.WORKFORCE_POOL_USER_PROJECT,
{
"x-goog-user-project": self.QUOTA_PROJECT_ID,
"authorization": "Bearer {}".format(
self.SUCCESS_RESPONSE["access_token"]
),
"x-allowed-locations": "0x0",
},
)
# Calling get_project_id again should return the cached project_id.
project_id = credentials.get_project_id(request)
assert project_id == self.PROJECT_ID
# No additional requests.
assert len(request.call_args_list) == 2
@mock.patch(
"google.auth.metrics.token_request_access_token_impersonate",
return_value=IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
)
@mock.patch(
"google.auth.metrics.python_and_auth_lib_version",
return_value=LANG_LIBRARY_METRICS_HEADER_VALUE,
)
def test_refresh_impersonation_with_lifetime(
self, mock_metrics_header_value, mock_auth_lib_value
):
# Simulate service account access token expires in 2800 seconds.
expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=2800)
).isoformat("T") + "Z"
expected_expiry = datetime.datetime.strptime(expire_time, "%Y-%m-%dT%H:%M:%SZ")
# STS token exchange request/response.
token_response = self.SUCCESS_RESPONSE.copy()
token_headers = {
"Content-Type": "application/x-www-form-urlencoded",
"x-goog-api-client": "gl-python/3.7 auth/1.1 google-byoid-sdk sa-impersonation/true config-lifetime/true",
}
token_request_data = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"audience": self.AUDIENCE,
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"subject_token": "subject_token_0",
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"scope": "https://www.googleapis.com/auth/iam",
}
# Service account impersonation request/response.
impersonation_response = {
"accessToken": "SA_ACCESS_TOKEN",
"expireTime": expire_time,
}
impersonation_headers = {
"Content-Type": "application/json",
"authorization": "Bearer {}".format(token_response["access_token"]),
"x-goog-api-client": IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
"x-allowed-locations": "0x0",
}
impersonation_request_data = {
"delegates": None,
"scope": self.SCOPES,
"lifetime": "2800s",
}
# Initialize mock request to handle token exchange and service account
# impersonation request.
request = self.make_mock_request(
status=http_client.OK,
data=token_response,
impersonation_status=http_client.OK,
impersonation_data=impersonation_response,
)
# Initialize credentials with service account impersonation.
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL,
service_account_impersonation_options={"token_lifetime_seconds": 2800},
scopes=self.SCOPES,
)
credentials.refresh(request)
# Only 2 requests should be processed.
assert len(request.call_args_list) == 2
# Verify token exchange request parameters.
self.assert_token_request_kwargs(
request.call_args_list[0][1], token_headers, token_request_data
)
# Verify service account impersonation request parameters.
self.assert_impersonation_request_kwargs(
request.call_args_list[1][1],
impersonation_headers,
impersonation_request_data,
)
assert credentials.valid
assert credentials.expiry == expected_expiry
assert not credentials.expired
assert credentials.token == impersonation_response["accessToken"]
def test_get_project_id_cloud_resource_manager_error(self):
# Simulate resource doesn't have sufficient permissions to access
# cloud resource manager.
request = self.make_mock_request(
status=http_client.OK,
data=self.SUCCESS_RESPONSE.copy(),
cloud_resource_manager_status=http_client.UNAUTHORIZED,
)
credentials = self.make_credentials(scopes=self.SCOPES)
project_id = credentials.get_project_id(request)
assert project_id is None
# Only 2 requests to STS and cloud resource manager should be sent.
assert len(request.call_args_list) == 2
def test_supplier_context():
context = external_account.SupplierContext("TestTokenType", "TestAudience")
assert context.subject_token_type == "TestTokenType"
assert context.audience == "TestAudience"
|