-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathAzureClient.cs
More file actions
471 lines (373 loc) · 18.4 KB
/
AzureClient.cs
File metadata and controls
471 lines (373 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
using Azure.Core;
using Microsoft.Identity.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Vano.Tools.Azure.Model;
namespace Vano.Tools.Azure
{
public class AzureClient : IAzureClient
{
#region Private members
private bool _initialized = false;
private HttpClient _client;
private SemaphoreSlim _lock = new SemaphoreSlim(1, 1);
private IPublicClientApplication _publicClientApp;
private AuthenticationResult _authResult;
#endregion
#region Constants
// Azure PowerShell client id
private const string AppClientId = "1950a258-227b-4e31-a9cf-717495945fc2";
private const string AppRedirectUri = "urn:ietf:wg:oauth:2.0:oob";
/// <summary>
/// Storage account name must be between 3 and 24 characters in length and use numbers and lower-case letters only.
/// </summary>
public static readonly Regex StorageNameValidation = new Regex(@"^[a-z0-9]{3,24}$", RegexOptions.Compiled);
/// <summary>
/// Resource group name can only include alphanumeric characters, periods, underscores, hyphens and parenthesis and cannot end in a period. Length (1,64).
/// </summary>
public static readonly Regex ResourceGroupValidation = new Regex(@"^[-_a-z0-9()\.]{0,63}[-_a-z0-9()]$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
#endregion
#region Constructors
public AzureClient(
string resourceManagerEndpoint = "management.azure.com",
string apiVersion = "2024-11-01",
AzureMetadata metadata = null,
Func<HttpMessageHandler> handlerFactory = null)
: this(resourceManagerEndpoint, apiVersion, null, null, handlerFactory)
{
this.Metadata = metadata;
}
public AzureClient(
string resourceManagerEndpoint = "management.azure.com",
string apiVersion = "2024-11-01",
string authenticationEndpoint = "https://login.windows.net",
string appResourceId = "https://management.core.windows.net/",
Func<HttpMessageHandler> handlerFactory = null)
{
this.ResouceManagerEndpoint = resourceManagerEndpoint;
this.ApiVersion = resourceManagerEndpoint.Contains("dogfood") ? "2022-03-01-privatepreview" : apiVersion;
this.AuthenticationEndpoint = authenticationEndpoint;
this.AppResourceId = appResourceId;
_client = CreateHttpClient(handlerFactory);
}
#endregion
#region Public properties
public AzureMetadata Metadata { get; private set; }
public string ResouceManagerEndpoint { get; private set; }
public string ApiVersion { get; private set; }
public string AuthenticationEndpoint { get; private set; }
public string AppResourceId { get; private set; }
public HttpHeadersProcessor HttpHeadersProcessor { get; set; }
#endregion
#region Public Methods - Initialize
public async Task Initialize()
{
if (!_initialized)
{
await _lock.WaitAsync();
try
{
if (!_initialized)
{
await InitializeInternal();
_initialized = true;
}
}
finally
{
_lock.Release();
}
}
}
private async Task InitializeInternal()
{
if (string.IsNullOrEmpty(this.AuthenticationEndpoint) || string.IsNullOrEmpty(this.AppResourceId))
{
if (this.Metadata == null)
{
// dogfood environment uses a different api version for the metadata endpoint.
this.Metadata = await GetAzureMetadata(
this.ResouceManagerEndpoint,
apiVersion: this.ResouceManagerEndpoint.Contains("dogfood") ?
this.ApiVersion :
"1.0");
}
this.AuthenticationEndpoint = this.Metadata.LoginEndpoint;
// dogfood's metadata doesn't retieve the correct audience endpoint for the dogfood's environemnt
this.AppResourceId = this.ResouceManagerEndpoint.Contains("dogfood") ?
"https://management.core.windows.net/" :
this.Metadata.Audiences.First();
}
// Also clear cookies from the browser control.
ClearCookies();
Uri authenticationUri = new Uri(this.AuthenticationEndpoint);
Uri authority = this.ResouceManagerEndpoint.Contains("dogfood") ?
new Uri(authenticationUri, "83abe5cd-bcc3-441a-bd86-e6a75360cecc") : // "Contoso Corp."
new Uri(authenticationUri, "organizations");
// MSAL: Build the PublicClientApplication
_publicClientApp = PublicClientApplicationBuilder.Create(AppClientId)
.WithAuthority(authority, validateAuthority: false)
.WithCacheOptions(CacheOptions.EnableSharedCacheOptions)
.WithRedirectUri(AppRedirectUri)
.Build();
// Try to acquire token interactively
try
{
string[] scopes = new[] { $"{this.AppResourceId.TrimEnd('/')}/.default" };
_authResult = await _publicClientApp.AcquireTokenInteractive(scopes)
.WithPrompt(Prompt.SelectAccount)
.ExecuteAsync();
Trace.WriteLine("Authority: " + _publicClientApp.Authority);
}
catch (MsalClientException ex) when (ex.ErrorCode == "authentication_canceled")
{
Trace.TraceInformation(ex.Message);
throw new OperationCanceledException(ex.Message, ex);
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
throw;
}
}
#endregion
#region Public Methods - ARM Operations
public async Task<IEnumerable<string>> GetTenantsIds(CancellationToken cancellationToken = new CancellationToken())
{
string token = await GetToken();
JObject response = await CallAzureResourceManagerAsJObject("GET", "/tenants", token, cancellationToken: cancellationToken);
IEnumerable<string> tenantIds = response
.Value<JArray>("value")
.Select(tenant => tenant.Value<string>("tenantId"));
foreach (string tenantId in tenantIds)
{
Trace.WriteLine("Tenant: " + tenantId);
}
return tenantIds;
}
public async Task<IEnumerable<Subscription>> GetSubscriptions(CancellationToken cancellationToken = new CancellationToken())
{
List<Subscription> subscriptions = new List<Subscription>();
IEnumerable<string> tenantsIds = await GetTenantsIds(cancellationToken);
foreach (string tenantId in tenantsIds)
{
IEnumerable<Subscription> subscriptionsInTenant = null;
try
{
string tenantToken = await GetTenantToken(tenantId);
if (tenantToken == null)
{
continue;
}
JObject response = await CallAzureResourceManagerAsJObject("GET", "/subscriptions", tenantToken, cancellationToken: cancellationToken);
subscriptionsInTenant = response
.Value<JArray>("value")
.Select(tenant => new Subscription()
{
Id = tenant.Value<string>("subscriptionId"),
DisplayName = tenant.Value<string>("displayName"),
State = tenant.Value<string>("state"),
TenantId = tenantId
});
}
catch (Exception e)
{
Trace.WriteLine(e.ToString());
}
if (subscriptionsInTenant != null)
{
subscriptions.AddRange(subscriptionsInTenant);
}
}
return subscriptions;
}
public async Task<IEnumerable<Location>> GetLocations(Subscription subscription, CancellationToken cancellationToken = new CancellationToken())
{
var tenantToken = await GetTenantToken(subscription.TenantId);
JObject response = await CallAzureResourceManagerAsJObject("GET", string.Format(@"/subscriptions/{0}/locations", subscription.Id), tenantToken, cancellationToken: cancellationToken);
IEnumerable<Location> locations = response.Value<JArray>("value").ToObject<IEnumerable<Location>>();
return locations;
}
#endregion
#region Public Static Methods - Metadata
public static async Task<AzureMetadata> GetAzureMetadata(string azureResourceManager = "management.azure.com", string apiVersion = "1.0")
{
JObject response = await GetAzureResourceManagerMetadataAsJObject(azureResourceManager, apiVersion);
JObject authentication = response.Value<JObject>("authentication");
AzureMetadata metadata = new AzureMetadata()
{
PortalEndpoint = response.Value<string>("portalEndpoint") ?? response.Value<string>("portal"),
GraphEndpoint = response.Value<string>("graphEndpoint"),
LoginEndpoint = authentication.Value<string>("loginEndpoint"),
Audiences = authentication
.Value<JArray>("audiences")
.Select(audience => audience.Value<string>())
.ToArray()
};
return metadata;
}
private static async Task<JObject> GetAzureResourceManagerMetadataAsJObject(string azureResourceManager, string apiVersion)
{
string response = await GetAzureResourceManagerMetadata(azureResourceManager, apiVersion);
if (!string.IsNullOrWhiteSpace(response))
{
return JObject.Parse(response);
}
return new JObject();
}
private static async Task<string> GetAzureResourceManagerMetadata(string azureResourceManager, string apiVersion)
{
string azureResourceManagerMetadataEndpoint = string.Format("https://{0}/metadata/endpoints?api-version={1}", azureResourceManager, apiVersion);
Trace.WriteLine("GET " + azureResourceManagerMetadataEndpoint);
Uri requestUri = new Uri(azureResourceManagerMetadataEndpoint);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "GET";
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
using (Stream receiveStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
string result = await readStream.ReadToEndAsync();
Trace.WriteLine(result);
return result;
}
}
}
#endregion
#region Private Methods - Tokens
public async Task<string> GetAuthSecret(string tenantId = null)
{
string token = tenantId == null ?
await GetToken() :
await GetTenantToken(tenantId);
return token;
}
private async Task<string> GetToken()
{
await Task.Yield();
return _authResult.AccessToken;
}
private async Task<string> GetTenantToken(string tenantId)
{
try
{
var scopes = new[] { $"{this.AppResourceId}/.default" };
var authority = $"{this.AuthenticationEndpoint.TrimEnd('/')}/{tenantId}";
var app = PublicClientApplicationBuilder
.Create(AppClientId)
.WithAuthority(authority)
.WithRedirectUri(AppRedirectUri)
.WithCacheOptions(CacheOptions.EnableSharedCacheOptions)
.Build();
var accounts = await app.GetAccountsAsync();
AuthenticationResult result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
return result.AccessToken;
}
catch (Exception ex)
{
Trace.TraceError($"TenantId: {tenantId}. Error: {ex.Message}");
return null;
}
}
#endregion
#region Private Methods - ARM Helper Methods
private static HttpClient CreateHttpClient(Func<HttpMessageHandler> handlerFactory = null)
{
HttpClient client = handlerFactory != null ?
new HttpClient(handlerFactory()) :
new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (!client.DefaultRequestHeaders.Contains("User-Agent"))
{
client.DefaultRequestHeaders.Add("User-Agent", $"VisualARM/{Assembly.GetExecutingAssembly().GetName().Version}");
}
return client;
}
private Uri CreateAzureResourceManagerUri(string path, Dictionary<string, string> parameters = null, string armEndpoint = null, string apiVersion = null)
{
armEndpoint = string.IsNullOrEmpty(armEndpoint) ? this.ResouceManagerEndpoint : armEndpoint;
if (path.Contains("api-version="))
{
return new Uri(string.Format("https://{0}{1}{2}",
armEndpoint,
path,
parameters != null ?
string.Concat("&", string.Join("&", parameters.Select(p => string.Concat(p.Key, "=", p.Value)))) :
string.Empty)
.Replace(" ", "%20"));
}
return new Uri(string.Format("https://{0}{1}?api-version={2}{3}",
armEndpoint,
path,
apiVersion ?? this.ApiVersion,
parameters != null ?
string.Concat("&", string.Join("&", parameters.Select(p => string.Concat(p.Key, "=", p.Value)))) :
string.Empty)
.Replace(" ", "%20"));
}
private async Task<JObject> CallAzureResourceManagerAsJObject(string method, string path, string token, string body = null, Dictionary<string, string> parameters = null, string armEndpoint = null, string apiVersion = null, bool displaySecrets = false, CancellationToken cancellationToken = new CancellationToken())
{
string response = await CallAzureResourceManager(method, path, token, body, parameters, armEndpoint, apiVersion, displaySecrets, cancellationToken);
if (!string.IsNullOrWhiteSpace(response))
{
return JObject.Parse(response);
}
return new JObject();
}
public async Task<string> CallAzureResourceManager(string method, string path, string token, string body = null, Dictionary<string, string> parameters = null, string armEndpoint = null, string apiVersion = null, bool displaySecrets = false, CancellationToken cancellationToken = new CancellationToken())
{
Uri requestUri = CreateAzureResourceManagerUri(path, parameters, armEndpoint, apiVersion);
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (HttpHeadersProcessor != null)
{
HttpHeadersProcessor.CaptureHttpHeadersFromRequest(requestUri.Host, _client.DefaultRequestHeaders, displaySecrets);
HttpHeadersProcessor.CaptureHttpHeadersFromRequest(requestUri.Host, request.Headers, displaySecrets);
}
if (!string.IsNullOrWhiteSpace(body))
{
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
}
using (HttpResponseMessage response = await _client.SendAsync(request, cancellationToken))
{
if (HttpHeadersProcessor != null)
{
HttpHeadersProcessor.CaptureHttpHeadersFromResponse(response.StatusCode, response.Headers, displaySecrets);
}
string output = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new AzureClientException(response.StatusCode, output);
}
return output;
}
}
#endregion
#region Private Static Methods - Clear Cookies
private static void ClearCookies()
{
NativeMethods.InternetSetOption(IntPtr.Zero, NativeMethods.INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);
}
private static class NativeMethods
{
internal const int INTERNET_OPTION_END_BROWSER_SESSION = 42;
[DllImport("wininet.dll", SetLastError = true)]
internal static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
}
#endregion
}
}