|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Text.Json; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Azure.Core; |
| 9 | +using Azure.Core.Pipeline; |
| 10 | +using Microsoft.Identity.Client; |
| 11 | + |
| 12 | +namespace Azure.Identity |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Credential which authenticates using an Azure Pipelines service connection. |
| 16 | + /// </summary> |
| 17 | + public class AzurePipelinesCredential : TokenCredential |
| 18 | + { |
| 19 | + internal readonly string[] AdditionallyAllowedTenantIds; |
| 20 | + internal string TenantId { get; } |
| 21 | + internal string ClientId { get; } |
| 22 | + internal MsalConfidentialClient Client { get; } |
| 23 | + internal CredentialPipeline Pipeline { get; } |
| 24 | + internal TenantIdResolverBase TenantIdResolver { get; } |
| 25 | + private const string OIDC_API_VERSION = "7.1"; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Protected constructor for mocking. |
| 29 | + /// </summary> |
| 30 | + protected AzurePipelinesCredential() |
| 31 | + { } |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Creates a new instance of the <see cref="AzurePipelinesCredential"/>. |
| 35 | + /// </summary> |
| 36 | + /// <param name="tenantId">The tenant ID for the service connection.</param> |
| 37 | + /// <param name="clientId">The client ID for the service connection.</param> |
| 38 | + /// <param name="serviceConnectionId">The service connection ID, as found in the querystring's resourceId key.</param> |
| 39 | + /// <param name="options">An instance of <see cref="AzurePipelinesCredentialOptions"/>.</param> |
| 40 | + /// <exception cref="System.ArgumentNullException">When <paramref name="tenantId"/>, <paramref name="clientId"/>, or <paramref name="serviceConnectionId"/> is null.</exception> |
| 41 | + public AzurePipelinesCredential(string tenantId, string clientId, string serviceConnectionId, AzurePipelinesCredentialOptions options = default) |
| 42 | + { |
| 43 | + Argument.AssertNotNull(serviceConnectionId, nameof(serviceConnectionId)); |
| 44 | + Argument.AssertNotNull(clientId, nameof(clientId)); |
| 45 | + Argument.AssertNotNull(tenantId, nameof(tenantId)); |
| 46 | + |
| 47 | + TenantId = Validations.ValidateTenantId(tenantId, nameof(tenantId)); |
| 48 | + ClientId = clientId; |
| 49 | + Pipeline = options?.Pipeline ?? CredentialPipeline.GetInstance(options); |
| 50 | + |
| 51 | + Func<CancellationToken, Task<string>> _assertionCallback = async (cancellationToken) => |
| 52 | + { |
| 53 | + var message = CreateOidcRequestMessage(serviceConnectionId, options ?? new AzurePipelinesCredentialOptions()); |
| 54 | + await Pipeline.HttpPipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); |
| 55 | + return GetOidcTokenResponse(message); |
| 56 | + }; |
| 57 | + |
| 58 | + Client = options?.MsalClient ?? new MsalConfidentialClient(Pipeline, tenantId, clientId, _assertionCallback, options); |
| 59 | + TenantIdResolver = options?.TenantIdResolver ?? TenantIdResolverBase.Default; |
| 60 | + AdditionallyAllowedTenantIds = TenantIdResolver.ResolveAddionallyAllowedTenantIds((options as ISupportsAdditionallyAllowedTenants)?.AdditionallyAllowedTenants); |
| 61 | + } |
| 62 | + |
| 63 | + /// <inheritdoc /> |
| 64 | + public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) |
| 65 | + => GetTokenCoreAsync(false, requestContext, cancellationToken).EnsureCompleted(); |
| 66 | + |
| 67 | + /// <inheritdoc /> |
| 68 | + public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) |
| 69 | + => await GetTokenCoreAsync(true, requestContext, cancellationToken).ConfigureAwait(false); |
| 70 | + |
| 71 | + internal async ValueTask<AccessToken> GetTokenCoreAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken) |
| 72 | + { |
| 73 | + using CredentialDiagnosticScope scope = Pipeline.StartGetTokenScope("AzurePipelinesCredential.GetToken", requestContext); |
| 74 | + |
| 75 | + try |
| 76 | + { |
| 77 | + var tenantId = TenantIdResolver.Resolve(TenantId, requestContext, AdditionallyAllowedTenantIds); |
| 78 | + |
| 79 | + AuthenticationResult result = await Client.AcquireTokenForClientAsync(requestContext.Scopes, tenantId, requestContext.Claims, requestContext.IsCaeEnabled, async, cancellationToken).ConfigureAwait(false); |
| 80 | + |
| 81 | + return scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)); |
| 82 | + } |
| 83 | + catch (Exception e) |
| 84 | + { |
| 85 | + throw scope.FailWrapAndThrow(e); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + internal HttpMessage CreateOidcRequestMessage(string serviceConnectionId, AzurePipelinesCredentialOptions options) |
| 90 | + { |
| 91 | + string CollectionUri = options.CollectionUri ?? throw new CredentialUnavailableException("AzurePipelinesCredential is not available: environment variable SYSTEM_TEAMFOUNDATIONCOLLECTIONURI is not set."); |
| 92 | + string projectId = options.TeamProjectId ?? throw new CredentialUnavailableException("AzurePipelinesCredential is not available: environment variable SYSTEM_TEAMPROJECTID is not set."); |
| 93 | + string planId = options.PlanId ?? throw new CredentialUnavailableException("AzurePipelinesCredential is not available: environment variable SYSTEM_PLANID is not set."); |
| 94 | + string jobId = options.JobId ?? throw new CredentialUnavailableException("AzurePipelinesCredential is not available: environment variable SYSTEM_JOBID is not set."); |
| 95 | + string systemToken = options.SystemAccessToken ?? throw new CredentialUnavailableException("AzurePipelinesCredential is not available: environment variable SYSTEM_ACCESSTOKEN is not set."); |
| 96 | + |
| 97 | + var message = Pipeline.HttpPipeline.CreateMessage(); |
| 98 | + |
| 99 | + var requestUri = new Uri($"{CollectionUri}{projectId}/_apis/distributedtask/hubs/build/plans/{planId}/jobs/{jobId}/oidctoken?api-version={OIDC_API_VERSION}&serviceConnectionId={serviceConnectionId}"); |
| 100 | + message.Request.Uri.Reset(requestUri); |
| 101 | + message.Request.Headers.SetValue(HttpHeader.Names.Authorization, $"Bearer {systemToken}"); |
| 102 | + message.Request.Headers.SetValue(HttpHeader.Names.ContentType, "application/json"); |
| 103 | + return message; |
| 104 | + } |
| 105 | + |
| 106 | + internal string GetOidcTokenResponse(HttpMessage message) |
| 107 | + { |
| 108 | + Utf8JsonReader reader = new Utf8JsonReader(message.Response.Content); |
| 109 | + string oidcToken = null; |
| 110 | + while (oidcToken is null && reader.Read()) |
| 111 | + { |
| 112 | + if (reader.TokenType == JsonTokenType.PropertyName) |
| 113 | + { |
| 114 | + switch (reader.GetString()) |
| 115 | + { |
| 116 | + case "oidcToken": |
| 117 | + reader.Read(); |
| 118 | + oidcToken = reader.GetString(); |
| 119 | + break; |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + return oidcToken ?? throw new AuthenticationFailedException("OIDC token not found in response."); |
| 124 | + } |
| 125 | + } |
| 126 | +} |
0 commit comments