-
Notifications
You must be signed in to change notification settings - Fork 331
Expand file tree
/
Copy pathConfigurationTests.cs
More file actions
6666 lines (5867 loc) · 355 KB
/
ConfigurationTests.cs
File metadata and controls
6666 lines (5867 loc) · 355 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.IO.Abstractions;
using System.IO.Abstractions.TestingHelpers;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Azure.DataApiBuilder.Auth;
using Azure.DataApiBuilder.Config;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core;
using Azure.DataApiBuilder.Core.AuthenticationHelpers;
using Azure.DataApiBuilder.Core.Authorization;
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Core.Models;
using Azure.DataApiBuilder.Core.Parsers;
using Azure.DataApiBuilder.Core.Resolvers;
using Azure.DataApiBuilder.Core.Resolvers.Factories;
using Azure.DataApiBuilder.Core.Services;
using Azure.DataApiBuilder.Core.Services.MetadataProviders;
using Azure.DataApiBuilder.Product;
using Azure.DataApiBuilder.Service.Controllers;
using Azure.DataApiBuilder.Service.Exceptions;
using Azure.DataApiBuilder.Service.HealthCheck;
using Azure.DataApiBuilder.Service.Tests.Authorization;
using Azure.DataApiBuilder.Service.Tests.OpenApiIntegration;
using Azure.DataApiBuilder.Service.Tests.SqlTests;
using HotChocolate;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Moq.Protected;
using Serilog;
using VerifyMSTest;
using static Azure.DataApiBuilder.Config.FileSystemRuntimeConfigLoader;
using static Azure.DataApiBuilder.Core.AuthenticationHelpers.AppServiceAuthentication;
using static Azure.DataApiBuilder.Service.Tests.Configuration.ConfigurationEndpoints;
using static Azure.DataApiBuilder.Service.Tests.Configuration.TestConfigFileReader;
namespace Azure.DataApiBuilder.Service.Tests.Configuration
{
[TestClass]
public class ConfigurationTests
: VerifyBase
{
private const string COSMOS_ENVIRONMENT = TestCategory.COSMOSDBNOSQL;
private const string MSSQL_ENVIRONMENT = TestCategory.MSSQL;
private const string MYSQL_ENVIRONMENT = TestCategory.MYSQL;
private const string POSTGRESQL_ENVIRONMENT = TestCategory.POSTGRESQL;
private const string POST_STARTUP_CONFIG_ENTITY = "Book";
private const string POST_STARTUP_CONFIG_ENTITY_SOURCE = "books";
private const string POST_STARTUP_CONFIG_ROLE = "PostStartupConfigRole";
private const string COSMOS_DATABASE_NAME = "config_db";
private const string CUSTOM_CONFIG_FILENAME = "custom-config.json";
private const string OPENAPI_SWAGGER_ENDPOINT = "swagger";
private const string OPENAPI_DOCUMENT_ENDPOINT = "openapi";
private const string BROWSER_USER_AGENT_HEADER = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36";
private const string BROWSER_ACCEPT_HEADER = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
private const int RETRY_COUNT = 5;
private const int RETRY_WAIT_SECONDS = 2;
/// <summary>
///
/// </summary>
public const string BOOK_ENTITY_JSON = @"
{
""entities"": {
""Book"": {
""source"": {
""object"": ""books"",
""type"": ""table""
},
""graphql"": {
""enabled"": true,
""type"": {
""singular"": ""book"",
""plural"": ""books""
}
},
""rest"":{
""enabled"": true
},
""permissions"": [
{
""role"": ""anonymous"",
""actions"": [
{
""action"": ""read""
}
]
}
],
""mappings"": null,
""relationships"": null
}
}
}";
/// <summary>
/// A valid REST API request body with correct parameter types for all the fields.
/// </summary>
public const string REQUEST_BODY_WITH_CORRECT_PARAM_TYPES = @"
{
""title"": ""New book"",
""publisher_id"": 1234
}
";
/// <summary>
/// An invalid REST API request body with incorrect parameter type for publisher_id field.
/// </summary>
public const string REQUEST_BODY_WITH_INCORRECT_PARAM_TYPES = @"
{
""title"": ""New book"",
""publisher_id"": ""one""
}
";
/// <summary>
/// A config file with SP entity with no REST section defined.
/// This config string is used for validating the REST HTTP methods that are enabled.
/// </summary>
public const string SP_CONFIG_WITH_NO_REST_SETTINGS = @"
{
""entities"": {
""GetBooks"": {
""source"": {
""object"": ""get_books"",
""type"": ""stored-procedure"",
""parameters"": null,
""key-fields"": null
},
""graphql"": {
""enabled"": true,
""operation"": ""query"",
""type"": {
""singular"": ""GetBooks"",
""plural"": ""GetBooks""
}
},
""permissions"": [
{
""role"": ""anonymous"",
""actions"": [
{
""action"": ""execute"",
""fields"": null,
""policy"": {
""request"": null,
""database"": null
}
}
]
}
],
""mappings"": null,
""relationships"": null
}
}
}";
/// <summary>
/// A config file with SP entity with a custom path defined in REST section.
/// This config string is used for validating the REST HTTP methods that are enabled.
/// </summary>
public const string SP_CONFIG_WITH_ONLY_PATH_IN_REST_SETTINGS = @"
{
""entities"": {
""GetBooks"": {
""source"": {
""object"": ""get_books"",
""type"": ""stored-procedure"",
""parameters"": null,
""key-fields"": null
},
""graphql"": {
""enabled"": true,
""operation"": ""query"",
""type"": {
""singular"": ""GetBooks"",
""plural"": ""GetBooks""
}
},
""rest"":{
""path"": ""get_books""
},
""permissions"": [
{
""role"": ""anonymous"",
""actions"": [
{
""action"": ""execute"",
""fields"": null,
""policy"": {
""request"": null,
""database"": null
}
}
]
}
],
""mappings"": null,
""relationships"": null
}
}
}";
/// <summary>
/// A config file with a SP entity with the supported HTTP methods defined in REST section.
/// This config string is used for validating the REST HTTP methods that are enabled.
/// </summary>
public const string SP_CONFIG_WITH_JUST_METHODS_IN_REST_SETTINGS = @"
{
""entities"": {
""GetBooks"": {
""source"": {
""object"": ""get_books"",
""type"": ""stored-procedure"",
""parameters"": null,
""key-fields"": null
},
""graphql"": {
""enabled"": true,
""operation"": ""query"",
""type"": {
""singular"": ""GetBooks"",
""plural"": ""GetBooks""
}
},
""rest"":{
""methods"": [
""get""
]
},
""permissions"": [
{
""role"": ""anonymous"",
""actions"": [
{
""action"": ""execute"",
""fields"": null,
""policy"": {
""request"": null,
""database"": null
}
}
]
}
],
""mappings"": null,
""relationships"": null
}
}
}";
/// <summary>
/// A config file with a SP entity for which REST APIs are disabled.
/// This config string is used for validating that none of the REST methods are enabled.
/// </summary>
public const string SP_CONFIG_WITH_REST_DISABLED = @"
{
""entities"": {
""GetBooks"": {
""source"": {
""object"": ""get_books"",
""type"": ""stored-procedure"",
""parameters"": null,
""key-fields"": null
},
""graphql"": {
""enabled"": true,
""operation"": ""query"",
""type"": {
""singular"": ""GetBooks"",
""plural"": ""GetBooks""
}
},
""rest"":{
""enabled"": false
},
""permissions"": [
{
""role"": ""anonymous"",
""actions"": [
{
""action"": ""execute"",
""fields"": null,
""policy"": {
""request"": null,
""database"": null
}
}
]
}
],
""mappings"": null,
""relationships"": null
}
}
}";
/// <summary>
/// A config file with a SP entity for which REST path and methods are not explicitly configured.
/// This config string is used for validating the default REST behavior.
/// </summary>
public const string SP_CONFIG_WITH_JUST_REST_ENABLED = @"
{
""entities"": {
""GetBooks"": {
""source"": {
""object"": ""get_books"",
""type"": ""stored-procedure"",
""parameters"": null,
""key-fields"": null
},
""graphql"": {
""enabled"": true,
""operation"": ""query"",
""type"": {
""singular"": ""GetBooks"",
""plural"": ""GetBooks""
}
},
""rest"":{
""enabled"": true
},
""permissions"": [
{
""role"": ""anonymous"",
""actions"": [
{
""action"": ""execute"",
""fields"": null,
""policy"": {
""request"": null,
""database"": null
}
}
]
}
],
""mappings"": null,
""relationships"": null
}
}
}";
/// <summary>
/// Invalid properties:
/// `data-source-file` instead of `data-source-files`
/// `GraphQL` instead of `graphql` in the global runtime section.
/// `rst` instead of `rest` in the entity section.
/// </summary>
public const string CONFIG_WITH_INVALID_SCHEMA = @"
{
""data-source"": {
""database-type"": ""mssql"",
""connection-string"": ""test-connection-string""
},
""data-source-file"": [],
""runtime"": {
""rest"": {
""enabled"": true,
""path"": ""/api""
},
""Graphql"": {
""enabled"": true,
""path"": ""/graphql"",
""allow-introspection"": true
},
""host"": {
""cors"": {
""origins"": [
""http://localhost:5000""
],
""allow-credentials"": false
},
""authentication"": {
""provider"": ""AppService""
},
""mode"": ""development""
}
},
""entities"": {
""Publisher"": {
""source"": {
""object"": ""publishers"",
""type"": ""table""
},
""graphql"": {
""enabled"": true,
""type"": {
""singular"": ""Publisher"",
""plural"": ""Publishers""
}
},
""rst"": {
""enabled"": true
},
""permissions"": [
{
""role"": ""anonymous"",
""actions"": [
{
""action"": ""create""
}
]
}
]
}
}
}";
internal const string GRAPHQL_SCHEMA_WITH_CYCLE_ARRAY = @"
type Character {
id : ID,
name : String,
moons: [Moon],
}
type Planet @model(name:""PlanetAlias"") {
id : ID!,
name : String,
character: Character
}
type Moon {
id : ID,
name : String,
details : String,
character: Character
}
";
internal const string GRAPHQL_SCHEMA_WITH_CYCLE_OBJECT = @"
type Character {
id : ID,
name : String,
moons: Moon,
}
type Planet @model(name:""PlanetAlias"") {
id : ID!,
name : String,
character: Character
}
type Moon {
id : ID,
name : String,
details : String,
character: Character
}
";
public const string CONFIG_FILE_WITH_NO_OPTIONAL_FIELD = @"{
""$schema"":""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch-alpha/dab.draft.schema.json"",
""data-source"": {
""database-type"": ""mssql"",
""connection-string"": ""sample-conn-string""
},
""entities"":{ }
}";
public const string CONFIG_FILE_WITH_NO_AUTHENTICATION_FIELD = @"{
// Link for latest draft schema.
""$schema"":""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch-alpha/dab.draft.schema.json"",
""data-source"": {
""database-type"": ""mssql"",
""connection-string"": ""sample-conn-string""
},
""runtime"": {
""rest"": {
""enabled"": true,
""path"": ""/api""
},
""graphql"": {
""enabled"": true,
""path"": ""/graphql"",
""allow-introspection"": true
},
""host"": {
""cors"": {
""origins"": [
""http://localhost:5000""
],
""allow-credentials"": false
}
}
},
""entities"":{ }
}";
public const string CONFIG_FILE_WITH_UNKNOWN_AUTHENTICATION_PROVIDER = @"{
// Link for latest draft schema.
""$schema"":""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch-alpha/dab.draft.schema.json"",
""data-source"": {
""database-type"": ""mssql"",
""connection-string"": ""sample-conn-string""
},
""runtime"": {
""rest"": {
""enabled"": true,
""path"": ""/api""
},
""graphql"": {
""enabled"": true,
""path"": ""/graphql"",
""allow-introspection"": true
},
""host"": {
""cors"": {
""origins"": [
""http://localhost:5000""
],
""allow-credentials"": false
},
""authentication"": {
""provider"": ""UnknownProvider""
}
}
},
""entities"":{ }
}";
public const string CONFIG_FILE_WITH_MISSING_JWT_PROPERTY = @"{
// Link for latest draft schema.
""$schema"":""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch-alpha/dab.draft.schema.json"",
""data-source"": {
""database-type"": ""mssql"",
""connection-string"": ""sample-conn-string""
},
""runtime"": {
""rest"": {
""enabled"": true,
""path"": ""/api""
},
""graphql"": {
""enabled"": true,
""path"": ""/graphql"",
""allow-introspection"": true
},
""host"": {
""cors"": {
""origins"": [
""http://localhost:5000""
],
""allow-credentials"": false
},
""authentication"": {
""provider"": ""EntraID""
}
}
},
""entities"":{ }
}";
public const string CONFIG_FILE_WITH_MISSING_JWT_CHILD_PROPERTIES = @"{
// Link for latest draft schema.
""$schema"":""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch-alpha/dab.draft.schema.json"",
""data-source"": {
""database-type"": ""mssql"",
""connection-string"": ""sample-conn-string""
},
""runtime"": {
""rest"": {
""enabled"": true,
""path"": ""/api""
},
""graphql"": {
""enabled"": true,
""path"": ""/graphql"",
""allow-introspection"": true
},
""host"": {
""cors"": {
""origins"": [
""http://localhost:5000""
],
""allow-credentials"": false
},
""authentication"": {
""provider"": ""EntraID"",
""jwt"": { }
}
}
},
""entities"":{ }
}";
public const string CONFIG_FILE_WITH_AUTHENTICATION_PROVIDER_THAT_SHOULD_NOT_HAVE_JWT = @"{
// Link for latest draft schema.
""$schema"":""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch-alpha/dab.draft.schema.json"",
""data-source"": {
""database-type"": ""mssql"",
""connection-string"": ""sample-conn-string""
},
""runtime"": {
""rest"": {
""enabled"": true,
""path"": ""/api""
},
""graphql"": {
""enabled"": true,
""path"": ""/graphql"",
""allow-introspection"": true
},
""host"": {
""cors"": {
""origins"": [
""http://localhost:5000""
],
""allow-credentials"": false
},
""authentication"": {
""provider"": ""Simulator"",
""jwt"": { ""audience"": ""https://example.com"", ""issuer"": ""https://example.com"" }
}
}
},
""entities"":{ }
}";
public const string CONFIG_FILE_WITH_NO_CORS_FIELD = @"{
// Link for latest draft schema.
""$schema"":""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch-alpha/dab.draft.schema.json"",
""data-source"": {
""database-type"": ""mssql"",
""connection-string"": ""sample-conn-string""
},
""runtime"": {
""rest"": {
""enabled"": true,
""path"": ""/api""
},
""graphql"": {
""enabled"": true,
""path"": ""/graphql"",
""allow-introspection"": true
},
""host"": {
""authentication"": {
""provider"": ""AppService""
}
}
},
""entities"":{ }
}";
public const string CONFIG_FILE_WITH_BOOLEAN_AS_ENV = @"{
// Link for latest draft schema.
""$schema"":""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch-alpha/dab.draft.schema.json"",
""data-source"": {
""database-type"": ""mssql"",
""connection-string"": ""sample-conn-string"",
""health"": {
""enabled"": <REPLACE_VALUE>
}
},
""runtime"": {
""health"": {
""enabled"": <REPLACE_VALUE>
},
""rest"": {
""enabled"": <REPLACE_VALUE>,
""path"": ""/api""
},
""graphql"": {
""enabled"": <REPLACE_VALUE>,
""path"": ""/graphql"",
""allow-introspection"": true
},
""host"": {
""authentication"": {
""provider"": ""AppService""
}
},
""telemetry"": {
""application-insights"":{
""enabled"": <REPLACE_VALUE>,
""connection-string"":""sample-ai-connection-string""
}
}
},
""entities"":{ }
}";
[TestCleanup]
public void CleanupAfterEachTest()
{
// Retry file deletion with exponential back-off to handle cases where a
// file watcher or hot-reload process may still hold a handle on the file.
if (File.Exists(CUSTOM_CONFIG_FILENAME))
{
int retryCount = 0;
const int maxRetries = 3;
while (true)
{
try
{
File.Delete(CUSTOM_CONFIG_FILENAME);
break;
}
catch (IOException ex) when (retryCount < maxRetries)
{
retryCount++;
Console.WriteLine($"CleanupAfterEachTest: Retry {retryCount}/{maxRetries} deleting {CUSTOM_CONFIG_FILENAME}. {ex.Message}");
Thread.Sleep(TimeSpan.FromSeconds(Math.Pow(2, retryCount)));
}
}
}
TestHelper.UnsetAllDABEnvironmentVariables();
}
/// <summary>
/// When updating config during runtime is possible, then For invalid config the Application continues to
/// accept request with status code of 503.
/// But if invalid config is provided during startup, ApplicationException is thrown
/// and application exits.
/// </summary>
[DataTestMethod]
[DataRow(new string[] { }, true, DisplayName = "No config returns 503 - config file flag absent")]
[DataRow(new string[] { "--ConfigFileName=" }, true, DisplayName = "No config returns 503 - empty config file option")]
[DataRow(new string[] { }, false, DisplayName = "Throws Application exception")]
[TestMethod("Validates that queries before runtime is configured returns a 503 in hosting scenario whereas an application exception when run through CLI")]
public async Task TestNoConfigReturnsServiceUnavailable(
string[] args,
bool isUpdateableRuntimeConfig)
{
TestServer server = null;
try
{
if (isUpdateableRuntimeConfig)
{
server = new(Program.CreateWebHostFromInMemoryUpdatableConfBuilder(args));
}
else
{
server = new(Program.CreateWebHostBuilder(args));
}
HttpClient httpClient = server.CreateClient();
HttpResponseMessage result = await httpClient.GetAsync("/graphql");
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, result.StatusCode);
}
catch (Exception e)
{
Assert.IsFalse(isUpdateableRuntimeConfig);
Assert.AreEqual(typeof(ApplicationException), e.GetType());
Assert.AreEqual(
$"Could not initialize the engine with the runtime config file: {DEFAULT_CONFIG_FILE_NAME}",
e.Message);
}
finally
{
server?.Dispose();
}
}
/// <summary>
/// Verify that https redirection is disabled when --no-https-redirect flag is passed through CLI.
/// We check if IsHttpsRedirectionDisabled is set to true with --no-https-redirect flag.
/// </summary>
[DataTestMethod]
[DataRow(new string[] { "" }, false, DisplayName = "Https redirection allowed")]
[DataRow(new string[] { Startup.NO_HTTPS_REDIRECT_FLAG }, true, DisplayName = "Http redirection disabled")]
[TestMethod("Validates that https redirection is disabled when --no-https-redirect option is used when engine is started through CLI")]
public void TestDisablingHttpsRedirection(
string[] args,
bool expectedIsHttpsRedirectionDisabled)
{
Program.CreateWebHostBuilder(args).Build();
Assert.AreEqual(expectedIsHttpsRedirectionDisabled, Program.IsHttpsRedirectionDisabled);
}
/// <summary>
/// Checks correct serialization and deserialization of Source Type from
/// Enum to String and vice-versa.
/// Consider both cases for source as an object and as a string
/// </summary>
[DataTestMethod]
[DataRow(true, EntitySourceType.StoredProcedure, "stored-procedure", DisplayName = "source is a stored-procedure")]
[DataRow(true, EntitySourceType.Table, "table", DisplayName = "source is a table")]
[DataRow(true, EntitySourceType.View, "view", DisplayName = "source is a view")]
[DataRow(false, null, null, DisplayName = "source is just string")]
public void TestCorrectSerializationOfSourceObject(
bool isDatabaseObjectSource,
EntitySourceType sourceObjectType,
string sourceTypeName)
{
RuntimeConfig runtimeConfig;
if (isDatabaseObjectSource)
{
EntitySource entitySource = new(
Type: sourceObjectType,
Object: "sourceName",
Parameters: null,
KeyFields: null
);
runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: "MyEntity",
entitySource: entitySource,
roleName: "Anonymous",
operation: EntityActionOperation.All
);
}
else
{
string entitySource = "sourceName";
runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: "MyEntity",
entitySource: entitySource,
roleName: "Anonymous",
operation: EntityActionOperation.All
);
}
string runtimeConfigJson = runtimeConfig.ToJson();
if (isDatabaseObjectSource)
{
Assert.IsTrue(runtimeConfigJson.Contains(sourceTypeName));
}
Assert.IsTrue(RuntimeConfigLoader.TryParseConfig(runtimeConfigJson, out RuntimeConfig deserializedRuntimeConfig));
Assert.IsTrue(deserializedRuntimeConfig.Entities.ContainsKey("MyEntity"));
Assert.AreEqual("sourceName", deserializedRuntimeConfig.Entities["MyEntity"].Source.Object);
if (isDatabaseObjectSource)
{
Assert.AreEqual(sourceObjectType, deserializedRuntimeConfig.Entities["MyEntity"].Source.Type);
}
else
{
Assert.AreEqual(EntitySourceType.Table, deserializedRuntimeConfig.Entities["MyEntity"].Source.Type);
}
}
/// <summary>
/// Validates that DAB supplements the MSSQL database connection strings with the property "Application Name" and
/// 1. Adds the property/value "Application Name=dab_oss_Major.Minor.Patch" when the env var DAB_APP_NAME_ENV is not set.
/// 2. Adds the property/value "Application Name=dab_hosted_Major.Minor.Patch" when the env var DAB_APP_NAME_ENV is set to "dab_hosted".
/// (DAB_APP_NAME_ENV is set in hosted scenario or when user sets the value.)
/// NOTE: "#pragma warning disable format" is used here to avoid removing intentional, readability promoting spacing in DataRow display names.
/// </summary>
/// <param name="configProvidedConnString">connection string provided in the config.</param>
/// <param name="expectedDabModifiedConnString">Updated connection string with Application Name.</param>
/// <param name="dabEnvOverride">Whether DAB_APP_NAME_ENV is set in environment. (Always present in hosted scenario or if user supplies value.)</param>
#pragma warning disable format
[DataTestMethod]
[DataRow("Data Source=<>;" , "Data Source=<>;Application Name=" , false, DisplayName = "[MSSQL]: DAB adds version 'dab_oss_major_minor_patch' to non-provided connection string property 'Application Name'.")]
[DataRow("Data Source=<>;Application Name=CustAppName;" , "Data Source=<>;Application Name=CustAppName," , false, DisplayName = "[MSSQL]: DAB appends version 'dab_oss_major_minor_patch' to user supplied 'Application Name' property.")]
[DataRow("Data Source=<>;App=CustAppName;" , "Data Source=<>;Application Name=CustAppName," , false, DisplayName = "[MSSQL]: DAB appends version 'dab_oss_major_minor_patch' to user supplied 'App' property and resolves property to 'Application Name'.")]
[DataRow("Data Source=<>;" , "Data Source=<>;Application Name=" , true , DisplayName = "[MSSQL]: DAB adds DAB_APP_NAME_ENV value 'dab_hosted' and version suffix '_major_minor_patch' to non-provided connection string property 'Application Name'.")]
[DataRow("Data Source=<>;Application Name=CustAppName;" , "Data Source=<>;Application Name=CustAppName," , true , DisplayName = "[MSSQL]: DAB appends DAB_APP_NAME_ENV value 'dab_hosted' and version suffix '_major_minor_patch' to user supplied 'Application Name' property.")]
[DataRow("Data Source=<>;App=CustAppName;" , "Data Source=<>;Application Name=CustAppName," , true , DisplayName = "[MSSQL]: DAB appends version string 'dab_hosted' and version suffix '_major_minor_patch' to user supplied 'App' property and resolves property to 'Application Name'.")]
#pragma warning restore format
public void MsSqlConnStringSupplementedWithAppNameProperty(
string configProvidedConnString,
string expectedDabModifiedConnString,
bool dabEnvOverride)
{
// Explicitly set the DAB_APP_NAME_ENV to null to ensure that the DAB_APP_NAME_ENV is not set.
if (dabEnvOverride)
{
Environment.SetEnvironmentVariable(ProductInfo.DAB_APP_NAME_ENV, "dab_hosted");
}
else
{
Environment.SetEnvironmentVariable(ProductInfo.DAB_APP_NAME_ENV, null);
}
// Resolve assembly version. Not possible to do in DataRow as DataRows expect compile-time constants.
string resolvedAssemblyVersion = ProductInfo.GetDataApiBuilderUserAgent();
expectedDabModifiedConnString += resolvedAssemblyVersion;
RuntimeConfig runtimeConfig = CreateBasicRuntimeConfigWithNoEntity(DatabaseType.MSSQL, configProvidedConnString);
// Act
bool configParsed = RuntimeConfigLoader.TryParseConfig(
json: runtimeConfig.ToJson(),
config: out RuntimeConfig updatedRuntimeConfig,
replacementSettings: new(doReplaceEnvVar: true));
// Assert
Assert.AreEqual(
expected: true,
actual: configParsed,
message: "Runtime config unexpectedly failed parsing.");
Assert.AreEqual(
expected: expectedDabModifiedConnString,
actual: updatedRuntimeConfig.DataSource.ConnectionString,
message: "DAB did not properly set the 'Application Name' connection string property.");
}
/// <summary>
/// Validates that DAB supplements the PgSQL database connection strings with the property "ApplicationName" and
/// 1. Adds the property/value "Application Name=dab_oss_Major.Minor.Patch" when the env var DAB_APP_NAME_ENV is not set.
/// 2. Adds the property/value "Application Name=dab_hosted_Major.Minor.Patch" when the env var DAB_APP_NAME_ENV is set to "dab_hosted".
/// (DAB_APP_NAME_ENV is set in hosted scenario or when user sets the value.)
/// NOTE: "#pragma warning disable format" is used here to avoid removing intentional, readability promoting spacing in DataRow display names.
/// </summary>
/// <param name="configProvidedConnString">connection string provided in the config.</param>
/// <param name="expectedDabModifiedConnString">Updated connection string with Application Name.</param>
/// <param name="dabEnvOverride">Whether DAB_APP_NAME_ENV is set in environment. (Always present in hosted scenario or if user supplies value.)</param>
[DataTestMethod]
[DataRow("Host=foo;Username=testuser;", "Host=foo;Username=testuser;Application Name=", false, DisplayName = "[PGSQL]:DAB adds version 'dab_oss_major_minor_patch' to non-provided connection string property 'ApplicationName']")]
[DataRow("Host=foo;Username=testuser;", "Host=foo;Username=testuser;Application Name=", true, DisplayName = "[PGSQL]:DAB adds DAB_APP_NAME_ENV value 'dab_hosted' and version suffix '_major_minor_patch' to non-provided connection string property 'ApplicationName'.]")]
[DataRow("Host=foo;Username=testuser;Application Name=UserAppName", "Host=foo;Username=testuser;Application Name=UserAppName,", false, DisplayName = "[PGSQL]:DAB appends version 'dab_oss_major_minor_patch' to user supplied 'Application Name' property.]")]
[DataRow("Host=foo;Username=testuser;Application Name=UserAppName", "Host=foo;Username=testuser;Application Name=UserAppName,", true, DisplayName = "[PGSQL]:DAB appends version string 'dab_hosted' and version suffix '_major_minor_patch' to user supplied 'ApplicationName' property.]")]
public void PgSqlConnStringSupplementedWithAppNameProperty(
string configProvidedConnString,
string expectedDabModifiedConnString,
bool dabEnvOverride)
{
// Explicitly set the DAB_APP_NAME_ENV to null to ensure that the DAB_APP_NAME_ENV is not set.
if (dabEnvOverride)
{
Environment.SetEnvironmentVariable(ProductInfo.DAB_APP_NAME_ENV, "dab_hosted");
}
else
{
Environment.SetEnvironmentVariable(ProductInfo.DAB_APP_NAME_ENV, null);
}
// Resolve assembly version. Not possible to do in DataRow as DataRows expect compile-time constants.
string resolvedAssemblyVersion = ProductInfo.GetDataApiBuilderUserAgent();
expectedDabModifiedConnString += resolvedAssemblyVersion;
RuntimeConfig runtimeConfig = CreateBasicRuntimeConfigWithNoEntity(DatabaseType.PostgreSQL, configProvidedConnString);
// Act
bool configParsed = RuntimeConfigLoader.TryParseConfig(
json: runtimeConfig.ToJson(),
config: out RuntimeConfig updatedRuntimeConfig,
replacementSettings: new(doReplaceEnvVar: true));
// Assert
Assert.AreEqual(
expected: true,
actual: configParsed,
message: "Runtime config unexpectedly failed parsing.");
Assert.AreEqual(
expected: expectedDabModifiedConnString,
actual: updatedRuntimeConfig.DataSource.ConnectionString,
message: "DAB did not properly set the 'Application Name' connection string property.");
}
/// <summary>
/// Validates that DAB doesn't append nor modify
/// - the 'Application Name' or 'App' properties in MySQL database connection strings.
/// - the 'Application Name' property in
/// CosmosDB_PostgreSQL, CosmosDB_NoSQL database connection strings.
/// This test validates that this behavior holds true when the DAB_APP_NAME_ENV environment variable
/// - is set (dabEnvOverride==true) -> (DAB hosted)
/// - is not set (dabEnvOverride==false) -> (DAB OSS).
/// </summary>
/// <param name="databaseType">database type.</param>
/// <param name="configProvidedConnString">connection string provided in the config.</param>
/// <param name="expectedDabModifiedConnString">Updated connection string with Application Name.</param>
/// <param name="dabEnvOverride">Whether DAB_APP_NAME_ENV is set in environment. (Always present in hosted scenario or if user supplies value.)</param>
#pragma warning disable format
[DataTestMethod]
[DataRow(DatabaseType.MySQL, "Something;" , "Something;" , false, DisplayName = "[MYSQL|DAB OSS]:No addition of 'Application Name' or 'App' property to connection string.")]
[DataRow(DatabaseType.MySQL, "Something;Application Name=CustAppName;" , "Something;Application Name=CustAppName;" , false, DisplayName = "[MYSQL|DAB OSS]:No modification of customer overridden 'Application Name' property.")]
[DataRow(DatabaseType.MySQL, "Something1;App=CustAppName;Something2;" , "Something1;App=CustAppName;Something2;" , false, DisplayName = "[MySQL|DAB OSS]:No modification of customer overridden 'App' property.")]
[DataRow(DatabaseType.MySQL, "Something;" , "Something;" , true , DisplayName = "[MYSQL|DAB hosted]:No addition of 'Application Name' or 'App' property to connection string.")]
[DataRow(DatabaseType.MySQL, "Something;Application Name=CustAppName;" , "Something;Application Name=CustAppName;" , true , DisplayName = "[MYSQL|DAB hosted]:No modification of customer overridden 'Application Name' property.")]
[DataRow(DatabaseType.MySQL, "Something1;App=CustAppName;Something2;" , "Something1;App=CustAppName;Something2;" , true, DisplayName = "[MySQL|DAB hosted]:No modification of customer overridden 'App' property.")]
[DataRow(DatabaseType.CosmosDB_NoSQL, "Something;" , "Something;" , false, DisplayName = "[COSMOSDB_NOSQL|DAB OSS]:No addition of 'Application Name' property to connection string.")]
[DataRow(DatabaseType.CosmosDB_NoSQL, "Something;Application Name=CustAppName;", "Something;Application Name=CustAppName;", false, DisplayName = "[COSMOSDB_NOSQL|DAB OSS]:No modification of customer overridden 'Application Name' property.")]
[DataRow(DatabaseType.CosmosDB_NoSQL, "Something;" , "Something;" , true , DisplayName = "[COSMOSDB_NOSQL|DAB hosted]:No addition of 'Application Name' property to connection string.")]
[DataRow(DatabaseType.CosmosDB_NoSQL, "Something;Application Name=CustAppName;", "Something;Application Name=CustAppName;", true , DisplayName = "[COSMOSDB_NOSQL|DAB hosted]:No modification of customer overridden 'Application Name' property.")]
[DataRow(DatabaseType.CosmosDB_PostgreSQL, "Something;" , "Something;" , false, DisplayName = "[COSMOSDB_PGSQL|DAB OSS]:No addition of 'Application Name' property to connection string.")]
[DataRow(DatabaseType.CosmosDB_PostgreSQL, "Something;Application Name=CustAppName;", "Something;Application Name=CustAppName;", false, DisplayName = "[COSMOSDB_PGSQL|DAB OSS]:No modification of customer overridden 'Application Name' property.")]