|
| 1 | +# ------------------------------------ |
| 2 | +# Copyright (c) Microsoft Corporation. |
| 3 | +# Licensed under the MIT License. |
| 4 | +# ------------------------------------ |
| 5 | +# cspell:ignore teamprojectid, planid, jobid, oidctoken |
| 6 | +import os |
| 7 | +from typing import Any, Optional |
| 8 | + |
| 9 | +from azure.core.exceptions import ClientAuthenticationError |
| 10 | +from azure.core.credentials import AccessToken |
| 11 | +from azure.core.rest import HttpRequest, HttpResponse |
| 12 | + |
| 13 | +from .client_assertion import ClientAssertionCredential |
| 14 | +from .. import CredentialUnavailableError |
| 15 | +from .._internal import validate_tenant_id |
| 16 | +from .._internal.pipeline import build_pipeline |
| 17 | +from .._constants import EnvironmentVariables as ev |
| 18 | + |
| 19 | + |
| 20 | +AZURE_PIPELINES_VARS = ( |
| 21 | + ev.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI, |
| 22 | + ev.SYSTEM_TEAMPROJECTID, |
| 23 | + ev.SYSTEM_PLANID, |
| 24 | + ev.SYSTEM_JOBID, |
| 25 | + ev.SYSTEM_ACCESSTOKEN, |
| 26 | + ev.SYSTEM_HOSTTYPE, |
| 27 | +) |
| 28 | +OIDC_API_VERSION = "7.1-preview.1" |
| 29 | + |
| 30 | + |
| 31 | +def build_oidc_request(service_connection_id: str) -> HttpRequest: |
| 32 | + base_uri = os.environ[ev.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI].rstrip("/") |
| 33 | + url = ( |
| 34 | + f"{base_uri}/{os.environ[ev.SYSTEM_TEAMPROJECTID]}/_apis/distributedtask/hubs/" |
| 35 | + f"{os.environ[ev.SYSTEM_HOSTTYPE]}/plans/{os.environ[ev.SYSTEM_PLANID]}/jobs/{os.environ[ev.SYSTEM_JOBID]}/" |
| 36 | + f"oidctoken?api-version={OIDC_API_VERSION}&serviceConnectionId={service_connection_id}" |
| 37 | + ) |
| 38 | + access_token = os.environ[ev.SYSTEM_ACCESSTOKEN] |
| 39 | + headers = {"Content-Type": "application/json", "Authorization": f"Bearer {access_token}"} |
| 40 | + return HttpRequest("POST", url, headers=headers) |
| 41 | + |
| 42 | + |
| 43 | +def validate_env_vars(): |
| 44 | + missing_vars = [] |
| 45 | + for var in AZURE_PIPELINES_VARS: |
| 46 | + if var not in os.environ or not os.environ[var]: |
| 47 | + missing_vars.append(var) |
| 48 | + if missing_vars: |
| 49 | + raise CredentialUnavailableError( |
| 50 | + message=f"Missing values for environment variables: {', '.join(missing_vars)}. " |
| 51 | + f"AzurePipelinesCredential is intended for use in Azure Pipelines where the following environment " |
| 52 | + f"variables are set: {AZURE_PIPELINES_VARS}." |
| 53 | + ) |
| 54 | + |
| 55 | + |
| 56 | +class AzurePipelinesCredential: |
| 57 | + """Authenticates using Microsoft Entra Workload ID in Azure Pipelines. |
| 58 | +
|
| 59 | + This credential enables authentication in Azure Pipelines using workload identity federation for Azure service |
| 60 | + connections. |
| 61 | +
|
| 62 | + :keyword str service_connection_id: The service connection ID, as found in the querystring's resourceId key. |
| 63 | + Required. |
| 64 | + :keyword str tenant_id: ID of the application's Microsoft Entra tenant. Also called its "directory" ID. |
| 65 | + :keyword str client_id: The client ID of a Microsoft Entra app registration. |
| 66 | + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" |
| 67 | + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to |
| 68 | + acquire tokens for any tenant the application can access. |
| 69 | +
|
| 70 | + .. admonition:: Example: |
| 71 | +
|
| 72 | + .. literalinclude:: ../samples/credential_creation_code_snippets.py |
| 73 | + :start-after: [START create_azure_pipelines_credential] |
| 74 | + :end-before: [END create_azure_pipelines_credential] |
| 75 | + :language: python |
| 76 | + :dedent: 4 |
| 77 | + :caption: Create an AzurePipelinesCredential. |
| 78 | + """ |
| 79 | + |
| 80 | + def __init__( |
| 81 | + self, |
| 82 | + *, |
| 83 | + tenant_id: str, |
| 84 | + client_id: str, |
| 85 | + service_connection_id: str, |
| 86 | + **kwargs: Any, |
| 87 | + ) -> None: |
| 88 | + |
| 89 | + if not tenant_id or not client_id or not service_connection_id: |
| 90 | + raise ValueError("tenant_id, client_id, and service_connection_id are required.") |
| 91 | + validate_tenant_id(tenant_id) |
| 92 | + |
| 93 | + self._service_connection_id = service_connection_id |
| 94 | + self._client_assertion_credential = ClientAssertionCredential( |
| 95 | + tenant_id=tenant_id, client_id=client_id, func=self._get_oidc_token, **kwargs |
| 96 | + ) |
| 97 | + self._pipeline = build_pipeline(**kwargs) |
| 98 | + self._env_validated = False |
| 99 | + |
| 100 | + def get_token( |
| 101 | + self, |
| 102 | + *scopes: str, |
| 103 | + claims: Optional[str] = None, |
| 104 | + tenant_id: Optional[str] = None, |
| 105 | + enable_cae: bool = False, |
| 106 | + **kwargs: Any, |
| 107 | + ) -> AccessToken: |
| 108 | + """Request an access token for `scopes`. |
| 109 | +
|
| 110 | + This method is called automatically by Azure SDK clients. |
| 111 | +
|
| 112 | + :param str scopes: desired scopes for the access token. This method requires at least one scope. |
| 113 | + For more information about scopes, see |
| 114 | + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. |
| 115 | + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's |
| 116 | + claims challenge following an authorization failure. |
| 117 | + :keyword str tenant_id: optional tenant to include in the token request. |
| 118 | + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested |
| 119 | + token. Defaults to False. |
| 120 | +
|
| 121 | + :return: An access token with the desired scopes. |
| 122 | + :rtype: ~azure.core.credentials.AccessToken |
| 123 | + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks |
| 124 | + required data, state, or platform support |
| 125 | + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` |
| 126 | + attribute gives a reason. |
| 127 | + """ |
| 128 | + if not self._env_validated: |
| 129 | + validate_env_vars() |
| 130 | + self._env_validated = True |
| 131 | + return self._client_assertion_credential.get_token( |
| 132 | + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs |
| 133 | + ) |
| 134 | + |
| 135 | + def _get_oidc_token(self) -> str: |
| 136 | + request = build_oidc_request(self._service_connection_id) |
| 137 | + response = self._pipeline.run(request, retry_on_methods=[request.method]) |
| 138 | + http_response: HttpResponse = response.http_response |
| 139 | + if http_response.status_code not in [200]: |
| 140 | + raise ClientAuthenticationError( |
| 141 | + message="Unexpected response from OIDC token endpoint.", response=http_response |
| 142 | + ) |
| 143 | + json_response = http_response.json() |
| 144 | + if "oidcToken" not in json_response: |
| 145 | + raise ClientAuthenticationError(message="OIDC token not found in response.") |
| 146 | + return json_response["oidcToken"] |
| 147 | + |
| 148 | + def __enter__(self): |
| 149 | + self._client_assertion_credential.__enter__() |
| 150 | + self._pipeline.__enter__() |
| 151 | + return self |
| 152 | + |
| 153 | + def __exit__(self, *args): |
| 154 | + self._client_assertion_credential.__exit__(*args) |
| 155 | + self._pipeline.__exit__(*args) |
| 156 | + |
| 157 | + def close(self) -> None: |
| 158 | + """Close the credential's transport session.""" |
| 159 | + self.__exit__() |
0 commit comments