-
Notifications
You must be signed in to change notification settings - Fork 37
feat: add Azure DevOps OIDC detector #301
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
cloudsmith_cli/core/credentials/oidc/detectors/azure_devops.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| # Copyright 2026 Cloudsmith Ltd | ||
| """Azure DevOps OIDC detector. | ||
|
|
||
| Fetches an OIDC token via the ``SYSTEM_OIDCREQUESTURI`` HTTP endpoint using | ||
| the pipeline's ``SYSTEM_ACCESSTOKEN`` for authorization. | ||
|
|
||
| The audience is not caller-configurable: Azure DevOps always mints the token | ||
| with a fixed audience (``api://AzureADTokenExchange``) and ignores any audience | ||
| supplied in the request, so the request is an empty POST (matching the Azure | ||
| SDK's AzurePipelinesCredential). | ||
|
|
||
| References: | ||
| https://learn.microsoft.com/en-us/azure/devops/release-notes/2024/sprint-240-update#pipelines-and-tasks-populate-variables-to-customize-workload-identity-federation-authentication | ||
| https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/azidentity/azure_pipelines_credential.go | ||
| https://docs.cloudsmith.com/integrations/integrating-with-azure-devops | ||
| https://cloudsmith.com/changelog/native-oidc-authentication-for-azure-devops | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
|
|
||
| from ....rest import create_requests_session as create_session | ||
| from .base import EnvironmentDetector | ||
|
|
||
| API_VERSION = "7.1" | ||
|
|
||
|
|
||
| class AzureDevOpsDetector(EnvironmentDetector): | ||
| """Detects Azure DevOps and fetches an OIDC token via HTTP POST.""" | ||
|
|
||
| name = "Azure DevOps" | ||
|
|
||
| def detect(self) -> bool: | ||
| return bool(os.environ.get("SYSTEM_OIDCREQUESTURI")) and bool( | ||
| os.environ.get("SYSTEM_ACCESSTOKEN") | ||
| ) | ||
|
|
||
| def get_token(self) -> str: | ||
| request_uri = os.environ["SYSTEM_OIDCREQUESTURI"] | ||
| access_token = os.environ["SYSTEM_ACCESSTOKEN"] | ||
|
|
||
| # The Azure DevOps OIDC endpoint rejects requests without an explicit | ||
| # api-version (HTTP 400), so it must always be supplied. | ||
| separator = "&" if "?" in request_uri else "?" | ||
| url = f"{request_uri}{separator}api-version={API_VERSION}" | ||
|
|
||
| session = self.context.session or create_session() | ||
| try: | ||
| response = session.post( | ||
| url, | ||
| headers={ | ||
| "Authorization": f"Bearer {access_token}", | ||
| "X-TFS-FedAuthRedirect": "Suppress", | ||
| }, | ||
| timeout=30, | ||
| ) | ||
| response.raise_for_status() | ||
|
|
||
| data = response.json() | ||
| token = data.get("oidcToken") | ||
| if not token: | ||
| raise ValueError( | ||
| "Azure DevOps OIDC response did not contain an oidcToken" | ||
| ) | ||
| return token | ||
| finally: | ||
| if not self.context.session: | ||
| session.close() | ||
125 changes: 125 additions & 0 deletions
125
cloudsmith_cli/core/tests/test_azure_devops_detector.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| """Tests for the Azure DevOps OIDC detector.""" | ||
|
|
||
| from unittest import mock | ||
|
|
||
| import pytest | ||
|
|
||
| from cloudsmith_cli.core.credentials.models import CredentialContext | ||
| from cloudsmith_cli.core.credentials.oidc.detectors import detect_environment | ||
| from cloudsmith_cli.core.credentials.oidc.detectors.azure_devops import ( | ||
| AzureDevOpsDetector, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def azure_env(): | ||
| env = { | ||
| "SYSTEM_OIDCREQUESTURI": "https://dev.azure.example/oidc/req", | ||
| "SYSTEM_ACCESSTOKEN": "access-token", | ||
| } | ||
| with mock.patch.dict("os.environ", env, clear=True): | ||
| yield env | ||
|
|
||
|
|
||
| class TestDetect: | ||
| def test_detects_when_all_env_vars_present(self, azure_env): | ||
| detector = AzureDevOpsDetector(context=CredentialContext()) | ||
| assert detector.detect() is True | ||
|
|
||
| def test_not_detected_when_unset(self): | ||
| with mock.patch.dict("os.environ", {}, clear=True): | ||
| detector = AzureDevOpsDetector(context=CredentialContext()) | ||
| assert detector.detect() is False | ||
|
|
||
| def test_not_detected_without_request_uri(self, azure_env): | ||
| del azure_env["SYSTEM_OIDCREQUESTURI"] | ||
| with mock.patch.dict("os.environ", azure_env, clear=True): | ||
| detector = AzureDevOpsDetector(context=CredentialContext()) | ||
| assert detector.detect() is False | ||
|
|
||
| def test_not_detected_without_access_token(self, azure_env): | ||
| del azure_env["SYSTEM_ACCESSTOKEN"] | ||
| with mock.patch.dict("os.environ", azure_env, clear=True): | ||
| detector = AzureDevOpsDetector(context=CredentialContext()) | ||
| assert detector.detect() is False | ||
|
|
||
|
|
||
| class TestGetToken: | ||
| def _mock_session(self, json_data): | ||
| response = mock.Mock() | ||
| response.json.return_value = json_data | ||
| response.raise_for_status = mock.Mock() | ||
| session = mock.Mock() | ||
| session.post.return_value = response | ||
| return session, response | ||
|
|
||
| def test_returns_token_from_response(self, azure_env): | ||
| session, _ = self._mock_session({"oidcToken": "the-jwt"}) | ||
| context = CredentialContext(session=session) | ||
| detector = AzureDevOpsDetector(context=context) | ||
|
|
||
| token = detector.get_token() | ||
|
|
||
| assert token == "the-jwt" | ||
|
|
||
| def test_posts_empty_body_with_api_version_and_auth_header(self, azure_env): | ||
| session, response = self._mock_session({"oidcToken": "the-jwt"}) | ||
| context = CredentialContext(session=session) | ||
| detector = AzureDevOpsDetector(context=context) | ||
|
|
||
| detector.get_token() | ||
|
|
||
| called_url = session.post.call_args[0][0] | ||
| assert called_url == "https://dev.azure.example/oidc/req?api-version=7.1" | ||
| kwargs = session.post.call_args[1] | ||
| # Azure DevOps ignores any requested audience and mints a token with a | ||
| # fixed audience, so no body is sent (matching the Azure SDK). | ||
| assert kwargs.get("json") is None | ||
| assert kwargs.get("data") is None | ||
| assert kwargs["headers"]["Authorization"] == "Bearer access-token" | ||
| assert kwargs["headers"]["X-TFS-FedAuthRedirect"] == "Suppress" | ||
| response.raise_for_status.assert_called_once() | ||
|
|
||
| def test_appends_api_version_with_ampersand_when_query_present(self, azure_env): | ||
| azure_env["SYSTEM_OIDCREQUESTURI"] = ( | ||
| "https://dev.azure.example/oidc/req?foo=bar" | ||
| ) | ||
| with mock.patch.dict("os.environ", azure_env, clear=True): | ||
| session, _ = self._mock_session({"oidcToken": "the-jwt"}) | ||
| context = CredentialContext(session=session) | ||
| detector = AzureDevOpsDetector(context=context) | ||
|
|
||
| detector.get_token() | ||
|
|
||
| called_url = session.post.call_args[0][0] | ||
| assert ( | ||
| called_url | ||
| == "https://dev.azure.example/oidc/req?foo=bar&api-version=7.1" | ||
| ) | ||
|
|
||
| def test_custom_audience_is_ignored(self, azure_env): | ||
| # Azure DevOps does not support a caller-supplied audience, so even a | ||
| # custom oidc_audience must not add a request body. | ||
| session, _ = self._mock_session({"oidcToken": "the-jwt"}) | ||
| context = CredentialContext(session=session, oidc_audience="my-aud") | ||
| detector = AzureDevOpsDetector(context=context) | ||
|
|
||
| detector.get_token() | ||
|
|
||
| kwargs = session.post.call_args[1] | ||
| assert kwargs.get("json") is None | ||
| assert kwargs.get("data") is None | ||
|
|
||
| def test_raises_when_token_missing(self, azure_env): | ||
| session, _ = self._mock_session({}) | ||
| context = CredentialContext(session=session) | ||
| detector = AzureDevOpsDetector(context=context) | ||
|
|
||
| with pytest.raises(ValueError): | ||
| detector.get_token() | ||
|
|
||
|
|
||
| class TestIntegration: | ||
| def test_detect_environment_selects_azure_devops(self, azure_env): | ||
| detector = detect_environment(CredentialContext()) | ||
| assert isinstance(detector, AzureDevOpsDetector) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.