|
1 | 1 | using System; |
2 | | -using System.Net; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
3 | 4 | using System.Net.Http; |
| 5 | +using System.Threading; |
4 | 6 | using System.Threading.Tasks; |
5 | 7 | using Azure.Core; |
6 | | -using Azure.Identity; |
7 | 8 | using Microsoft.Extensions.Logging; |
8 | 9 | using Models.OpenSourcePortal; |
9 | 10 | using Newtonsoft.Json; |
10 | 11 |
|
11 | 12 | namespace Azure.Sdk.Tools.NotificationConfiguration.Helpers |
12 | 13 | { |
| 14 | + /// <summary> |
| 15 | + /// Utility class for converting GitHub usernames to AAD user principal names. |
| 16 | + /// </summary> |
| 17 | + /// <remarks> |
| 18 | + /// A map of GitHub usernames to AAD user principal names is cached in memory to avoid making multiple calls to the |
| 19 | + /// OpenSource portal API. The cache is initialized with the full alias list on the first call to |
| 20 | + /// GetUserPrincipalNameFromGithubAsync. |
| 21 | + /// </remarks> |
13 | 22 | public class GitHubToAADConverter |
14 | 23 | { |
| 24 | + private readonly TokenCredential credential; |
| 25 | + private readonly ILogger<GitHubToAADConverter> logger; |
| 26 | + private readonly SemaphoreSlim cacheLock = new(1); |
| 27 | + private Dictionary<string, string> lookupCache; |
| 28 | + |
15 | 29 | /// <summary> |
16 | 30 | /// GitHubToAadConverter constructor for generating new token, and initialize http client. |
17 | 31 | /// </summary> |
18 | 32 | /// <param name="credential">The aad token auth class.</param> |
19 | 33 | /// <param name="logger">Logger</param> |
20 | | - public GitHubToAADConverter( |
21 | | - ClientSecretCredential credential, |
22 | | - ILogger<GitHubToAADConverter> logger) |
| 34 | + public GitHubToAADConverter(TokenCredential credential, ILogger<GitHubToAADConverter> logger) |
23 | 35 | { |
| 36 | + this.credential = credential; |
24 | 37 | this.logger = logger; |
25 | | - var opsAuthToken = ""; |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + public async Task<string> GetUserPrincipalNameFromGithubAsync(string gitHubUserName) |
| 42 | + { |
| 43 | + await EnsureCacheExistsAsync(); |
| 44 | + |
| 45 | + if (this.lookupCache.TryGetValue(gitHubUserName, out string aadUserPrincipalName)) |
| 46 | + { |
| 47 | + return aadUserPrincipalName; |
| 48 | + } |
| 49 | + |
| 50 | + return null; |
| 51 | + } |
| 52 | + |
| 53 | + public async Task EnsureCacheExistsAsync() |
| 54 | + { |
| 55 | + await this.cacheLock.WaitAsync(); |
26 | 56 | try |
27 | 57 | { |
28 | | - // This is aad scope of opensource rest API. |
29 | | - string[] scopes = new string[] |
| 58 | + if (this.lookupCache == null) |
30 | 59 | { |
31 | | - "api://2789159d-8d8b-4d13-b90b-ca29c1707afd/.default" |
32 | | - }; |
33 | | - opsAuthToken = credential.GetToken(new TokenRequestContext(scopes)).Token; |
| 60 | + var peopleLinks = await GetPeopleLinksAsync(); |
| 61 | + this.lookupCache = peopleLinks.ToDictionary( |
| 62 | + x => x.GitHub.Login, |
| 63 | + x => x.Aad.UserPrincipalName, |
| 64 | + StringComparer.OrdinalIgnoreCase); |
| 65 | + } |
34 | 66 | } |
35 | | - catch (Exception ex) |
| 67 | + finally |
36 | 68 | { |
37 | | - logger.LogError("Failed to generate aad token. " + ex.Message); |
| 69 | + this.cacheLock.Release(); |
38 | 70 | } |
39 | | - client = new HttpClient(); |
40 | | - client.DefaultRequestHeaders.Add("content_type", "application/json"); |
41 | | - client.DefaultRequestHeaders.Add("api-version", "2019-10-01"); |
42 | | - client.DefaultRequestHeaders.Add("Authorization", $"Bearer {opsAuthToken}"); |
43 | 71 | } |
44 | 72 |
|
45 | | - private readonly HttpClient client; |
46 | | - private readonly ILogger<GitHubToAADConverter> logger; |
47 | | - |
48 | | - /// <summary> |
49 | | - /// Get the user principal name from github. User principal name is in format of ms email. |
50 | | - /// </summary> |
51 | | - /// <param name="githubUserName">github user name</param> |
52 | | - /// <returns>Aad user principal name</returns> |
53 | | - public string GetUserPrincipalNameFromGithub(string githubUserName) |
| 73 | + private async Task<UserLink[]> GetPeopleLinksAsync() |
54 | 74 | { |
55 | | - return GetUserPrincipalNameFromGithubAsync(githubUserName).Result; |
56 | | - } |
| 75 | + AccessToken opsAuthToken; |
57 | 76 |
|
58 | | - public async Task<string> GetUserPrincipalNameFromGithubAsync(string githubUserName) |
59 | | - { |
60 | 77 | try |
61 | 78 | { |
62 | | - var responseJsonString = await client.GetStringAsync($"https://repos.opensource.microsoft.com/api/people/links/github/{githubUserName}"); |
63 | | - dynamic contentJson = JsonConvert.DeserializeObject(responseJsonString); |
64 | | - return contentJson.aad.userPrincipalName; |
65 | | - } |
66 | | - catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) |
67 | | - { |
68 | | - logger.LogWarning("Github username {Username} not found", githubUserName); |
| 79 | + // This is aad scope of opensource rest API. |
| 80 | + string[] scopes = new [] { "api://66b6ea26-954d-4b68-8f48-71e3faec7ad1/.default" }; |
| 81 | + opsAuthToken = await credential.GetTokenAsync(new TokenRequestContext(scopes), CancellationToken.None); |
69 | 82 | } |
70 | 83 | catch (Exception ex) |
71 | 84 | { |
72 | | - logger.LogError(ex.Message); |
| 85 | + this.logger.LogError("Failed to generate aad token. {ExceptionMessage}", ex.Message); |
| 86 | + throw; |
73 | 87 | } |
74 | 88 |
|
75 | | - return null; |
76 | | - } |
77 | | - |
78 | | - public async Task<UserLink[]> GetPeopleLinksAsync() |
79 | | - { |
80 | 89 | try |
81 | 90 | { |
82 | | - logger.LogInformation("Calling GET https://repos.opensource.microsoft.com/api/people/links"); |
83 | | - var responseJsonString = await client.GetStringAsync($"https://repos.opensource.microsoft.com/api/people/links"); |
84 | | - var allLinks = JsonConvert.DeserializeObject<UserLink[]>(responseJsonString); |
| 91 | + using HttpClient client = new (); |
| 92 | + client.DefaultRequestHeaders.Add("content_type", "application/json"); |
| 93 | + client.DefaultRequestHeaders.Add("api-version", "2019-10-01"); |
| 94 | + client.DefaultRequestHeaders.Add("Authorization", $"Bearer {opsAuthToken.Token}"); |
85 | 95 |
|
86 | | - return allLinks; |
| 96 | + this.logger.LogInformation("Calling GET https://repos.opensource.microsoft.com/api/people/links"); |
| 97 | + string responseJsonString = await client.GetStringAsync($"https://repos.opensource.microsoft.com/api/people/links"); |
| 98 | + return JsonConvert.DeserializeObject<UserLink[]>(responseJsonString); |
87 | 99 | } |
88 | 100 | catch (Exception ex) |
89 | 101 | { |
90 | | - logger.LogError(ex.Message); |
| 102 | + this.logger.LogError(ex, "Error getting people links from opensource.microsoft.com: {ExceptionMessage}", ex.Message); |
| 103 | + throw; |
91 | 104 | } |
92 | | - |
93 | | - return null; |
94 | 105 | } |
95 | 106 | } |
96 | 107 | } |
0 commit comments