|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Net.Http; |
| 6 | +using System.Net.Http.Headers; |
| 7 | +using System.Text; |
| 8 | +using System.Threading; |
| 9 | +using System.Threading.Tasks; |
| 10 | +using GitHubVulnerabilities2Db.GraphQL; |
| 11 | +using Newtonsoft.Json; |
| 12 | +using Newtonsoft.Json.Linq; |
| 13 | +using VerifyGitHubVulnerabilities.Configuration; |
| 14 | + |
| 15 | +namespace VerifyGitHubVulnerabilities.GraphQL |
| 16 | +{ |
| 17 | + public class QueryService : IQueryService |
| 18 | + { |
| 19 | + /// <remarks> |
| 20 | + /// GitHub requires that every request includes a UserAgent. |
| 21 | + /// </remarks> |
| 22 | + public const string UserAgent = "NuGet.Jobs.VerifyGitHubVulnerabilities"; |
| 23 | + |
| 24 | + private readonly VerifyGitHubVulnerabilitiesConfiguration _configuration; |
| 25 | + private readonly HttpClient _client; |
| 26 | + |
| 27 | + public QueryService( |
| 28 | + VerifyGitHubVulnerabilitiesConfiguration configuration, |
| 29 | + HttpClient client) |
| 30 | + { |
| 31 | + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); |
| 32 | + _client = client ?? throw new ArgumentNullException(nameof(client)); |
| 33 | + } |
| 34 | + |
| 35 | + public async Task<QueryResponse> QueryAsync(string query, CancellationToken token) |
| 36 | + { |
| 37 | + var queryJObject = new JObject |
| 38 | + { |
| 39 | + ["query"] = query |
| 40 | + }; |
| 41 | + |
| 42 | + var response = await MakeWebRequestAsync(queryJObject.ToString(), token); |
| 43 | + return JsonConvert.DeserializeObject<QueryResponse>(response); |
| 44 | + } |
| 45 | + |
| 46 | + private async Task<string> MakeWebRequestAsync(string query, CancellationToken token) |
| 47 | + { |
| 48 | + using (var request = CreateRequest(query)) |
| 49 | + using (var response = await _client.SendAsync(request, token)) |
| 50 | + { |
| 51 | + return await response.Content.ReadAsStringAsync(); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + private HttpRequestMessage CreateRequest(string query) |
| 56 | + { |
| 57 | + var message = new HttpRequestMessage |
| 58 | + { |
| 59 | + Method = HttpMethod.Post, |
| 60 | + RequestUri = _configuration.GitHubGraphQLQueryEndpoint, |
| 61 | + Content = new StringContent(query, Encoding.UTF8, "application/json") |
| 62 | + }; |
| 63 | + |
| 64 | + message.Headers.Authorization = new AuthenticationHeaderValue( |
| 65 | + "Bearer", _configuration.GitHubPersonalAccessToken); |
| 66 | + message.Headers.UserAgent.TryParseAdd(UserAgent); |
| 67 | + return message; |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments