-
Notifications
You must be signed in to change notification settings - Fork 235
Expand file tree
/
Copy pathRecordingHandler.cs
More file actions
1353 lines (1135 loc) · 56.7 KB
/
RecordingHandler.cs
File metadata and controls
1353 lines (1135 loc) · 56.7 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Azure.Core;
using Azure.Sdk.Tools.TestProxy.Common;
using Azure.Sdk.Tools.TestProxy.Common.Exceptions;
using Azure.Sdk.Tools.TestProxy.Models;
using Azure.Sdk.Tools.TestProxy.Store;
using Azure.Sdk.Tools.TestProxy.Transforms;
using Azure.Sdk.Tools.TestProxy.Vendored;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Sdk.Tools.TestProxy
{
public class RecordingHandler
{
#region constructor and common variables
public string ContextDirectory;
public bool HandleRedirects = true;
private const string SkipRecordingHeaderKey = "x-recording-skip";
private const string SkipRecordingRequestBody = "request-body";
private const string SkipRecordingRequestResponse = "request-response";
public IAssetsStore Store;
public StoreResolver Resolver;
private static readonly string[] s_excludedRequestHeaders = new string[] {
// Only applies to request between client and proxy
// TODO, we need to handle this properly, there are tests that actually test proxy functionality.
"Host",
"Proxy-Connection",
};
public HttpClient BaseRedirectableClient = Startup.Insecure ?
new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = (_, _, _, _) => true })
{
Timeout = TimeSpan.FromSeconds(600),
} :
new HttpClient()
{
Timeout = TimeSpan.FromSeconds(600)
};
public HttpClient BaseRedirectlessClient = Startup.Insecure ?
new HttpClient(new HttpClientHandler() { AllowAutoRedirect = false, ServerCertificateCustomValidationCallback = (_, _, _, _) => true })
{
Timeout = TimeSpan.FromSeconds(600),
} :
new HttpClient(new HttpClientHandler() { AllowAutoRedirect = false })
{
Timeout = TimeSpan.FromSeconds(600)
};
public HttpClient RedirectlessClient;
public HttpClient RedirectableClient;
public SanitizerDictionary SanitizerRegistry = new SanitizerDictionary();
public List<ResponseTransform> Transforms { get; set; }
public RecordMatcher Matcher { get; set; }
public readonly ConcurrentDictionary<string, ModifiableRecordSession> RecordingSessions
= new ConcurrentDictionary<string, ModifiableRecordSession>();
public readonly ConcurrentDictionary<string, ModifiableRecordSession> InMemorySessions
= new ConcurrentDictionary<string, ModifiableRecordSession>();
public readonly ConcurrentDictionary<string, ModifiableRecordSession> PlaybackSessions
= new ConcurrentDictionary<string, ModifiableRecordSession>();
public readonly ConcurrentDictionary<string, ConcurrentQueue<AuditLogItem>> AuditSessions
= new ConcurrentDictionary<string, ConcurrentQueue<AuditLogItem>>();
/// <summary>
/// This exists to grab any sessions that might be ongoing. I don't have any evidence that sessions are being left behind, but
/// we have to have this to be certain!
/// </summary>
/// <returns></returns>
public List<ConcurrentQueue<AuditLogItem>> RetrieveOngoingAuditLogs()
{
List<ConcurrentQueue<AuditLogItem>> results = new List<ConcurrentQueue<AuditLogItem>>();
if (PlaybackSessions.Keys.Any())
{
foreach(var value in PlaybackSessions.Values)
{
results.Add(value.AuditLog);
}
}
if (RecordingSessions.Keys.Any())
{
foreach (var value in RecordingSessions.Values)
{
results.Add(value.AuditLog);
}
}
if (InMemorySessions.Keys.Any())
{
foreach (var value in InMemorySessions.Values)
{
results.Add(value.AuditLog);
}
}
return results;
}
public RecordingHandler(string targetDirectory, IAssetsStore store = null, StoreResolver storeResolver = null)
{
ContextDirectory = targetDirectory;
SetDefaultExtensions().Wait();
Store = store;
if (store == null)
{
Store = new NullStore();
}
Resolver = storeResolver;
if (Resolver == null)
{
Resolver = new StoreResolver();
}
}
#endregion
#region recording functionality
public async Task StopRecording(string sessionId, IDictionary<string, string> variables = null, bool saveRecording = true)
{
var id = Guid.NewGuid().ToString();
DebugLogger.LogTrace($"RECORD STOP BEGIN {id}.");
if (!RecordingSessions.TryRemove(sessionId, out var recordingSession))
{
return;
}
recordingSession.AuditLog.Enqueue(new AuditLogItem(sessionId, $"Stopping recording for {sessionId}."));
if (!AuditSessions.TryAdd(sessionId, recordingSession.AuditLog))
{
DebugLogger.LogError($"Unable to save audit log for {sessionId}");
}
var sanitizers = await SanitizerRegistry.GetSanitizers(recordingSession);
await recordingSession.Session.Sanitize(sanitizers);
if (variables != null)
{
foreach (var kvp in variables)
{
recordingSession.Session.Variables[kvp.Key] = kvp.Value;
}
}
if (saveRecording)
{
if (String.IsNullOrEmpty(recordingSession.Path))
{
if (!InMemorySessions.TryAdd(sessionId, recordingSession))
{
throw new HttpException(HttpStatusCode.InternalServerError, $"Unexpectedly failed to add new in-memory session under id {sessionId}.");
}
}
else
{
// Create directories above file if they don't already exist
WriteToDisk(recordingSession);
}
}
DebugLogger.LogTrace($"RECORD STOP END {id}.");
}
public void WriteToDisk(ModifiableRecordSession recordingSession)
{
// Create directories above file if they don't already exist
var directory = Path.GetDirectoryName(recordingSession.Path);
if (!String.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}
using var stream = System.IO.File.Create(recordingSession.Path);
var options = new JsonWriterOptions { Indented = true, Encoder = RecordEntry.WriterOptions.Encoder };
var writer = new Utf8JsonWriter(stream, options);
recordingSession.Session.Serialize(writer);
writer.Flush();
stream.Write(Encoding.UTF8.GetBytes(Environment.NewLine));
}
/// <summary>
/// Entrypoint handling an an optional parameter assets.json. If present, a restore option either MUST run or MAY run depending on if we're running in playback or adding new recordings.
/// </summary>
/// <param name="assetsJson">The absolute path to the targeted assets.json.</param>
/// <param name="forceCheckout">If this is set to true, a restore MUST be run. Otherwise, we just need to ensure that the current assets Tag is selected.</param>
/// <returns></returns>
private async Task RestoreAssetsJson(string assetsJson = null, bool forceCheckout = false)
{
if (!string.IsNullOrWhiteSpace(assetsJson))
{
await this.Store.Restore(assetsJson);
}
}
public async Task StartRecordingAsync(string sessionId, HttpResponse outgoingResponse, string assetsJson = null)
{
var id = Guid.NewGuid().ToString();
DebugLogger.LogTrace($"RECORD START BEGIN {id}.");
var auditEntry = new AuditLogItem(id, $"Starting record for path {sessionId}, which will return recordingId {id}.");
await RestoreAssetsJson(assetsJson, false);
var session = new ModifiableRecordSession(new RecordSession(), SanitizerRegistry, id)
{
Path = !string.IsNullOrWhiteSpace(sessionId) ? (await GetRecordingPath(sessionId, assetsJson)) : String.Empty,
Client = null
};
session.AuditLog.Enqueue(auditEntry);
if (!RecordingSessions.TryAdd(id, session))
{
throw new HttpException(HttpStatusCode.InternalServerError, $"Unexpectedly failed to add new recording session under id {id}.");
}
DebugLogger.LogTrace($"RECORD START END {id}.");
outgoingResponse.Headers.Append("x-recording-id", id);
}
public async Task HandleRecordRequestAsync(string recordingId, HttpRequest incomingRequest, HttpResponse outgoingResponse)
{
if (!RecordingSessions.TryGetValue(recordingId, out var session))
{
throw new HttpException(HttpStatusCode.BadRequest, $"There is no active recording session under id {recordingId}.");
}
RecordEntry noBodyEntry = RecordingHandler.CreateNoBodyRecordEntry(incomingRequest);
session.AuditLog.Enqueue(new AuditLogItem(recordingId, noBodyEntry.RequestUri, noBodyEntry.RequestMethod.ToString()));
var sanitizers = await SanitizerRegistry.GetSanitizers(session);
DebugLogger.LogRequestDetails(incomingRequest, sanitizers);
(RecordEntry entry, byte[] requestBody) = await CreateEntryAsync(incomingRequest).ConfigureAwait(false);
var upstreamRequest = CreateUpstreamRequest(incomingRequest, requestBody);
HttpResponseMessage upstreamResponse = null;
// The experience around Content-Length is a bit weird in .NET. We're using the .NET native HttpClient class to send our requests. This comes with
// some automagic.
//
// If an incoming request...
// ...has a Content-Length 0 header, and no body. We should send along the Content-Length: 0 header with the upstreamrequest.
// ...has no Content-Length header, and no body. We _should not_ send along the Content-Length: 0 header.
// ...has no Content-Length header, a 0 length body, but a TransferEncoding header with value "chunked". We _should_ allow any other Content headers to stick around.
//
// The .NET http client is a bit weird about attaching the Content-Length header though. If you HAVE the .Content property defined, a Content-Length
// header WILL be added. This is due to the fact that on send, the client considers a populated Client property as having a body, even if it's zero length.
if (incomingRequest.ContentLength == null)
{
if(!incomingRequest.Headers["Transfer-Encoding"].ToString().Split(' ').Select(x => x.Trim()).Contains("chunked"))
{
upstreamRequest.Content = null;
}
}
if (HandleRedirects)
{
upstreamResponse = await (session.Client ?? RedirectableClient).SendAsync(upstreamRequest).ConfigureAwait(false);
}
else
{
upstreamResponse = await (session.Client ?? RedirectlessClient).SendAsync(upstreamRequest).ConfigureAwait(false);
}
byte[] body = Array.Empty<byte>();
// HEAD requests do NOT have a body regardless of the value of the Content-Length header
if (incomingRequest.Method.ToUpperInvariant() != "HEAD")
{
body = CompressionUtilities.DecompressBody((MemoryStream)await upstreamResponse.Content.ReadAsStreamAsync().ConfigureAwait(false), upstreamResponse.Content.Headers);
}
entry.Response.Body = body.Length == 0 ? null : body;
entry.StatusCode = (int)upstreamResponse.StatusCode;
EntryRecordMode mode = GetRecordMode(incomingRequest);
if (mode != EntryRecordMode.DontRecord)
{
await session.Session.EntryLock.WaitAsync();
try
{
session.AuditLog.Enqueue(new AuditLogItem(recordingId, $"Lock obtained. Adding entry {entry.RequestMethod} {entry.RequestUri} to session {recordingId}."));
session.Session.Entries.Add(entry);
}
finally
{
session.Session.EntryLock.Release();
}
Interlocked.Increment(ref Startup.RequestsRecorded);
}
if (mode == EntryRecordMode.RecordWithoutRequestBody)
{
entry.Request.Body = null;
}
outgoingResponse.StatusCode = (int)upstreamResponse.StatusCode;
foreach (var header in upstreamResponse.Headers.Concat(upstreamResponse.Content.Headers))
{
var values = new StringValues(header.Value.ToArray());
outgoingResponse.Headers.Append(header.Key, values);
entry.Response.Headers.Add(header.Key, values);
}
outgoingResponse.Headers.Remove("Transfer-Encoding");
if (entry.Response.Body?.Length > 0)
{
var bodyData = CompressionUtilities.CompressBody(entry.Response.Body, entry.Response.Headers);
if (entry.Response.Headers.ContainsKey("Content-Length")){
outgoingResponse.ContentLength = bodyData.Length;
}
await outgoingResponse.Body.WriteAsync(bodyData).ConfigureAwait(false);
}
}
public static EntryRecordMode GetRecordMode(HttpRequest request)
{
EntryRecordMode mode = EntryRecordMode.Record;
if (request.Headers.TryGetValue(SkipRecordingHeaderKey, out var values))
{
if (values.Count != 1)
{
throw new HttpException(
HttpStatusCode.BadRequest,
$"'{SkipRecordingHeaderKey}' should contain a single value set to either '{SkipRecordingRequestBody}' or " +
$"'{SkipRecordingRequestResponse}'");
}
string skipMode = values.First();
if (skipMode.Equals(SkipRecordingRequestResponse, StringComparison.OrdinalIgnoreCase))
{
mode = EntryRecordMode.DontRecord;
}
else if (skipMode.Equals(SkipRecordingRequestBody, StringComparison.OrdinalIgnoreCase))
{
mode = EntryRecordMode.RecordWithoutRequestBody;
}
else
{
throw new HttpException(
HttpStatusCode.BadRequest,
$"{skipMode} is not a supported value for header '{SkipRecordingHeaderKey}'." +
$"It should be either omitted from the request headers, or set to either '{SkipRecordingRequestBody}' " +
$"or '{SkipRecordingRequestResponse}'");
}
}
return mode;
}
public HttpRequestMessage CreateUpstreamRequest(HttpRequest incomingRequest, byte[] incomingBody)
{
var upstreamRequest = new HttpRequestMessage();
upstreamRequest.RequestUri = GetRequestUri(incomingRequest);
upstreamRequest.Method = new HttpMethod(incomingRequest.Method);
upstreamRequest.Content = new ReadOnlyMemoryContent(incomingBody);
foreach (var header in incomingRequest.Headers)
{
IEnumerable<string> values = header.Value;
// can't handle PROXY_CONNECTION right now.
if (s_excludedRequestHeaders.Contains(header.Key, StringComparer.OrdinalIgnoreCase))
{
continue;
}
if (!header.Key.StartsWith("x-recording"))
{
if (upstreamRequest.Headers.TryAddWithoutValidation(header.Key, values))
{
continue;
}
if (!upstreamRequest.Content.Headers.TryAddWithoutValidation(header.Key, values))
{
throw new HttpException(
HttpStatusCode.BadRequest,
$"Encountered an unexpected exception while mapping a content header during upstreamRequest creation. Header: \"{header.Key}\". Value: \"{String.Join(",", values)}\""
);
}
}
if (header.Key == "x-recording-upstream-host-header")
{
upstreamRequest.Headers.Host = header.Value;
}
}
return upstreamRequest;
}
#endregion
#region playback functionality
public async Task StartPlaybackAsync(string sessionId, HttpResponse outgoingResponse, RecordingType mode = RecordingType.FilePersisted, string assetsPath = null)
{
var id = Guid.NewGuid().ToString();
DebugLogger.LogTrace($"PLAYBACK START BEGIN {id}.");
ModifiableRecordSession session = new ModifiableRecordSession(SanitizerRegistry, id);
var auditEntry = new AuditLogItem(id, $"Starting playback for path {sessionId}, which will return recordingId {id}.");
if (mode == RecordingType.InMemory)
{
if (!InMemorySessions.TryGetValue(sessionId, out session))
{
throw new HttpException(HttpStatusCode.BadRequest, $"There is no in-memory session with id {sessionId} available for playback retrieval.");
}
session.SourceRecordingId = sessionId;
}
else
{
await RestoreAssetsJson(assetsPath, true);
var path = await GetRecordingPath(sessionId, assetsPath);
var base64path = Convert.ToBase64String(Encoding.UTF8.GetBytes(path));
outgoingResponse.Headers.Append("x-base64-recording-file-location", base64path);
if (!File.Exists(path))
{
throw new TestRecordingMismatchException($"Recording file path {path} does not exist.");
}
using var stream = System.IO.File.OpenRead(path);
using var doc = await JsonDocument.ParseAsync(stream).ConfigureAwait(false);
session = new ModifiableRecordSession(RecordSession.Deserialize(doc.RootElement), SanitizerRegistry, id)
{
Path = path
};
session.AuditLog.Enqueue(auditEntry);
}
if (!PlaybackSessions.TryAdd(id, session))
{
throw new HttpException(HttpStatusCode.InternalServerError, $"Unexpectedly failed to add new playback session under id {id}.");
}
outgoingResponse.Headers.Append("x-recording-id", id);
var json = JsonSerializer.Serialize(session.Session.Variables);
outgoingResponse.Headers.Append("Content-Type", "application/json");
// Write to the response
await outgoingResponse.WriteAsync(json);
DebugLogger.LogTrace($"PLAYBACK START END {id}.");
}
public async Task StopPlayback(string recordingId, bool purgeMemoryStore = false)
{
var id = Guid.NewGuid().ToString();
DebugLogger.LogTrace($"PLAYBACK STOP BEGIN {id}.");
// obtain the playbacksession so we can get grab a lock on it. if there is a streaming response we will HAVE TO WAIT for that to complete
// before we finish
if (!PlaybackSessions.TryGetValue(recordingId, out var session))
{
throw new HttpException(HttpStatusCode.BadRequest, $"There is no active playback session under recording id {recordingId}.");
}
await session.Session.EntryLock.WaitAsync();
try
{
if (!PlaybackSessions.TryRemove(recordingId, out var removedSession))
{
throw new HttpException(HttpStatusCode.BadRequest, $"There is no active playback session under recording id {recordingId}.");
}
session.AuditLog.Enqueue(new AuditLogItem(recordingId, $"Lock obtained, stopping playback for {recordingId}."));
if (!AuditSessions.TryAdd(recordingId, session.AuditLog))
{
DebugLogger.LogError($"Unable to save audit log for {recordingId}");
}
if (!String.IsNullOrEmpty(session.SourceRecordingId) && purgeMemoryStore)
{
if (!InMemorySessions.TryRemove(session.SourceRecordingId, out var inMemorySession))
{
throw new HttpException(HttpStatusCode.InternalServerError, $"Unexpectedly failed to remove in-memory session {session.SourceRecordingId}.");
}
Interlocked.Add(ref Startup.RequestsRecorded, -1 * inMemorySession.Session.Entries.Count);
GC.Collect();
}
DebugLogger.LogTrace($"PLAYBACK STOP END {id}.");
}
finally
{
session.Session.EntryLock.Release();
}
}
public async Task HandlePlaybackRequest(string recordingId, HttpRequest incomingRequest, HttpResponse outgoingResponse)
{
if (!PlaybackSessions.TryGetValue(recordingId, out var session))
{
throw new HttpException(HttpStatusCode.BadRequest, $"There is no active playback session under recording id {recordingId}.");
}
RecordEntry noBodyEntry = RecordingHandler.CreateNoBodyRecordEntry(incomingRequest);
session.AuditLog.Enqueue(new AuditLogItem(recordingId, noBodyEntry.RequestUri, noBodyEntry.RequestMethod.ToString()));
var sanitizers = await SanitizerRegistry.GetSanitizers(session);
if (!session.IsSanitized)
{
// we don't need to re-sanitize with recording-applicable sanitizers every time. just the very first one
await session.Session.EntryLock.WaitAsync();
try
{
if (!session.IsSanitized)
{
session.AuditLog.Enqueue(new AuditLogItem(recordingId, $"In 'one-time' sanitization for {recordingId}. I am applying {sanitizers.Count} sanitizers."));
await session.Session.Sanitize(sanitizers, false);
session.IsSanitized = true;
}
}
finally
{
session.Session.EntryLock.Release();
session.AuditLog.Enqueue(new AuditLogItem(recordingId, $"Finished 'one-time' sanitization for {recordingId}. I applied {sanitizers.Count} sanitizers."));
}
}
DebugLogger.LogRequestDetails(incomingRequest, sanitizers);
var entry = (await CreateEntryAsync(incomingRequest).ConfigureAwait(false)).Item1;
await session.Session.EntryLock.WaitAsync();
try
{
// Session may be removed later, but only after response has been fully written
var match = session.Session.Lookup(entry, session.CustomMatcher ?? Matcher, sanitizers, remove: false, sessionId: recordingId);
foreach (ResponseTransform transform in Transforms.Concat(session.AdditionalTransforms))
{
transform.Transform(incomingRequest, match);
}
outgoingResponse.StatusCode = match.StatusCode;
foreach (var header in match.Response.Headers)
{
outgoingResponse.Headers.Append(header.Key, header.Value.ToArray());
}
outgoingResponse.Headers.Remove("Transfer-Encoding");
if (match.Response.Body?.Length > 0)
{
var bodyData = CompressionUtilities.CompressBody(match.Response.Body, match.Response.Headers);
if (match.Response.Headers.ContainsKey("Content-Length"))
{
outgoingResponse.ContentLength = bodyData.Length;
}
session.AuditLog.Enqueue(new AuditLogItem(recordingId, $"Beginning body write for {recordingId}."));
await WriteBodyBytes(bodyData, session.PlaybackResponseTime, outgoingResponse);
}
Interlocked.Increment(ref Startup.RequestsPlayedBack);
// Only remove session once body has been written, to minimize probability client retries but test-proxy has already removed the session
var remove = true;
// If request contains "x-recording-remove: false", then request is not removed from session after playback.
// Used by perf tests to play back the same request multiple times.
if (incomingRequest.Headers.TryGetValue("x-recording-remove", out var removeHeader))
{
remove = bool.Parse(removeHeader);
}
if (remove)
{
session.AuditLog.Enqueue(new AuditLogItem(recordingId, $"Now popping entry {entry.RequestMethod} {match.RequestUri} from entries for {recordingId}."));
await session.Session.Remove(match, shouldLock: false);
}
}
finally
{
session.Session.EntryLock.Release();
}
}
public byte[][] GetBatches(byte[] bodyData, int batchCount)
{
if (bodyData.Length == 0 || bodyData.Length < batchCount)
{
var result = new byte[1][];
result[0] = bodyData;
return result;
}
int chunkLength = bodyData.Length / batchCount;
int remainder = (bodyData.Length % batchCount);
var batches = new byte[batchCount + (remainder > 0 ? 1 : 0)][];
for(int i = 0; i < batches.Length; i++)
{
var calculatedChunkLength = ((i == batches.Length - 1) && (batches.Length > 1) && (remainder > 0)) ? remainder : chunkLength;
var batch = new byte[calculatedChunkLength];
Array.Copy(bodyData, i * chunkLength, batch, 0, calculatedChunkLength);
batches[i] = batch;
}
return batches;
}
public async Task WriteBodyBytes(byte[] bodyData, int playbackResponseTime, HttpResponse outgoingResponse)
{
if (playbackResponseTime > 0)
{
int batchCount = 10;
int sleepLength = playbackResponseTime / batchCount;
byte[][] chunks = GetBatches(bodyData, batchCount);
for(int i = 0; i < chunks.Length; i++)
{
var chunk = chunks[i];
await outgoingResponse.Body.WriteAsync(chunk).ConfigureAwait(false);
if (i != chunks.Length - 1)
{
await Task.Delay(sleepLength);
}
}
}
else
{
await outgoingResponse.Body.WriteAsync(bodyData).ConfigureAwait(false);
}
}
public static async Task<(RecordEntry, byte[])> CreateEntryAsync(HttpRequest request)
{
var entry = CreateNoBodyRecordEntry(request);
byte[] bytes = await ReadAllBytes(request.Body).ConfigureAwait(false);
entry.Request.Body = CompressionUtilities.DecompressBody(bytes, request.Headers);
return (entry, bytes);
}
public static RecordEntry CreateNoBodyRecordEntry(HttpRequest request)
{
var entry = new RecordEntry();
entry.RequestUri = GetRequestUri(request).AbsoluteUri;
entry.RequestMethod = new RequestMethod(request.Method);
foreach (var header in request.Headers)
{
if (IncludeHeader(header.Key))
{
entry.Request.Headers.Add(header.Key, header.Value.ToArray());
}
}
return entry;
}
#endregion
#region SetRecordingOptions and store functionality
public static string GetAssetsJsonLocation(string pathToAssetsJson, string contextDirectory)
{
if (pathToAssetsJson == null)
{
return null;
}
var path = pathToAssetsJson;
if (!Path.IsPathFullyQualified(pathToAssetsJson))
{
path = Path.Join(contextDirectory, pathToAssetsJson);
}
return path.Replace("\\", "/");
}
public async Task Restore(string pathToAssetsJson)
{
var resultingPath = await Store.Restore(pathToAssetsJson);
ContextDirectory = resultingPath;
}
public void SetRecordingOptions(IDictionary<string, object> options = null, string sessionId = null)
{
if (options != null)
{
if (options.Keys.Count == 0)
{
throw new HttpException(HttpStatusCode.BadRequest, "At least one key is expected in the body being passed to SetRecordingOptions.");
}
if (options.TryGetValue("HandleRedirects", out var handleRedirectsObj))
{
var handleRedirectsString = $"{handleRedirectsObj}";
if (bool.TryParse(handleRedirectsString, out var handleRedirectsBool))
{
HandleRedirects = handleRedirectsBool;
}
else if (handleRedirectsString.Equals("0", StringComparison.OrdinalIgnoreCase))
{
HandleRedirects = false;
}
else if (handleRedirectsString.Equals("1", StringComparison.OrdinalIgnoreCase))
{
HandleRedirects = true;
}
else
{
throw new HttpException(HttpStatusCode.BadRequest, $"The value of key \"HandleRedirects\" MUST be castable to a valid boolean value. Unparsable Value: \"{handleRedirectsString}\".");
}
}
if (options.TryGetValue("ContextDirectory", out var sourceDirectoryObj))
{
var newSourceDirectory = sourceDirectoryObj.ToString();
if (!string.IsNullOrWhiteSpace(newSourceDirectory))
{
SetRecordingDirectory(newSourceDirectory);
}
else
{
throw new HttpException(HttpStatusCode.BadRequest, "Users must provide a valid value to the key \"ContextDirectory\" in the recording options dictionary.");
}
}
if (options.TryGetValue("AssetsStore", out var assetsStoreObj))
{
var newAssetsStoreIdentifier = assetsStoreObj.ToString();
if (!string.IsNullOrWhiteSpace(newAssetsStoreIdentifier))
{
SetAssetsStore(newAssetsStoreIdentifier);
}
else
{
throw new HttpException(HttpStatusCode.BadRequest, "Users must provide a valid value when providing the key \"AssetsStore\" in the recording options dictionary.");
}
}
if (options.TryGetValue("Transport", out var transportConventions))
{
if (transportConventions != null)
{
try
{
string transportObject;
if (transportConventions is JsonElement je)
{
transportObject = je.ToString();
}
else
{
throw new Exception("'Transport' object was not a JsonElement");
}
var serializerOptions = new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
var customizations = JsonSerializer.Deserialize<TransportCustomizations>(transportObject, serializerOptions);
SetTransportOptions(customizations, sessionId);
}
catch (HttpException)
{
throw;
}
catch (Exception e)
{
throw new HttpException(HttpStatusCode.BadRequest, $"Unable to deserialize the contents of the \"Transport\" key. Visible object: {transportConventions}. Json Deserialization Error: {e.Message}");
}
}
else
{
throw new HttpException(HttpStatusCode.BadRequest, "Users must provide a valid value when providing the key \"Transport\" in the recording options dictionary.");
}
}
}
else
{
throw new HttpException(HttpStatusCode.BadRequest, "When setting recording options, the request body is expected to be non-null and of type Dictionary<string, string>.");
}
}
public X509Certificate2 GetValidationCert(TransportCustomizations settings)
{
try
{
var span = new ReadOnlySpan<char>(settings.TLSValidationCert.ToCharArray());
return PemReader.LoadCertificate(span, null, PemReader.KeyType.Auto, true);
}
catch (Exception e)
{
throw new HttpException(HttpStatusCode.BadRequest, $"Unable to instantiate a valid cert from the value provided in Transport settings key \"TLSValidationCert\". Value: \"{settings.TLSValidationCert}\". Message: \"{e.Message}\".");
}
}
public HttpClientHandler GetTransport(bool allowAutoRedirect, TransportCustomizations customizations, bool insecure = false)
{
var clientHandler = new HttpClientHandler()
{
AllowAutoRedirect = allowAutoRedirect
};
if (customizations.Certificates != null)
{
foreach (var certPair in customizations.Certificates)
{
try
{
var cert = X509Certificate2.CreateFromPem(certPair.PemValue, certPair.PemKey);
cert = new X509Certificate2(cert.Export(X509ContentType.Pfx));
clientHandler.ClientCertificates.Add(cert);
}
catch (Exception e)
{
throw new HttpException(HttpStatusCode.BadRequest, $"Unable to instantiate a new X509 certificate from the provided value and key. Failure Message: \"{e.Message}\".");
}
}
}
if (customizations.TLSValidationCert != null && !insecure)
{
var ledgerCert = GetValidationCert(customizations);
X509Chain certificateChain = new();
certificateChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
certificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
certificateChain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
certificateChain.ChainPolicy.VerificationTime = DateTime.Now;
certificateChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);
certificateChain.ChainPolicy.ExtraStore.Add(ledgerCert);
clientHandler.ServerCertificateCustomValidationCallback = (HttpRequestMessage httpRequestMessage, X509Certificate2 cert, X509Chain x509Chain, SslPolicyErrors sslPolicyErrors) =>
{
if (!string.IsNullOrWhiteSpace(customizations.TSLValidationCertHost) && httpRequestMessage.RequestUri.Host != customizations.TSLValidationCertHost)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
return false;
}
else
{
bool isChainValid = certificateChain.Build(cert);
if (!isChainValid) return false;
var isCertSignedByTheTlsCert = certificateChain.ChainElements.Cast<X509ChainElement>()
.Any(x => x.Certificate.Thumbprint == ledgerCert.Thumbprint);
return isCertSignedByTheTlsCert;
}
};
}
else if (insecure)
{
clientHandler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
}
return clientHandler;
}
public void SetTransportOptions(TransportCustomizations customizations, string sessionId)
{
var timeoutSpan = TimeSpan.FromSeconds(600);
// this will look a bit strange until we take care of #3488 due to the fact that this AllowAutoRedirect customizable from two places
if (!string.IsNullOrWhiteSpace(sessionId))
{
var customizedClientHandler = GetTransport(customizations.AllowAutoRedirect, customizations);
if (RecordingSessions.TryGetValue(sessionId, out var recordingSession))
{
recordingSession.Client = new HttpClient(customizedClientHandler)
{
Timeout = timeoutSpan
};
}
if (customizations.PlaybackResponseTime > 0)
{
if (PlaybackSessions.TryGetValue(sessionId, out var playbackSession))
{
playbackSession.PlaybackResponseTime = customizations.PlaybackResponseTime;
}
else
{
throw new HttpException(HttpStatusCode.BadRequest, $"Unable to set a transport customization on a recording session that is not active. Id: \"{sessionId}\"");
}
}
}
else
{
// after #3488 we will swap to a single client instead of both of these
var redirectableCustomizedHandler = GetTransport(true, customizations, Startup.Insecure);
var redirectlessCustomizedHandler = GetTransport(false, customizations, Startup.Insecure);
RedirectableClient = new HttpClient(redirectableCustomizedHandler)
{
Timeout = timeoutSpan
};
RedirectlessClient = new HttpClient(redirectlessCustomizedHandler)
{
Timeout = timeoutSpan
};
}
}
public void SetAssetsStore(string assetsStoreId)
{
Store = Resolver.ResolveStore(assetsStoreId);
}
public void SetRecordingDirectory(string targetDirectory)
{
try
{
// Given that it is perfectly valid to pass a directory that does not yet exist, we cannot get the file attributes to "properly"
// determine if an incoming path is a valid one via <attr>.HasFlag(FileAttributes.Directory). We can shorthand this by checking
// for a file extension.
if (Path.GetExtension(targetDirectory) != String.Empty)
{
targetDirectory = Path.GetDirectoryName(targetDirectory);
}
if (!String.IsNullOrEmpty(targetDirectory))
{
Directory.CreateDirectory(targetDirectory);
}
ContextDirectory = targetDirectory;
}
catch (Exception ex)
{
throw new HttpException(HttpStatusCode.BadRequest, $"Unable set proxy context to target directory \"{targetDirectory}\". Unhandled exception was: \"{ex.Message}\".");
}
}
#endregion
#region utility and common-use functions
public ModifiableRecordSession GetActiveSession(string recordingId)
{
if (PlaybackSessions.TryGetValue(recordingId, out var playbackSession))