-
Notifications
You must be signed in to change notification settings - Fork 351
Expand file tree
/
Copy pathHttpUtilities.cs
More file actions
282 lines (246 loc) · 12.2 KB
/
Copy pathHttpUtilities.cs
File metadata and controls
282 lines (246 loc) · 12.2 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Config.DatabasePrimitives;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core.Authorization;
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Core.Services;
using Azure.DataApiBuilder.Core.Services.MetadataProviders;
using Azure.DataApiBuilder.Service.GraphQLBuilder;
using Microsoft.Extensions.Logging;
namespace Azure.DataApiBuilder.Service.HealthCheck
{
/// <summary>
/// HttpUtilities creates and executes the HTTP requests for HealthEndpoint.
/// </summary>
public class HttpUtilities
{
private readonly ILogger<HttpUtilities> _logger;
private HttpClient _httpClient;
private IMetadataProviderFactory _metadataProviderFactory;
private RuntimeConfigProvider _runtimeConfigProvider;
/// <summary>
/// HttpUtility constructor.
/// </summary>
/// <param name="logger">Logger</param>
/// <param name="metadataProviderFactory">MetadataProviderFactory</param>
/// <param name="runtimeConfigProvider">RuntimeConfigProvider</param>
/// <param name="httpClientFactory">HttpClientFactory</param>
public HttpUtilities(
ILogger<HttpUtilities> logger,
IMetadataProviderFactory metadataProviderFactory,
RuntimeConfigProvider runtimeConfigProvider,
IHttpClientFactory httpClientFactory)
{
_logger = logger;
_metadataProviderFactory = metadataProviderFactory;
_runtimeConfigProvider = runtimeConfigProvider;
_httpClient = httpClientFactory.CreateClient("ContextConfiguredHealthCheckClient");
}
// Executes the DB query by establishing a connection to the DB.
public async Task<string?> ExecuteDbQueryAsync(string query, string connectionString, DbProviderFactory providerFactory, DatabaseType databaseType)
{
string? errorMessage = null;
// Execute the query on DB and return the response time.
DbConnection? connection = providerFactory.CreateConnection();
if (connection == null)
{
errorMessage = "Failed to create database connection.";
_logger.LogError(errorMessage);
return errorMessage;
}
using (connection)
{
try
{
connection.ConnectionString = Utilities.NormalizeConnectionString(connectionString, databaseType, _logger);
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = query;
await connection.OpenAsync();
using (DbDataReader reader = await command.ExecuteReaderAsync())
{
_logger.LogTrace("The health check query for datasource executed successfully.");
}
}
}
catch (Exception ex)
{
_logger.LogError($"An exception occurred while executing the health check query: {ex.Message}");
errorMessage = ex.Message;
}
}
return errorMessage;
}
// Executes the REST query by sending a GET request to the API.
public async Task<string?> ExecuteRestQueryAsync(string restUriSuffix, string entityName, int first, string incomingRoleHeader, string incomingRoleToken)
{
string? errorMessage = null;
try
{
// Base URL of the API that handles SQL operations
string apiRoute = $"{restUriSuffix}{Utilities.CreateHttpRestQuery(entityName, first)}";
if (string.IsNullOrEmpty(apiRoute))
{
_logger.LogError("The API route is not available, hence HealthEndpoint is not available.");
return errorMessage;
}
if (!Program.CheckSanityOfUrl($"{_httpClient.BaseAddress}{restUriSuffix}"))
{
_logger.LogError("Blocked outbound request due to invalid or unsafe URI.");
return "Blocked outbound request due to invalid or unsafe URI.";
}
HttpRequestMessage message = new(method: HttpMethod.Get, requestUri: apiRoute);
if (!string.IsNullOrEmpty(incomingRoleToken))
{
message.Headers.Add(AuthenticationOptions.CLIENT_PRINCIPAL_HEADER, incomingRoleToken);
}
if (!string.IsNullOrEmpty(incomingRoleHeader))
{
message.Headers.Add(AuthorizationResolver.CLIENT_ROLE_HEADER, incomingRoleHeader);
}
HttpResponseMessage response = await _httpClient.SendAsync(message);
if (response.IsSuccessStatusCode)
{
_logger.LogTrace($"The REST HealthEndpoint query executed successfully with code {response.IsSuccessStatusCode}.");
}
else
{
errorMessage = $"The REST HealthEndpoint query failed with code: {response.StatusCode}.";
}
return errorMessage;
}
catch (Exception ex)
{
_logger.LogError($"An exception occurred while executing the health check REST query: {ex.Message}");
return ex.Message;
}
}
// Executes the MCP query by sending an initialize JSON-RPC POST request to the MCP endpoint.
public async Task<string?> ExecuteMcpQueryAsync(string mcpUriSuffix, string incomingRoleHeader, string incomingRoleToken)
{
string? errorMessage = null;
try
{
if (string.IsNullOrWhiteSpace(mcpUriSuffix))
{
const string msg = "MCP path is not configured.";
_logger.LogError(msg);
return msg;
}
if (_httpClient.BaseAddress is null)
{
const string msg = "Health check HTTP client BaseAddress is not configured.";
_logger.LogError(msg);
return msg;
}
// Ensure the configured MCP path cannot override the host (e.g. absolute URIs).
if (!Uri.TryCreate(mcpUriSuffix, UriKind.Relative, out _))
{
_logger.LogError("Blocked outbound request due to invalid or unsafe URI.");
return "Blocked outbound request due to invalid or unsafe URI.";
}
Uri requestUri = new(_httpClient.BaseAddress, mcpUriSuffix);
if (!Program.CheckSanityOfUrl(requestUri.AbsoluteUri))
{
_logger.LogError("Blocked outbound request due to invalid or unsafe URI.");
return "Blocked outbound request due to invalid or unsafe URI.";
}
string jsonPayload = Utilities.CreateHttpMcpQuery();
HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, Utilities.JSON_CONTENT_TYPE);
HttpRequestMessage message = new(method: HttpMethod.Post, requestUri: requestUri)
{
Content = content
}
// The MCP Streamable HTTP transport requires the client to accept both
// JSON and SSE responses.
message.Headers.Add("Accept", "application/json, text/event-stream");
if (!string.IsNullOrEmpty(incomingRoleToken))
{
message.Headers.Add(AuthenticationOptions.CLIENT_PRINCIPAL_HEADER, incomingRoleToken);
}
if (!string.IsNullOrEmpty(incomingRoleHeader))
{
message.Headers.Add(AuthorizationResolver.CLIENT_ROLE_HEADER, incomingRoleHeader);
}
HttpResponseMessage response = await _httpClient.SendAsync(message);
if (response.IsSuccessStatusCode)
{
_logger.LogTrace($"The MCP HealthEndpoint query executed successfully with code {response.StatusCode}.");
}
else
{
errorMessage = $"The MCP HealthEndpoint query failed with code: {response.StatusCode}.";
}
return errorMessage;
}
catch (Exception ex)
{
_logger.LogError($"An exception occurred while executing the health check MCP query: {ex.Message}");
return ex.Message;
}
}
// Executes the GraphQL query by sending a POST request to the API.
// Internally calls the metadata provider to fetch the column names to create the graphql payload.
public async Task<string?> ExecuteGraphQLQueryAsync(string graphqlUriSuffix, string entityName, Entity entity, string incomingRoleHeader, string incomingRoleToken)
{
string? errorMessage = null;
if (!Program.CheckSanityOfUrl($"{_httpClient.BaseAddress}{graphqlUriSuffix}"))
{
_logger.LogError("Blocked outbound request due to invalid or unsafe URI.");
return "Blocked outbound request due to invalid or unsafe URI.";
}
try
{
string dataSourceName = _runtimeConfigProvider.GetConfig().GetDataSourceNameFromEntityName(entityName);
// Fetch Column Names from Metadata Provider
ISqlMetadataProvider sqlMetadataProvider = _metadataProviderFactory.GetMetadataProvider(dataSourceName);
DatabaseObject dbObject = sqlMetadataProvider.GetDatabaseObjectByKey(entityName);
List<string> columnNames = dbObject.SourceDefinition.Columns.Keys.ToList();
// In case of GraphQL API, use the plural value specified in [entity.graphql.type.plural].
// Further, we need to camel case this plural value to match the GraphQL object name.
string graphqlObjectName = GraphQLNaming.GenerateListQueryName(entityName, entity);
// In case any primitive column names are present, execute the query
if (columnNames.Any())
{
string jsonPayload = Utilities.CreateHttpGraphQLQuery(graphqlObjectName, columnNames, entity.EntityFirst);
HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, Utilities.JSON_CONTENT_TYPE);
HttpRequestMessage message = new(method: HttpMethod.Post, requestUri: graphqlUriSuffix)
{
Content = content
};
if (!string.IsNullOrEmpty(incomingRoleToken))
{
message.Headers.Add(AuthenticationOptions.CLIENT_PRINCIPAL_HEADER, incomingRoleToken);
}
if (!string.IsNullOrEmpty(incomingRoleHeader))
{
message.Headers.Add(AuthorizationResolver.CLIENT_ROLE_HEADER, incomingRoleHeader);
}
HttpResponseMessage response = await _httpClient.SendAsync(message);
if (response.IsSuccessStatusCode)
{
_logger.LogTrace("The GraphQL HealthEndpoint query executed successfully.");
}
else
{
errorMessage = $"The GraphQL HealthEndpoint query failed with code: {response.StatusCode}.";
}
}
return errorMessage;
}
catch (Exception ex)
{
_logger.LogError($"An exception occurred while executing the GraphQL health check query: {ex.Message}");
return ex.Message;
}
}
}
}