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
|
# Copyright 2022 The Sigstore Authors
#
# 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 json
from pathlib import Path
import pretend
import pytest
from id import detect_credential
from id._internal.oidc import ambient
HERE = Path(__file__).parent
# example from Github Actions (audience of the token is "sigstore")
_GHA_TOKEN = (HERE / "gha_token.txt").read_text().strip()
# request URL example from Github Actions: note the query params already in the URL
_GHA_TOKEN_REQUEST_URL = "https://run-actions-3-azure-eastus.actions.githubusercontent.com/64//idtoken/918f5315-f823-4b74-ae16-8fc423e48661/0b77e920-7dce-5419-aca2-996d3c2116b7?api-version=2.0"
def test_detect_credential_none(monkeypatch):
detect_none = pretend.call_recorder(lambda audience: None)
monkeypatch.setattr(ambient, "detect_github", detect_none)
monkeypatch.setattr(ambient, "detect_gcp", detect_none)
monkeypatch.setattr(ambient, "detect_buildkite", detect_none)
assert detect_credential("some-audience") is None
def test_detect_credential(monkeypatch):
detect_github = pretend.call_recorder(lambda audience: _GHA_TOKEN)
monkeypatch.setattr(ambient, "detect_github", detect_github)
assert detect_credential("sigstore") == _GHA_TOKEN
def test_detect_credential_audience_mismatch(monkeypatch):
detect_github = pretend.call_recorder(lambda audience: _GHA_TOKEN)
monkeypatch.setattr(ambient, "detect_github", detect_github)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"Token audience claim mismatch \(expected my-audience, got sigstore\)",
):
detect_credential("my-audience")
def test_detect_credential_malformed_token(monkeypatch):
detect_github = pretend.call_recorder(lambda audience: "header.payload.sig")
monkeypatch.setattr(ambient, "detect_github", detect_github)
with pytest.raises(
ambient.AmbientCredentialError,
match="Malformed token",
):
detect_credential("my-audience")
def test_detect_github_bad_env(monkeypatch):
# We might actually be running in a CI, so explicitly remove this.
monkeypatch.delenv("GITHUB_ACTIONS", raising=False)
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
assert ambient.detect_github("some-audience") is None
assert logger.debug.calls == [
pretend.call("GitHub: looking for OIDC credentials"),
pretend.call("GitHub: environment doesn't look like a GH action; giving up"),
]
def test_detect_github_bad_request_token(monkeypatch):
monkeypatch.setenv("GITHUB_ACTIONS", "true")
monkeypatch.delenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", raising=False)
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", _GHA_TOKEN_REQUEST_URL)
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
with pytest.raises(
ambient.AmbientCredentialError,
match="GitHub: missing or insufficient OIDC token permissions?",
):
ambient.detect_github("some-audience")
assert logger.debug.calls == [
pretend.call("GitHub: looking for OIDC credentials"),
]
def test_detect_github_bad_request_url(monkeypatch):
monkeypatch.setenv("GITHUB_ACTIONS", "true")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "faketoken")
monkeypatch.delenv("ACTIONS_ID_TOKEN_REQUEST_URL", raising=False)
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
with pytest.raises(
ambient.AmbientCredentialError,
match="GitHub: missing or insufficient OIDC token permissions?",
):
ambient.detect_github("some-audience")
assert logger.debug.calls == [
pretend.call("GitHub: looking for OIDC credentials"),
]
def test_detect_github_request_fails(monkeypatch):
monkeypatch.setenv("GITHUB_ACTIONS", "true")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "faketoken")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", _GHA_TOKEN_REQUEST_URL)
resp = pretend.stub(
status=999,
data=b"something",
)
u3 = pretend.stub(request=pretend.call_recorder(lambda meth, url, **kw: resp))
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GitHub: OIDC token request failed \(code=999, body='something'\)",
):
ambient.detect_github("some-audience")
assert u3.request.calls == [
pretend.call(
"GET",
f"{_GHA_TOKEN_REQUEST_URL}&audience=some-audience",
fields=None,
headers={"Authorization": "bearer faketoken"},
timeout=30,
)
]
def test_detect_github_request_timeout(monkeypatch):
monkeypatch.setenv("GITHUB_ACTIONS", "true")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "faketoken")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", _GHA_TOKEN_REQUEST_URL)
u3 = pretend.stub(
request=pretend.raiser(ValueError), exceptions=pretend.stub(MaxRetryError=ValueError)
)
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GitHub: OIDC token request timed out",
):
ambient.detect_github("some-audience")
def test_detect_github_invalid_json_payload(monkeypatch):
monkeypatch.setenv("GITHUB_ACTIONS", "true")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "faketoken")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", _GHA_TOKEN_REQUEST_URL)
resp = pretend.stub(status=200, json=pretend.raiser(json.JSONDecodeError))
request = pretend.call_recorder(lambda meth, url, **kw: resp)
monkeypatch.setattr(ambient.urllib3, "request", request)
with pytest.raises(
ambient.AmbientCredentialError,
match="GitHub: malformed or incomplete JSON",
):
ambient.detect_github("some-audience")
assert request.calls == [
pretend.call(
"GET",
f"{_GHA_TOKEN_REQUEST_URL}&audience=some-audience",
fields=None,
headers={"Authorization": "bearer faketoken"},
timeout=30,
)
]
@pytest.mark.parametrize("payload", [{}, {"notvalue": None}, {"value": None}, {"value": 1234}])
def test_detect_github_bad_payload(monkeypatch, payload):
monkeypatch.setenv("GITHUB_ACTIONS", "true")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "faketoken")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", _GHA_TOKEN_REQUEST_URL)
resp = pretend.stub(status=200, json=pretend.call_recorder(lambda: payload))
u3 = pretend.stub(request=pretend.call_recorder(lambda meth, url, **kw: resp))
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match="GitHub: malformed or incomplete JSON",
):
ambient.detect_github("some-audience")
assert u3.request.calls == [
pretend.call(
"GET",
f"{_GHA_TOKEN_REQUEST_URL}&audience=some-audience",
fields=None,
headers={"Authorization": "bearer faketoken"},
timeout=30,
)
]
assert resp.json.calls == [pretend.call()]
def test_detect_github(monkeypatch):
monkeypatch.setenv("GITHUB_ACTIONS", "true")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "faketoken")
monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", _GHA_TOKEN_REQUEST_URL)
resp = pretend.stub(
status=200,
json=pretend.call_recorder(lambda: {"value": "fakejwt"}),
)
u3 = pretend.stub(request=pretend.call_recorder(lambda meth, url, **kw: resp))
monkeypatch.setattr(ambient, "urllib3", u3)
assert ambient.detect_github("some-audience") == "fakejwt"
assert u3.request.calls == [
pretend.call(
"GET",
f"{_GHA_TOKEN_REQUEST_URL}&audience=some-audience",
fields=None,
headers={"Authorization": "bearer faketoken"},
timeout=30,
)
]
assert resp.json.calls == [pretend.call()]
def test_gcp_impersonation_access_token_request_fail(monkeypatch):
monkeypatch.setenv("GOOGLE_SERVICE_ACCOUNT_NAME", "identity@project.iam.gserviceaccount.com")
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
resp = pretend.stub(status=999, data=b"something")
u3 = pretend.stub(request=pretend.call_recorder(lambda meth, url, **kw: resp))
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GCP: access token request failed \(code=999, body='something'\)",
):
ambient.detect_gcp("some-audience")
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME set; attempting impersonation"),
pretend.call("GCP: requesting access token"),
]
def test_gcp_impersonation_access_token_request_timeout(monkeypatch):
monkeypatch.setenv("GOOGLE_SERVICE_ACCOUNT_NAME", "identity@project.iam.gserviceaccount.com")
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
u3 = pretend.stub(
request=pretend.raiser(ValueError), exceptions=pretend.stub(MaxRetryError=ValueError)
)
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GCP: access token request timed out",
):
ambient.detect_gcp("some-audience")
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME set; attempting impersonation"),
pretend.call("GCP: requesting access token"),
]
def test_gcp_impersonation_access_token_missing(monkeypatch):
monkeypatch.setenv("GOOGLE_SERVICE_ACCOUNT_NAME", "identity@project.iam.gserviceaccount.com")
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
resp = pretend.stub(status=200, json=lambda: {})
u3 = pretend.stub(request=pretend.call_recorder(lambda meth, url, **kw: resp))
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GCP: access token missing from response",
):
ambient.detect_gcp("some-audience")
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME set; attempting impersonation"),
pretend.call("GCP: requesting access token"),
]
def test_gcp_impersonation_identity_token_request_fail(monkeypatch):
monkeypatch.setenv("GOOGLE_SERVICE_ACCOUNT_NAME", "identity@project.iam.gserviceaccount.com")
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
access_token = pretend.stub()
get_resp = pretend.stub(status=200, json=lambda: {"access_token": access_token})
post_resp = pretend.stub(
status=999,
data=b"something",
)
def _request(meth, *a, **kw):
if meth == "GET":
return get_resp
elif meth == "POST":
return post_resp
else:
assert False
u3 = pretend.stub(request=_request)
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GCP: OIDC token request failed \(code=999, body='something'\)",
):
ambient.detect_gcp("some-audience")
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME set; attempting impersonation"),
pretend.call("GCP: requesting access token"),
pretend.call("GCP: requesting OIDC token"),
]
def test_gcp_impersonation_identity_token_request_timeout(monkeypatch):
monkeypatch.setenv("GOOGLE_SERVICE_ACCOUNT_NAME", "identity@project.iam.gserviceaccount.com")
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
access_token = pretend.stub()
get_resp = pretend.stub(status=200, json=lambda: {"access_token": access_token})
def _request(meth, *a, **kw):
if meth == "GET":
return get_resp
elif meth == "POST":
raise ValueError
else:
assert False
u3 = pretend.stub(request=_request, exceptions=pretend.stub(MaxRetryError=ValueError))
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GCP: OIDC token request timed out",
):
ambient.detect_gcp("some-audience")
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME set; attempting impersonation"),
pretend.call("GCP: requesting access token"),
pretend.call("GCP: requesting OIDC token"),
]
def test_gcp_impersonation_identity_token_missing(monkeypatch):
monkeypatch.setenv("GOOGLE_SERVICE_ACCOUNT_NAME", "identity@project.iam.gserviceaccount.com")
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
access_token = pretend.stub()
get_resp = pretend.stub(status=200, json=lambda: {"access_token": access_token})
post_resp = pretend.stub(status=200, json=lambda: {})
def _request(meth, *a, **kw):
if meth == "GET":
return get_resp
elif meth == "POST":
return post_resp
else:
assert False
u3 = pretend.stub(request=_request)
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GCP: OIDC token missing from response",
):
ambient.detect_gcp("some-audience")
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME set; attempting impersonation"),
pretend.call("GCP: requesting access token"),
pretend.call("GCP: requesting OIDC token"),
]
def test_gcp_impersonation_succeeds(monkeypatch):
monkeypatch.setenv("GOOGLE_SERVICE_ACCOUNT_NAME", "identity@project.iam.gserviceaccount.com")
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
access_token = pretend.stub()
oidc_token = pretend.stub()
get_resp = pretend.stub(status=200, json=lambda: {"access_token": access_token})
post_resp = pretend.stub(status=200, json=lambda: {"token": oidc_token})
def _request(meth, *a, **kw):
if meth == "GET":
return get_resp
elif meth == "POST":
return post_resp
else:
assert False
u3 = pretend.stub(request=_request)
monkeypatch.setattr(ambient, "urllib3", u3)
assert ambient.detect_gcp("some-audience") == oidc_token
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME set; attempting impersonation"),
pretend.call("GCP: requesting access token"),
pretend.call("GCP: requesting OIDC token"),
pretend.call("GCP: successfully requested OIDC token"),
]
def test_gcp_bad_env(monkeypatch):
oserror = pretend.raiser(OSError)
monkeypatch.setattr(ambient, "_open", oserror) # type: ignore
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
assert ambient.detect_gcp("some-audience") is None
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME not set; skipping impersonation"),
pretend.call("GCP: environment doesn't have GCP product name file; giving up"),
]
def test_gcp_wrong_product(monkeypatch):
stub_file = pretend.stub(
__enter__=lambda *a: pretend.stub(read=lambda: "Unsupported Product"),
__exit__=lambda *a: None,
)
monkeypatch.setattr(ambient, "_open", lambda fn: stub_file) # type: ignore
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
assert ambient.detect_gcp("some-audience") is None
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME not set; skipping impersonation"),
pretend.call(
"GCP: product name file exists, but product name is 'Unsupported Product'; giving up"
),
]
def test_detect_gcp_request_fails(monkeypatch):
stub_file = pretend.stub(
__enter__=lambda *a: pretend.stub(read=lambda: "Google"),
__exit__=lambda *a: None,
)
monkeypatch.setattr(ambient, "_open", lambda fn: stub_file) # type: ignore
resp = pretend.stub(
status=999,
data=b"something",
)
u3 = pretend.stub(request=pretend.call_recorder(lambda meth, url, **kw: resp))
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GCP: OIDC token request failed \(code=999, body='something'\)",
):
ambient.detect_gcp("some-audience")
assert u3.request.calls == [
pretend.call(
"GET",
f"{ambient._GCP_IDENTITY_REQUEST_URL}?audience=some-audience&format=full",
fields=None,
headers={"Metadata-Flavor": "Google"},
timeout=30,
)
]
def test_detect_gcp_request_timeout(monkeypatch):
stub_file = pretend.stub(
__enter__=lambda *a: pretend.stub(read=lambda: "Google"),
__exit__=lambda *a: None,
)
monkeypatch.setattr(ambient, "_open", lambda fn: stub_file) # type: ignore
u3 = pretend.stub(
request=pretend.raiser(ValueError), exceptions=pretend.stub(MaxRetryError=ValueError)
)
monkeypatch.setattr(ambient, "urllib3", u3)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"GCP: OIDC token request timed out",
):
ambient.detect_gcp("some-audience")
@pytest.mark.parametrize("product_name", ("Google", "Google Compute Engine"))
def test_detect_gcp(monkeypatch, product_name):
stub_file = pretend.stub(
__enter__=lambda *a: pretend.stub(read=lambda: product_name),
__exit__=lambda *a: None,
)
monkeypatch.setattr(ambient, "_open", lambda fn: stub_file) # type: ignore
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
resp = pretend.stub(
status=200,
data=b"fakejwt",
)
u3 = pretend.stub(request=pretend.call_recorder(lambda meth, url, **kw: resp))
monkeypatch.setattr(ambient, "urllib3", u3)
assert ambient.detect_gcp("some-audience") == "fakejwt"
assert u3.request.calls == [
pretend.call(
"GET",
f"{ambient._GCP_IDENTITY_REQUEST_URL}?audience=some-audience&format=full",
fields=None,
headers={"Metadata-Flavor": "Google"},
timeout=30,
)
]
assert logger.debug.calls == [
pretend.call("GCP: looking for OIDC credentials"),
pretend.call("GCP: GOOGLE_SERVICE_ACCOUNT_NAME not set; skipping impersonation"),
pretend.call("GCP: requesting OIDC token"),
pretend.call("GCP: successfully requested OIDC token"),
]
def test_buildkite_no_agent(monkeypatch):
monkeypatch.setenv("BUILDKITE", "true")
# Mock out the `which` call. We don't expect this to exist in the `PATH` but
# just in case someone is running these tests on a Buildkite host...
shutil = pretend.stub(which=pretend.call_recorder(lambda bin: None))
monkeypatch.setattr(ambient, "shutil", shutil)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"Buildkite: could not find Buildkite agent in Buildkite environment",
):
ambient.detect_buildkite("some-audience")
assert shutil.which.calls == [pretend.call("buildkite-agent")]
def test_buildkite_agent_error(monkeypatch):
monkeypatch.setenv("BUILDKITE", "true")
# Mock out the `which` call to show that we have a `buildkite-agent` in our `PATH`.
shutil = pretend.stub(which=pretend.call_recorder(lambda bin: "/usr/bin/buildkite-agent"))
monkeypatch.setattr(ambient, "shutil", shutil)
# Mock out `run` call to emulate getting a non-zero return code from the `buildkite-agent`.
resp = pretend.stub(
returncode=-1,
stdout="mock error message",
)
subprocess = pretend.stub(run=pretend.call_recorder(lambda run_args, **kw: resp), PIPE=None)
monkeypatch.setattr(ambient, "subprocess", subprocess)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"Buildkite: the Buildkite agent encountered an error: mock error message",
):
ambient.detect_buildkite("some-audience")
assert shutil.which.calls == [pretend.call("buildkite-agent")]
assert subprocess.run.calls == [
pretend.call(
["buildkite-agent", "oidc", "request-token", "--audience", "some-audience"],
capture_output=True,
text=True,
)
]
def test_buildkite(monkeypatch):
monkeypatch.setenv("BUILDKITE", "true")
# Mock out the `which` call to show that we have a `buildkite-agent` in our `PATH`.
shutil = pretend.stub(which=pretend.call_recorder(lambda bin: "/usr/bin/buildkite-agent"))
monkeypatch.setattr(ambient, "shutil", shutil)
# Mock out `run` call to emulate getting a successful return code from the `buildkite-agent`.
resp = pretend.stub(
returncode=0,
stdout="fakejwt",
)
subprocess = pretend.stub(run=pretend.call_recorder(lambda run_args, **kw: resp), PIPE=None)
monkeypatch.setattr(ambient, "subprocess", subprocess)
assert ambient.detect_buildkite("some-audience") == "fakejwt"
assert shutil.which.calls == [pretend.call("buildkite-agent")]
assert subprocess.run.calls == [
pretend.call(
["buildkite-agent", "oidc", "request-token", "--audience", "some-audience"],
capture_output=True,
text=True,
)
]
def test_buildkite_bad_env(monkeypatch):
monkeypatch.delenv("BUILDKITE", False)
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
assert ambient.detect_buildkite("some-audience") is None
assert logger.debug.calls == [
pretend.call("Buildkite: looking for OIDC credentials"),
pretend.call("Buildkite: environment doesn't look like BuildKite; giving up"),
]
def test_gitlab_bad_env(monkeypatch):
monkeypatch.delenv("GITLAB_CI", False)
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
assert ambient.detect_gitlab("some-audience") is None
assert logger.debug.calls == [
pretend.call("GitLab: looking for OIDC credentials"),
pretend.call("GitLab: environment doesn't look like GitLab CI/CD; giving up"),
]
def test_gitlab_no_variable(monkeypatch):
monkeypatch.setenv("GITLAB_CI", "true")
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
with pytest.raises(
ambient.AmbientCredentialError,
match="GitLab: Environment variable SOME_AUDIENCE_ID_TOKEN not found",
):
ambient.detect_gitlab("some-audience")
assert logger.debug.calls == [
pretend.call("GitLab: looking for OIDC credentials"),
]
def test_gitlab(monkeypatch):
monkeypatch.setenv("GITLAB_CI", "true")
monkeypatch.setenv("SOME_AUDIENCE_ID_TOKEN", "fakejwt")
monkeypatch.setenv("_1_OTHER_AUDIENCE_ID_TOKEN", "fakejwt2")
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
assert ambient.detect_gitlab("some-audience") == "fakejwt"
assert ambient.detect_gitlab("11 other audience") == "fakejwt2"
assert logger.debug.calls == [
pretend.call("GitLab: looking for OIDC credentials"),
pretend.call("GitLab: Found token in environment variable SOME_AUDIENCE_ID_TOKEN"),
pretend.call("GitLab: looking for OIDC credentials"),
pretend.call("GitLab: Found token in environment variable _1_OTHER_AUDIENCE_ID_TOKEN"),
]
def test_circleci_bad_env(monkeypatch):
monkeypatch.delenv("CIRCLECI", False)
logger = pretend.stub(debug=pretend.call_recorder(lambda s: None))
monkeypatch.setattr(ambient, "logger", logger)
assert ambient.detect_circleci("some-audience") is None
assert logger.debug.calls == [
pretend.call("CircleCI: looking for OIDC credentials"),
pretend.call("CircleCI: environment doesn't look like CircleCI; giving up"),
]
def test_circleci_no_circleci_cli(monkeypatch):
monkeypatch.setenv("CIRCLECI", "true")
# Mock out the `which` call. We don't expect this to exist in the `PATH` but
# just in case someone is running these tests on a Buildkite host...
shutil = pretend.stub(which=pretend.call_recorder(lambda bin: None))
monkeypatch.setattr(ambient, "shutil", shutil)
with pytest.raises(
ambient.AmbientCredentialError,
match=r"CircleCI: could not find `circleci` in the environment",
):
ambient.detect_circleci("some-audience")
assert shutil.which.calls == [pretend.call("circleci")]
@pytest.mark.parametrize("root_issuer", [True, False])
def test_circleci_circlecli_error(monkeypatch, root_issuer):
monkeypatch.setenv("CIRCLECI", "true")
# Mock out the `which` call to show that we have a `circleci` in our `PATH`.
shutil = pretend.stub(which=pretend.call_recorder(lambda bin: "/usr/bin/circleci"))
monkeypatch.setattr(ambient, "shutil", shutil)
# Mock out `run` call to emulate getting a non-zero return code from the `circleci`.
resp = pretend.stub(
returncode=-1,
stderr="mock error message",
)
subprocess = pretend.stub(run=pretend.call_recorder(lambda run_args, **kw: resp), PIPE=None)
monkeypatch.setattr(ambient, "subprocess", subprocess)
payload = json.dumps({"aud": "some-audience"})
expected_cmd = ["circleci", "run", "oidc", "get", "--claims", payload]
if root_issuer:
expected_cmd.append("--root-issuer")
with pytest.raises(
ambient.AmbientCredentialError,
match=r"CircleCI: the `circleci` tool encountered an error: mock error message",
):
ambient.detect_circleci("some-audience", root_issuer)
assert shutil.which.calls == [pretend.call("circleci")]
assert subprocess.run.calls == [
pretend.call(
expected_cmd,
capture_output=True,
text=True,
)
]
@pytest.mark.parametrize("root_issuer", [True, False])
def test_circleci(monkeypatch, root_issuer):
monkeypatch.setenv("CIRCLECI", "true")
# Mock out the `which` call to show that we have a `circleci` in our `PATH`.
shutil = pretend.stub(which=pretend.call_recorder(lambda bin: "/usr/bin/circleci"))
monkeypatch.setattr(ambient, "shutil", shutil)
# Mock out `run` call to emulate getting a successful return code from the `circleci`.
resp = pretend.stub(
returncode=0,
stdout="fakejwt",
)
subprocess = pretend.stub(run=pretend.call_recorder(lambda run_args, **kw: resp), PIPE=None)
monkeypatch.setattr(ambient, "subprocess", subprocess)
payload = json.dumps({"aud": "some-audience"})
expected_cmd = ["circleci", "run", "oidc", "get", "--claims", payload]
if root_issuer:
expected_cmd.append("--root-issuer")
assert ambient.detect_circleci("some-audience", root_issuer) == "fakejwt"
assert shutil.which.calls == [pretend.call("circleci")]
assert subprocess.run.calls == [
pretend.call(
expected_cmd,
capture_output=True,
text=True,
)
]
|