| | | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | | 2 | | // Licensed under the MIT License. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Runtime.ExceptionServices; |
| | | 9 | | using System.Runtime.InteropServices; |
| | | 10 | | using System.Text; |
| | | 11 | | using System.Text.Json; |
| | | 12 | | using System.Threading; |
| | | 13 | | using System.Threading.Tasks; |
| | | 14 | | using Azure.Core; |
| | | 15 | | using Azure.Core.Pipeline; |
| | | 16 | | |
| | | 17 | | |
| | | 18 | | namespace Azure.Identity |
| | | 19 | | { |
| | | 20 | | /// <summary> |
| | | 21 | | /// Enables authentication to Azure Active Directory using data from Visual Studio |
| | | 22 | | /// </summary> |
| | | 23 | | public class VisualStudioCredential : TokenCredential |
| | | 24 | | { |
| | | 25 | | private const string TokenProviderFilePath = @".IdentityService\AzureServiceAuth\tokenprovider.json"; |
| | | 26 | | private const string ResourceArgumentName = "--resource"; |
| | | 27 | | private const string TenantArgumentName = "--tenant"; |
| | | 28 | | |
| | | 29 | | private readonly CredentialPipeline _pipeline; |
| | | 30 | | private readonly string _tenantId; |
| | | 31 | | private readonly IFileSystemService _fileSystem; |
| | | 32 | | private readonly IProcessService _processService; |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Creates a new instance of the <see cref="VisualStudioCredential"/>. |
| | | 36 | | /// </summary> |
| | 96 | 37 | | public VisualStudioCredential() : this(null) { } |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// Creates a new instance of the <see cref="VisualStudioCredential"/> with the specified options. |
| | | 41 | | /// </summary> |
| | | 42 | | /// <param name="options">Options for configuring the credential.</param> |
| | 96 | 43 | | public VisualStudioCredential(VisualStudioCredentialOptions options) : this(options?.TenantId, CredentialPipelin |
| | | 44 | | |
| | 130 | 45 | | internal VisualStudioCredential(string tenantId, CredentialPipeline pipeline, IFileSystemService fileSystem, IPr |
| | | 46 | | { |
| | 130 | 47 | | _tenantId = tenantId; |
| | 130 | 48 | | _pipeline = pipeline ?? CredentialPipeline.GetInstance(null); |
| | 130 | 49 | | _fileSystem = fileSystem ?? FileSystemService.Default; |
| | 130 | 50 | | _processService = processService ?? ProcessService.Default; |
| | 130 | 51 | | } |
| | | 52 | | |
| | | 53 | | /// <inheritdoc /> |
| | | 54 | | public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken |
| | 38 | 55 | | => await GetTokenImplAsync(requestContext, true, cancellationToken).ConfigureAwait(false); |
| | | 56 | | |
| | | 57 | | /// <inheritdoc /> |
| | | 58 | | public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) |
| | 40 | 59 | | => GetTokenImplAsync(requestContext, false, cancellationToken).EnsureCompleted(); |
| | | 60 | | |
| | | 61 | | private async ValueTask<AccessToken> GetTokenImplAsync(TokenRequestContext requestContext, bool async, Cancellat |
| | | 62 | | { |
| | 78 | 63 | | using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("VisualStudioCredential.GetToken", requ |
| | | 64 | | |
| | | 65 | | try |
| | | 66 | | { |
| | 78 | 67 | | var tokenProviderPath = GetTokenProviderPath(); |
| | 78 | 68 | | var tokenProviders = GetTokenProviders(tokenProviderPath); |
| | | 69 | | |
| | 40 | 70 | | var resource = ScopeUtilities.ScopesToResource(requestContext.Scopes); |
| | 40 | 71 | | var processStartInfos = GetProcessStartInfos(tokenProviders, resource, cancellationToken); |
| | | 72 | | |
| | 36 | 73 | | if (processStartInfos.Count == 0) |
| | | 74 | | { |
| | 4 | 75 | | throw new CredentialUnavailableException("No installed instance of Visual Studio was found"); |
| | | 76 | | } |
| | | 77 | | |
| | 32 | 78 | | var accessToken = await RunProcessesAsync(processStartInfos, async, cancellationToken).ConfigureAwait(fa |
| | 16 | 79 | | return scope.Succeeded(accessToken); |
| | | 80 | | } |
| | 62 | 81 | | catch (Exception e) |
| | | 82 | | { |
| | 62 | 83 | | throw scope.FailWrapAndThrow(e); |
| | | 84 | | } |
| | 16 | 85 | | } |
| | | 86 | | |
| | | 87 | | private static string GetTokenProviderPath() |
| | | 88 | | { |
| | 78 | 89 | | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| | | 90 | | { |
| | 78 | 91 | | return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), TokenProv |
| | | 92 | | } |
| | | 93 | | |
| | 0 | 94 | | throw new CredentialUnavailableException($"Operating system {RuntimeInformation.OSDescription} isn't support |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | private async Task<AccessToken> RunProcessesAsync(List<ProcessStartInfo> processStartInfos, bool async, Cancella |
| | | 98 | | { |
| | 32 | 99 | | var exceptions = new List<Exception>(); |
| | 136 | 100 | | foreach (ProcessStartInfo processStartInfo in processStartInfos) |
| | | 101 | | { |
| | 44 | 102 | | string output = string.Empty; |
| | | 103 | | try |
| | | 104 | | { |
| | 44 | 105 | | var processRunner = new ProcessRunner(_processService.Create(processStartInfo), TimeSpan.FromSeconds |
| | 44 | 106 | | output = async |
| | 44 | 107 | | ? await processRunner.RunAsync().ConfigureAwait(false) |
| | 44 | 108 | | : processRunner.Run(); |
| | | 109 | | |
| | 24 | 110 | | JsonElement root = JsonDocument.Parse(output).RootElement; |
| | 16 | 111 | | string accessToken = root.GetProperty("access_token").GetString(); |
| | 16 | 112 | | DateTimeOffset expiresOn = root.GetProperty("expires_on").GetDateTimeOffset(); |
| | 16 | 113 | | return new AccessToken(accessToken, expiresOn); |
| | | 114 | | } |
| | 4 | 115 | | catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) |
| | | 116 | | { |
| | 0 | 117 | | exceptions.Add(new CredentialUnavailableException($"Process \"{processStartInfo.FileName}\" has fail |
| | 0 | 118 | | } |
| | 8 | 119 | | catch (JsonException exception) |
| | | 120 | | { |
| | 8 | 121 | | exceptions.Add(new CredentialUnavailableException($"Process \"{processStartInfo.FileName}\" has non- |
| | 8 | 122 | | } |
| | 20 | 123 | | catch (Exception exception) |
| | | 124 | | { |
| | 20 | 125 | | exceptions.Add(exception); |
| | 20 | 126 | | } |
| | 28 | 127 | | } |
| | | 128 | | |
| | 16 | 129 | | switch (exceptions.Count) { |
| | | 130 | | case 0: |
| | 0 | 131 | | throw new CredentialUnavailableException("No installed instance of Visual Studio was able to get cre |
| | | 132 | | case 1: |
| | 12 | 133 | | ExceptionDispatchInfo.Capture(exceptions[0]).Throw(); |
| | 0 | 134 | | return default; |
| | | 135 | | default: |
| | 4 | 136 | | throw new AggregateException(exceptions); |
| | | 137 | | } |
| | 16 | 138 | | } |
| | | 139 | | |
| | | 140 | | private List<ProcessStartInfo> GetProcessStartInfos(VisualStudioTokenProvider[] visualStudioTokenProviders, stri |
| | | 141 | | { |
| | 40 | 142 | | List<ProcessStartInfo> processStartInfos = new List<ProcessStartInfo>(); |
| | 40 | 143 | | StringBuilder arguments = new StringBuilder(); |
| | | 144 | | |
| | 196 | 145 | | foreach (VisualStudioTokenProvider tokenProvider in visualStudioTokenProviders) |
| | | 146 | | { |
| | 60 | 147 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 148 | | |
| | | 149 | | // If file does not exist, the version of Visual Studio that set the token provider may be uninstalled. |
| | 56 | 150 | | if (!_fileSystem.FileExists(tokenProvider.Path)) |
| | | 151 | | { |
| | | 152 | | continue; |
| | | 153 | | } |
| | | 154 | | |
| | 48 | 155 | | arguments.Clear(); |
| | 48 | 156 | | arguments.Append(ResourceArgumentName).Append(' ').Append(resource); |
| | | 157 | | |
| | 48 | 158 | | if (_tenantId != default) |
| | | 159 | | { |
| | 0 | 160 | | arguments.Append(' ').Append(TenantArgumentName).Append(' ').Append(_tenantId); |
| | | 161 | | } |
| | | 162 | | |
| | | 163 | | // Add the arguments set in the token provider file. |
| | 48 | 164 | | if (tokenProvider.Arguments?.Length > 0) |
| | | 165 | | { |
| | 192 | 166 | | foreach (var argument in tokenProvider.Arguments) |
| | | 167 | | { |
| | 48 | 168 | | arguments.Append(' ').Append(argument); |
| | | 169 | | } |
| | | 170 | | } |
| | | 171 | | |
| | 48 | 172 | | var startInfo = new ProcessStartInfo |
| | 48 | 173 | | { |
| | 48 | 174 | | FileName = tokenProvider.Path, |
| | 48 | 175 | | Arguments = arguments.ToString(), |
| | 48 | 176 | | ErrorDialog = false, |
| | 48 | 177 | | CreateNoWindow = true, |
| | 48 | 178 | | }; |
| | | 179 | | |
| | 48 | 180 | | processStartInfos.Add(startInfo); |
| | | 181 | | } |
| | | 182 | | |
| | 36 | 183 | | return processStartInfos; |
| | | 184 | | } |
| | | 185 | | |
| | | 186 | | private VisualStudioTokenProvider[] GetTokenProviders(string tokenProviderPath) |
| | | 187 | | { |
| | 78 | 188 | | var content = GetTokenProviderContent(tokenProviderPath); |
| | | 189 | | |
| | 62 | 190 | | using JsonDocument document = JsonDocument.Parse(content); |
| | | 191 | | |
| | 62 | 192 | | JsonElement providersElement = document.RootElement.GetProperty("TokenProviders"); |
| | | 193 | | |
| | 40 | 194 | | var providers = new VisualStudioTokenProvider[providersElement.GetArrayLength()]; |
| | 200 | 195 | | for (int i = 0; i < providers.Length; i++) |
| | | 196 | | { |
| | 60 | 197 | | JsonElement providerElement = providersElement[i]; |
| | | 198 | | |
| | 60 | 199 | | var path = providerElement.GetProperty("Path").GetString(); |
| | 60 | 200 | | var preference = providerElement.GetProperty("Preference").GetInt32(); |
| | 60 | 201 | | var arguments = GetStringArrayPropertyValue(providerElement, "Arguments"); |
| | | 202 | | |
| | 60 | 203 | | providers[i] = new VisualStudioTokenProvider(path, arguments, preference); |
| | | 204 | | } |
| | | 205 | | |
| | 40 | 206 | | Array.Sort(providers); |
| | 40 | 207 | | return providers; |
| | 40 | 208 | | } |
| | | 209 | | |
| | | 210 | | private string GetTokenProviderContent(string tokenProviderPath) |
| | | 211 | | { |
| | | 212 | | try |
| | | 213 | | { |
| | 78 | 214 | | return _fileSystem.ReadAllText(tokenProviderPath); |
| | | 215 | | } |
| | 12 | 216 | | catch (FileNotFoundException exception) |
| | | 217 | | { |
| | 12 | 218 | | throw new CredentialUnavailableException($"Visual Studio Token provider file not found at {tokenProvider |
| | | 219 | | } |
| | 4 | 220 | | catch (IOException exception) |
| | | 221 | | { |
| | 4 | 222 | | throw new CredentialUnavailableException($"Visual Studio Token provider can't be accessed at {tokenProvi |
| | | 223 | | } |
| | 62 | 224 | | } |
| | | 225 | | |
| | | 226 | | private static string[] GetStringArrayPropertyValue(JsonElement element, string name) |
| | | 227 | | { |
| | 60 | 228 | | JsonElement arrayElement = element.GetProperty(name); |
| | 60 | 229 | | var array = new string[arrayElement.GetArrayLength()]; |
| | | 230 | | |
| | 240 | 231 | | for (int i = 0; i < array.Length; i++) |
| | | 232 | | { |
| | 60 | 233 | | array[i] = arrayElement[i].GetString(); |
| | | 234 | | } |
| | | 235 | | |
| | 60 | 236 | | return array; |
| | | 237 | | } |
| | | 238 | | |
| | | 239 | | private readonly struct VisualStudioTokenProvider : IComparable<VisualStudioTokenProvider> |
| | | 240 | | { |
| | | 241 | | private readonly int _preference; |
| | | 242 | | |
| | 104 | 243 | | public string Path { get; } |
| | 96 | 244 | | public string[] Arguments { get; } |
| | | 245 | | |
| | | 246 | | public VisualStudioTokenProvider(string path, string[] arguments, int preference) |
| | | 247 | | { |
| | 60 | 248 | | Path = path; |
| | 60 | 249 | | Arguments = arguments; |
| | 60 | 250 | | _preference = preference; |
| | 60 | 251 | | } |
| | | 252 | | |
| | 24 | 253 | | public int CompareTo(VisualStudioTokenProvider other) => _preference.CompareTo(other._preference); |
| | | 254 | | } |
| | | 255 | | } |
| | | 256 | | } |