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