-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathAdmin.cs
325 lines (269 loc) · 12.6 KB
/
Admin.cs
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Sdk.Tools.TestProxy.Common;
using Azure.Sdk.Tools.TestProxy.Common.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
namespace Azure.Sdk.Tools.TestProxy
{
[ApiController]
[Route("[controller]/[action]")]
public sealed class Admin : ControllerBase
{
private readonly RecordingHandler _recordingHandler;
private readonly ILogger _logger;
public Admin(RecordingHandler recordingHandler, ILoggerFactory loggingFactory)
{
_recordingHandler = recordingHandler;
_logger = loggingFactory.CreateLogger<Admin>();
}
[HttpPost]
public async Task Reset()
{
DebugLogger.LogAdminRequestDetails(_logger, Request);
var recordingId = RecordingHandler.GetHeader(Request, "x-recording-id", allowNulls: true);
await _recordingHandler.SetDefaultExtensions(recordingId);
}
[HttpGet]
public void IsAlive()
{
DebugLogger.LogAdminRequestDetails(_logger, Request);
Response.StatusCode = 200;
}
[HttpPost]
public async Task AddTransform()
{
DebugLogger.LogAdminRequestDetails(_logger, Request);
var tName = RecordingHandler.GetHeader(Request, "x-abstraction-identifier");
var recordingId = RecordingHandler.GetHeader(Request, "x-recording-id", allowNulls: true);
ResponseTransform t = (ResponseTransform)GetTransform(tName, await HttpRequestInteractions.GetBody(Request));
if (recordingId != null)
{
_recordingHandler.AddTransformToRecording(recordingId, t);
}
else
{
_recordingHandler.Transforms.Add(t);
}
}
[HttpPost]
public async Task RemoveSanitizers()
{
DebugLogger.LogAdminRequestDetails(_logger, Request);
// Originally, this list was parsed using [FromBody], which was implicitly case insensitive. Need to maintain for compat.
var sanitizerList = await HttpRequestInteractions.GetBody<RemoveSanitizerList>(Request, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
var recordingId = RecordingHandler.GetHeader(Request, "x-recording-id", allowNulls: true);
var removedSanitizers = new List<string>();
// - body may be empty
// - body may actually pass an empty list. handle both.
if ((sanitizerList?.Sanitizers ?? new List<string>()).Count == 0)
{
throw new HttpException(HttpStatusCode.BadRequest, "At least one sanitizerId for removal must be provided.");
}
foreach(var sanitizerId in sanitizerList.Sanitizers) {
var removedId = await _recordingHandler.UnregisterSanitizer(sanitizerId, recordingId);
if (!string.IsNullOrWhiteSpace(removedId))
{
removedSanitizers.Add(sanitizerId);
}
}
var json = JsonSerializer.Serialize(new { Removed = removedSanitizers });
Response.ContentType = "application/json";
Response.ContentLength = json.Length;
await Response.WriteAsync(json);
}
[HttpGet]
public async Task GetSanitizers()
{
DebugLogger.LogAdminRequestDetails(_logger, Request);
var recordingId = RecordingHandler.GetHeader(Request, "x-recording-id", allowNulls: true);
List<RegisteredSanitizer> sanitizers;
if (!string.IsNullOrEmpty(recordingId))
{
var session = _recordingHandler.GetActiveSession(recordingId);
sanitizers = await _recordingHandler.SanitizerRegistry.GetRegisteredSanitizers(session);
}
else
{
sanitizers = await _recordingHandler.SanitizerRegistry.GetRegisteredSanitizers();
}
var json = JsonSerializer.Serialize(new { Sanitizers = sanitizers });
Response.ContentType = "application/json";
Response.ContentLength = json.Length;
await Response.WriteAsync(json);
}
[HttpPost]
public async Task AddSanitizer()
{
DebugLogger.LogAdminRequestDetails(_logger, Request);
var sName = RecordingHandler.GetHeader(Request, "x-abstraction-identifier");
var recordingId = RecordingHandler.GetHeader(Request, "x-recording-id", allowNulls: true);
RecordedTestSanitizer s = (RecordedTestSanitizer)GetSanitizer(sName, await HttpRequestInteractions.GetBody(Request));
string registeredSanitizerId;
if (recordingId != null)
{
registeredSanitizerId = await _recordingHandler.RegisterSanitizer(s, recordingId);
}
else
{
registeredSanitizerId = await _recordingHandler.RegisterSanitizer(s);
}
var json = JsonSerializer.Serialize(new { Sanitizer = registeredSanitizerId });
Response.ContentType = "application/json";
Response.ContentLength = json.Length;
await Response.WriteAsync(json);
}
[HttpPost]
public async Task AddSanitizers()
{
DebugLogger.LogAdminRequestDetails(_logger, Request);
var recordingId = RecordingHandler.GetHeader(Request, "x-recording-id", allowNulls: true);
// parse all of them first, any exceptions should pop here
var workload = (await HttpRequestInteractions.GetBody<List<SanitizerBody>>(Request)).Select(s => (RecordedTestSanitizer)GetSanitizer(s.Name, s.Body)).ToList();
if (workload.Count == 0)
{
throw new HttpException(HttpStatusCode.BadRequest, "When bulk adding sanitizers, ensure there is at least one sanitizer added in each batch. Received 0 work items.");
}
// we need check if a recording id is present BEFORE the loop, as we want to encapsulate the entire
// sanitizer add operation in a single lock, rather than gathering and releasing a sanitizer lock
// for the session/recording on _each_ sanitizer addition.
var registeredSanitizers = await _recordingHandler.RegisterSanitizers(workload, recordingId);
if (recordingId != null)
{
Response.Headers.Append("x-recording-id", recordingId);
}
var json = JsonSerializer.Serialize(new { Sanitizers = registeredSanitizers });
Response.ContentType = "application/json";
Response.ContentLength = json.Length;
await Response.WriteAsync(json);
}
[HttpPost]
public async Task SetMatcher()
{
DebugLogger.LogAdminRequestDetails(_logger, Request);
var mName = RecordingHandler.GetHeader(Request, "x-abstraction-identifier");
var recordingId = RecordingHandler.GetHeader(Request, "x-recording-id", allowNulls: true);
RecordMatcher m = (RecordMatcher)GetMatcher(mName, await HttpRequestInteractions.GetBody(Request));
if (recordingId != null)
{
_recordingHandler.SetMatcherForRecording(recordingId, m);
}
else
{
_recordingHandler.Matcher = m;
}
}
[HttpPost]
public async Task SetRecordingOptions()
{
DebugLogger.LogAdminRequestDetails(_logger, Request);
var options = await HttpRequestInteractions.GetBody<Dictionary<string, object>>(Request);
var recordingId = RecordingHandler.GetHeader(Request, "x-recording-id", allowNulls: true);
_recordingHandler.SetRecordingOptions(options, recordingId);
}
public object GetSanitizer(string name, JsonDocument body)
{
return GenerateInstance("Azure.Sdk.Tools.TestProxy.Sanitizers.", name, new HashSet<string>() { "value" }, documentBody: body);
}
public object GetTransform(string name, JsonDocument body)
{
return GenerateInstance("Azure.Sdk.Tools.TestProxy.Transforms.", name, new HashSet<string>() { }, documentBody: body);
}
public object GetMatcher(string name, JsonDocument body)
{
return GenerateInstance("Azure.Sdk.Tools.TestProxy.Matchers.", name, new HashSet<string>() { }, documentBody:body);
}
private object GenerateInstance(string typePrefix, string name, HashSet<string> acceptableEmptyArgs, JsonDocument documentBody = null)
{
Type t = Type.GetType(typePrefix + name);
if (t == null)
{
throw new HttpException(HttpStatusCode.BadRequest, String.Format("Requested type {0} is not not recognized.", typePrefix + name));
}
var arg_list = new List<Object> { };
// we are deliberately assuming here that there will only be a single constructor
var ctor = t.GetConstructors()[0];
var paramsSet = ctor.GetParameters();
// walk across our constructor params. check inside the body for a resulting value for each of them
foreach (var param in paramsSet)
{
if (documentBody != null && documentBody.RootElement.TryGetProperty(param.Name, out var jsonElement))
{
if (DebugLogger.CheckLogLevel(LogLevel.Debug))
{
_logger.LogDebug("Request Body Content" + JsonSerializer.Serialize(documentBody.RootElement));
}
object argumentValue = null;
switch (jsonElement.ValueKind)
{
case JsonValueKind.Null:
case JsonValueKind.String:
argumentValue = jsonElement.GetString();
break;
case JsonValueKind.True:
case JsonValueKind.False:
argumentValue = jsonElement.GetBoolean();
break;
case JsonValueKind.Object:
try
{
argumentValue = Activator.CreateInstance(param.ParameterType, new List<object> { jsonElement }.ToArray());
}
catch (Exception e)
{
if (e.InnerException is HttpException)
{
throw e.InnerException;
}
else throw;
}
break;
default:
throw new HttpException(HttpStatusCode.BadRequest, $"{jsonElement.ValueKind} parameters are not supported");
}
if(argumentValue == null || (argumentValue is string stringResult && string.IsNullOrEmpty(stringResult)))
{
if (!acceptableEmptyArgs.Contains(param.Name))
{
throw new HttpException(HttpStatusCode.BadRequest, $"Parameter \"{param.Name}\" was passed with no value. Please check the request body and try again.");
}
}
arg_list.Add((object)argumentValue);
}
else
{
if (param.IsOptional)
{
arg_list.Add(param.DefaultValue);
}
else
{
throw new HttpException(HttpStatusCode.BadRequest, $"Required parameter key \"{param.Name}\" was not found in the request body.");
}
}
}
try
{
return Activator.CreateInstance(t, arg_list.ToArray());
}
catch(Exception e)
{
if (e.InnerException is HttpException)
{
throw e.InnerException;
}
else throw;
}
}
}
}