-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathConfigurationTests.cs
More file actions
1974 lines (1714 loc) · 105 KB
/
ConfigurationTests.cs
File metadata and controls
1974 lines (1714 loc) · 105 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.IO;
using System.IO.Abstractions.TestingHelpers;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Config;
using Azure.DataApiBuilder.Service.AuthenticationHelpers;
using Azure.DataApiBuilder.Service.Authorization;
using Azure.DataApiBuilder.Service.Configurations;
using Azure.DataApiBuilder.Service.Controllers;
using Azure.DataApiBuilder.Service.Exceptions;
using Azure.DataApiBuilder.Service.Parsers;
using Azure.DataApiBuilder.Service.Resolvers;
using Azure.DataApiBuilder.Service.Services;
using Azure.DataApiBuilder.Service.Services.MetadataProviders;
using Azure.DataApiBuilder.Service.Services.OpenAPI;
using Azure.DataApiBuilder.Service.Tests.Authorization;
using Azure.DataApiBuilder.Service.Tests.SqlTests;
using HotChocolate;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using MySqlConnector;
using Npgsql;
using static Azure.DataApiBuilder.Config.RuntimeConfigPath;
namespace Azure.DataApiBuilder.Service.Tests.Configuration
{
[TestClass]
public class ConfigurationTests
{
private const string ASP_NET_CORE_ENVIRONMENT_VAR_NAME = "ASPNETCORE_ENVIRONMENT";
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 = 1;
/// <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""
}
";
public TestContext TestContext { get; set; }
[TestInitialize]
public void Setup()
{
TestContext.Properties.Add(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, Environment.GetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME));
TestContext.Properties.Add(RUNTIME_ENVIRONMENT_VAR_NAME, Environment.GetEnvironmentVariable(RUNTIME_ENVIRONMENT_VAR_NAME));
}
[ClassCleanup]
public static void Cleanup()
{
if (File.Exists($"{CONFIGFILE_NAME}.Test{CONFIG_EXTENSION}"))
{
File.Delete($"{CONFIGFILE_NAME}.Test{CONFIG_EXTENSION}");
}
if (File.Exists($"{CONFIGFILE_NAME}.HostTest{CONFIG_EXTENSION}"))
{
File.Delete($"{CONFIGFILE_NAME}.HostTest{CONFIG_EXTENSION}");
}
if (File.Exists($"{CONFIGFILE_NAME}.Test.overrides{CONFIG_EXTENSION}"))
{
File.Delete($"{CONFIGFILE_NAME}.Test.overrides{CONFIG_EXTENSION}");
}
if (File.Exists($"{CONFIGFILE_NAME}.HostTest.overrides{CONFIG_EXTENSION}"))
{
File.Delete($"{CONFIGFILE_NAME}.HostTest.overrides{CONFIG_EXTENSION}");
}
}
[TestCleanup]
public void CleanupAfterEachTest()
{
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, (string)TestContext.Properties[ASP_NET_CORE_ENVIRONMENT_VAR_NAME]);
Environment.SetEnvironmentVariable(RUNTIME_ENVIRONMENT_VAR_NAME, (string)TestContext.Properties[RUNTIME_ENVIRONMENT_VAR_NAME]);
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, "");
Environment.SetEnvironmentVariable($"{ENVIRONMENT_PREFIX}{nameof(RuntimeConfigPath.CONNSTRING)}", "");
}
/// <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;
try
{
if (isUpdateableRuntimeConfig)
{
server = new(Program.CreateWebHostFromInMemoryUpdateableConfBuilder(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: {RuntimeConfigPath.DefaultName}",
e.Message);
}
}
/// <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(RuntimeConfigProvider.IsHttpsRedirectionDisabled, expectedIsHttpsRedirectionDisabled);
}
/// <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, SourceType.StoredProcedure, "stored-procedure", DisplayName = "source is a stored-procedure")]
[DataRow(true, SourceType.Table, "table", DisplayName = "source is a table")]
[DataRow(true, SourceType.View, "view", DisplayName = "source is a view")]
[DataRow(false, null, null, DisplayName = "source is just string")]
public void TestCorrectSerializationOfSourceObject(
bool isDatabaseObjectSource,
SourceType sourceObjectType,
string sourceTypeName)
{
object entitySource;
if (isDatabaseObjectSource)
{
entitySource = new DatabaseObjectSource(
Type: sourceObjectType,
Name: "sourceName",
Parameters: null,
KeyFields: null
);
}
else
{
entitySource = "sourceName";
}
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: "MyEntity",
entitySource: entitySource,
roleName: "Anonymous",
operation: Config.Operation.All,
includedCols: null,
excludedCols: null,
databasePolicy: null
);
string runtimeConfigJson = JsonSerializer.Serialize<RuntimeConfig>(runtimeConfig);
if (isDatabaseObjectSource)
{
Assert.IsTrue(runtimeConfigJson.Contains(sourceTypeName));
}
Mock<ILogger> logger = new();
Assert.IsTrue(RuntimeConfig.TryGetDeserializedRuntimeConfig(
runtimeConfigJson,
out RuntimeConfig deserializedRuntimeConfig,
logger.Object));
Assert.IsTrue(deserializedRuntimeConfig.Entities.ContainsKey("MyEntity"));
deserializedRuntimeConfig.Entities["MyEntity"].TryPopulateSourceFields();
Assert.AreEqual("sourceName", deserializedRuntimeConfig.Entities["MyEntity"].SourceName);
JsonElement sourceJson = (JsonElement)deserializedRuntimeConfig.Entities["MyEntity"].Source;
if (isDatabaseObjectSource)
{
Assert.AreEqual(JsonValueKind.Object, sourceJson.ValueKind);
Assert.AreEqual(sourceObjectType, deserializedRuntimeConfig.Entities["MyEntity"].ObjectType);
}
else
{
Assert.AreEqual(JsonValueKind.String, sourceJson.ValueKind);
Assert.AreEqual("sourceName", deserializedRuntimeConfig.Entities["MyEntity"].Source.ToString());
}
}
[TestMethod("Validates that once the configuration is set, the config controller isn't reachable."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public async Task TestConflictAlreadySetConfiguration()
{
TestServer server = new(Program.CreateWebHostFromInMemoryUpdateableConfBuilder(Array.Empty<string>()));
HttpClient httpClient = server.CreateClient();
ConfigurationPostParameters config = GetCosmosConfigurationParameters();
_ = await httpClient.PostAsync("/configuration", JsonContent.Create(config));
ValidateCosmosDbSetup(server);
HttpResponseMessage result = await httpClient.PostAsync("/configuration", JsonContent.Create(config));
Assert.AreEqual(HttpStatusCode.Conflict, result.StatusCode);
}
[TestMethod("Validates that the config controller returns a conflict when using local configuration."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public async Task TestConflictLocalConfiguration()
{
Environment.SetEnvironmentVariable
(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, COSMOS_ENVIRONMENT);
TestServer server = new(Program.CreateWebHostBuilder(Array.Empty<string>()));
HttpClient httpClient = server.CreateClient();
ValidateCosmosDbSetup(server);
ConfigurationPostParameters config = GetCosmosConfigurationParameters();
HttpResponseMessage result =
await httpClient.PostAsync("/configuration", JsonContent.Create(config));
Assert.AreEqual(HttpStatusCode.Conflict, result.StatusCode);
}
[TestMethod("Validates setting the configuration at runtime."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public async Task TestSettingConfigurations()
{
TestServer server = new(Program.CreateWebHostFromInMemoryUpdateableConfBuilder(Array.Empty<string>()));
HttpClient httpClient = server.CreateClient();
ConfigurationPostParameters config = GetCosmosConfigurationParameters();
HttpResponseMessage postResult =
await httpClient.PostAsync("/configuration", JsonContent.Create(config));
Assert.AreEqual(HttpStatusCode.OK, postResult.StatusCode);
}
[TestMethod("Validates an invalid configuration returns a bad request."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public async Task TestInvalidConfigurationAtRuntime()
{
TestServer server = new(Program.CreateWebHostFromInMemoryUpdateableConfBuilder(Array.Empty<string>()));
HttpClient httpClient = server.CreateClient();
ConfigurationPostParameters config = GetCosmosConfigurationParameters();
config = config with { Configuration = "invalidString" };
HttpResponseMessage postResult =
await httpClient.PostAsync("/configuration", JsonContent.Create(config));
Assert.AreEqual(HttpStatusCode.BadRequest, postResult.StatusCode);
}
[TestMethod("Validates a failure in one of the config updated handlers returns a bad request."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public async Task TestSettingFailureConfigurations()
{
TestServer server = new(Program.CreateWebHostFromInMemoryUpdateableConfBuilder(Array.Empty<string>()));
HttpClient httpClient = server.CreateClient();
ConfigurationPostParameters config = GetCosmosConfigurationParameters();
RuntimeConfigProvider runtimeConfigProvider = server.Services.GetService<RuntimeConfigProvider>();
runtimeConfigProvider.RuntimeConfigLoadedHandlers.Add((_, _) =>
{
return Task.FromResult(false);
});
HttpResponseMessage postResult =
await httpClient.PostAsync("/configuration", JsonContent.Create(config));
Assert.AreEqual(HttpStatusCode.BadRequest, postResult.StatusCode);
}
[TestMethod("Validates that the configuration endpoint doesn't return until all configuration loaded handlers have executed."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public async Task TestLongRunningConfigUpdatedHandlerConfigurations()
{
TestServer server = new(Program.CreateWebHostFromInMemoryUpdateableConfBuilder(Array.Empty<string>()));
HttpClient httpClient = server.CreateClient();
ConfigurationPostParameters config = GetCosmosConfigurationParameters();
RuntimeConfigProvider runtimeConfigProvider = server.Services.GetService<RuntimeConfigProvider>();
bool taskHasCompleted = false;
runtimeConfigProvider.RuntimeConfigLoadedHandlers.Add(async (_, _) =>
{
await Task.Delay(1000);
taskHasCompleted = true;
return true;
});
HttpResponseMessage postResult =
await httpClient.PostAsync("/configuration", JsonContent.Create(config));
Assert.AreEqual(HttpStatusCode.OK, postResult.StatusCode);
Assert.IsTrue(taskHasCompleted);
}
/// <summary>
/// Tests that sending configuration to the DAB engine post-startup will properly hydrate
/// the AuthorizationResolver by:
/// 1. Validate that pre-configuration hydration requests result in 503 Service Unavailable
/// 2. Validate that custom configuration hydration succeeds.
/// 3. Validate that request to protected entity without role membership triggers Authorization Resolver
/// to reject the request with HTTP 403 Forbidden.
/// 4. Validate that request to protected entity with required role membership passes authorization requirements
/// and succeeds with HTTP 200 OK.
/// Note: This test is database engine agnostic, though requires denoting a database environment to fetch a usable
/// connection string to complete the test. Most applicable to CI/CD test execution.
/// </summary>
[TestCategory(TestCategory.MSSQL)]
[TestMethod("Validates setting the AuthN/Z configuration post-startup during runtime.")]
public async Task TestSqlSettingPostStartupConfigurations()
{
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, MSSQL_ENVIRONMENT);
TestServer server = new(Program.CreateWebHostFromInMemoryUpdateableConfBuilder(Array.Empty<string>()));
HttpClient httpClient = server.CreateClient();
RuntimeConfig configuration = AuthorizationHelpers.InitRuntimeConfig(
entityName: POST_STARTUP_CONFIG_ENTITY,
entitySource: POST_STARTUP_CONFIG_ENTITY_SOURCE,
roleName: POST_STARTUP_CONFIG_ROLE,
operation: Config.Operation.Read,
includedCols: new HashSet<string>() { "*" });
ConfigurationPostParameters config = GetPostStartupConfigParams(MSSQL_ENVIRONMENT, configuration);
HttpResponseMessage preConfigHydrationResult =
await httpClient.GetAsync($"/{POST_STARTUP_CONFIG_ENTITY}");
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, preConfigHydrationResult.StatusCode);
HttpResponseMessage preConfigOpenApiDocumentExistence =
await httpClient.GetAsync($"{GlobalSettings.REST_DEFAULT_PATH}/{OPENAPI_DOCUMENT_ENDPOINT}");
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, preConfigOpenApiDocumentExistence.StatusCode);
// SwaggerUI (OpenAPI user interface) is not made available in production/hosting mode.
HttpResponseMessage preConfigOpenApiSwaggerEndpointAvailability =
await httpClient.GetAsync($"/{OPENAPI_SWAGGER_ENDPOINT}");
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, preConfigOpenApiSwaggerEndpointAvailability.StatusCode);
HttpStatusCode responseCode = await HydratePostStartupConfiguration(httpClient, config);
// When the authorization resolver is properly configured, authorization will have failed
// because no auth headers are present.
Assert.AreEqual(
expected: HttpStatusCode.Forbidden,
actual: responseCode,
message: "Configuration not yet hydrated after retry attempts..");
// Sends a GET request to a protected entity which requires a specific role to access.
// Authorization will pass because proper auth headers are present.
HttpRequestMessage message = new(method: HttpMethod.Get, requestUri: $"api/{POST_STARTUP_CONFIG_ENTITY}");
string swaTokenPayload = AuthTestHelper.CreateStaticWebAppsEasyAuthToken(
addAuthenticated: true,
specificRole: POST_STARTUP_CONFIG_ROLE);
message.Headers.Add(AuthenticationConfig.CLIENT_PRINCIPAL_HEADER, swaTokenPayload);
message.Headers.Add(AuthorizationResolver.CLIENT_ROLE_HEADER, POST_STARTUP_CONFIG_ROLE);
HttpResponseMessage authorizedResponse = await httpClient.SendAsync(message);
Assert.AreEqual(expected: HttpStatusCode.OK, actual: authorizedResponse.StatusCode);
// OpenAPI document is created during config hydration and
// is made available after config hydration completes.
HttpResponseMessage postConfigOpenApiDocumentExistence =
await httpClient.GetAsync($"{GlobalSettings.REST_DEFAULT_PATH}/{OPENAPI_DOCUMENT_ENDPOINT}");
Assert.AreEqual(HttpStatusCode.OK, postConfigOpenApiDocumentExistence.StatusCode);
// SwaggerUI (OpenAPI user interface) is not made available in production/hosting mode.
// HTTP 400 - BadRequest because when SwaggerUI is disabled, the endpoint is not mapped
// and the request is processed and failed by the RestService.
HttpResponseMessage postConfigOpenApiSwaggerEndpointAvailability =
await httpClient.GetAsync($"/{OPENAPI_SWAGGER_ENDPOINT}");
Assert.AreEqual(HttpStatusCode.BadRequest, postConfigOpenApiSwaggerEndpointAvailability.StatusCode);
}
[TestMethod("Validates that local cosmosdb_nosql settings can be loaded and the correct classes are in the service provider."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public void TestLoadingLocalCosmosSettings()
{
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, COSMOS_ENVIRONMENT);
TestServer server = new(Program.CreateWebHostBuilder(Array.Empty<string>()));
ValidateCosmosDbSetup(server);
}
[TestMethod("Validates access token is correctly loaded when Account Key is not present for Cosmos."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public async Task TestLoadingAccessTokenForCosmosClient()
{
TestServer server = new(Program.CreateWebHostFromInMemoryUpdateableConfBuilder(Array.Empty<string>()));
HttpClient httpClient = server.CreateClient();
ConfigurationPostParameters config = GetCosmosConfigurationParametersWithAccessToken();
HttpResponseMessage authorizedResponse = await httpClient.PostAsync("/configuration", JsonContent.Create(config));
Assert.AreEqual(expected: HttpStatusCode.OK, actual: authorizedResponse.StatusCode);
CosmosClientProvider cosmosClientProvider = server.Services.GetService(typeof(CosmosClientProvider)) as CosmosClientProvider;
Assert.IsNotNull(cosmosClientProvider);
Assert.IsNotNull(cosmosClientProvider.Client);
}
[TestMethod("Validates that local MsSql settings can be loaded and the correct classes are in the service provider."), TestCategory(TestCategory.MSSQL)]
public void TestLoadingLocalMsSqlSettings()
{
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, MSSQL_ENVIRONMENT);
TestServer server = new(Program.CreateWebHostBuilder(Array.Empty<string>()));
object queryEngine = server.Services.GetService(typeof(IQueryEngine));
Assert.IsInstanceOfType(queryEngine, typeof(SqlQueryEngine));
object mutationEngine = server.Services.GetService(typeof(IMutationEngine));
Assert.IsInstanceOfType(mutationEngine, typeof(SqlMutationEngine));
object queryBuilder = server.Services.GetService(typeof(IQueryBuilder));
Assert.IsInstanceOfType(queryBuilder, typeof(MsSqlQueryBuilder));
object queryExecutor = server.Services.GetService(typeof(IQueryExecutor));
Assert.IsInstanceOfType(queryExecutor, typeof(QueryExecutor<SqlConnection>));
object sqlMetadataProvider = server.Services.GetService(typeof(ISqlMetadataProvider));
Assert.IsInstanceOfType(sqlMetadataProvider, typeof(MsSqlMetadataProvider));
}
[TestMethod("Validates that local PostgreSql settings can be loaded and the correct classes are in the service provider."), TestCategory(TestCategory.POSTGRESQL)]
public void TestLoadingLocalPostgresSettings()
{
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, POSTGRESQL_ENVIRONMENT);
TestServer server = new(Program.CreateWebHostBuilder(Array.Empty<string>()));
object queryEngine = server.Services.GetService(typeof(IQueryEngine));
Assert.IsInstanceOfType(queryEngine, typeof(SqlQueryEngine));
object mutationEngine = server.Services.GetService(typeof(IMutationEngine));
Assert.IsInstanceOfType(mutationEngine, typeof(SqlMutationEngine));
object queryBuilder = server.Services.GetService(typeof(IQueryBuilder));
Assert.IsInstanceOfType(queryBuilder, typeof(PostgresQueryBuilder));
object queryExecutor = server.Services.GetService(typeof(IQueryExecutor));
Assert.IsInstanceOfType(queryExecutor, typeof(QueryExecutor<NpgsqlConnection>));
object sqlMetadataProvider = server.Services.GetService(typeof(ISqlMetadataProvider));
Assert.IsInstanceOfType(sqlMetadataProvider, typeof(PostgreSqlMetadataProvider));
}
[TestMethod("Validates that local MySql settings can be loaded and the correct classes are in the service provider."), TestCategory(TestCategory.MYSQL)]
public void TestLoadingLocalMySqlSettings()
{
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, MYSQL_ENVIRONMENT);
TestServer server = new(Program.CreateWebHostBuilder(Array.Empty<string>()));
object queryEngine = server.Services.GetService(typeof(IQueryEngine));
Assert.IsInstanceOfType(queryEngine, typeof(SqlQueryEngine));
object mutationEngine = server.Services.GetService(typeof(IMutationEngine));
Assert.IsInstanceOfType(mutationEngine, typeof(SqlMutationEngine));
object queryBuilder = server.Services.GetService(typeof(IQueryBuilder));
Assert.IsInstanceOfType(queryBuilder, typeof(MySqlQueryBuilder));
object queryExecutor = server.Services.GetService(typeof(IQueryExecutor));
Assert.IsInstanceOfType(queryExecutor, typeof(QueryExecutor<MySqlConnection>));
object sqlMetadataProvider = server.Services.GetService(typeof(ISqlMetadataProvider));
Assert.IsInstanceOfType(sqlMetadataProvider, typeof(MySqlMetadataProvider));
}
[TestMethod("Validates that trying to override configs that are already set fail."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public async Task TestOverridingLocalSettingsFails()
{
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, COSMOS_ENVIRONMENT);
TestServer server = new(Program.CreateWebHostBuilder(Array.Empty<string>()));
HttpClient client = server.CreateClient();
ConfigurationPostParameters config = GetCosmosConfigurationParameters();
HttpResponseMessage postResult = await client.PostAsync("/configuration", JsonContent.Create(config));
Assert.AreEqual(HttpStatusCode.Conflict, postResult.StatusCode);
}
[TestMethod("Validates that setting the configuration at runtime will instantiate the proper classes."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public async Task TestSettingConfigurationCreatesCorrectClasses()
{
TestServer server = new(Program.CreateWebHostFromInMemoryUpdateableConfBuilder(Array.Empty<string>()));
HttpClient client = server.CreateClient();
ConfigurationPostParameters config = GetCosmosConfigurationParameters();
HttpResponseMessage postResult = await client.PostAsync("/configuration", JsonContent.Create(config));
Assert.AreEqual(HttpStatusCode.OK, postResult.StatusCode);
ValidateCosmosDbSetup(server);
RuntimeConfigProvider configProvider = server.Services.GetService<RuntimeConfigProvider>();
Assert.IsNotNull(configProvider, "Configuration Provider shouldn't be null after setting the configuration at runtime.");
Assert.IsNotNull(configProvider.GetRuntimeConfiguration(), "Runtime Configuration shouldn't be null after setting the configuration at runtime.");
RuntimeConfig configuration;
bool isConfigSet = configProvider.TryGetRuntimeConfiguration(out configuration);
Assert.IsNotNull(configuration, "TryGetRuntimeConfiguration should set the config in the out parameter.");
Assert.IsTrue(isConfigSet, "TryGetRuntimeConfiguration should return true when the config is set.");
Assert.AreEqual(DatabaseType.cosmosdb_nosql, configuration.DatabaseType, "Expected cosmosdb_nosql database type after configuring the runtime with cosmosdb_nosql settings.");
Assert.AreEqual(config.Schema, configuration.DataSource.CosmosDbNoSql.GraphQLSchema, "Expected the schema in the configuration to match the one sent to the configuration endpoint.");
Assert.AreEqual(config.ConnectionString, configuration.ConnectionString, "Expected the connection string in the configuration to match the one sent to the configuration endpoint.");
string db = configProvider.GetRuntimeConfiguration().DataSource.CosmosDbNoSql.Database;
Assert.AreEqual(COSMOS_DATABASE_NAME, db, "Expected the database name in the runtime config to match the one sent to the configuration endpoint.");
}
[TestMethod("Validates that an exception is thrown if there's a null model in filter parser.")]
public void VerifyExceptionOnNullModelinFilterParser()
{
ODataParser parser = new();
try
{
// FilterParser has no model so we expect exception
parser.GetFilterClause(filterQueryString: string.Empty, resourcePath: string.Empty);
Assert.Fail();
}
catch (DataApiBuilderException exception)
{
Assert.AreEqual("The runtime has not been initialized with an Edm model.", exception.Message);
Assert.AreEqual(HttpStatusCode.InternalServerError, exception.StatusCode);
Assert.AreEqual(DataApiBuilderException.SubStatusCodes.UnexpectedError, exception.SubStatusCode);
}
}
/// <summary>
/// This test reads the dab-config.MsSql.json file and validates that the
/// deserialization succeeds.
/// </summary>
[TestMethod("Validates if deserialization of MsSql config file succeeds."), TestCategory(TestCategory.MSSQL)]
public void TestReadingRuntimeConfigForMsSql()
{
ConfigFileDeserializationValidationHelper(File.ReadAllText($"{RuntimeConfigPath.CONFIGFILE_NAME}.{MSSQL_ENVIRONMENT}{RuntimeConfigPath.CONFIG_EXTENSION}"));
}
/// <summary>
/// This test reads the dab-config.MySql.json file and validates that the
/// deserialization succeeds.
/// </summary>
[TestMethod("Validates if deserialization of MySql config file succeeds."), TestCategory(TestCategory.MYSQL)]
public void TestReadingRuntimeConfigForMySql()
{
ConfigFileDeserializationValidationHelper(File.ReadAllText($"{RuntimeConfigPath.CONFIGFILE_NAME}.{MYSQL_ENVIRONMENT}{RuntimeConfigPath.CONFIG_EXTENSION}"));
}
/// <summary>
/// This test reads the dab-config.PostgreSql.json file and validates that the
/// deserialization succeeds.
/// </summary>
[TestMethod("Validates if deserialization of PostgreSql config file succeeds."), TestCategory(TestCategory.POSTGRESQL)]
public void TestReadingRuntimeConfigForPostgreSql()
{
ConfigFileDeserializationValidationHelper(File.ReadAllText($"{RuntimeConfigPath.CONFIGFILE_NAME}.{POSTGRESQL_ENVIRONMENT}{RuntimeConfigPath.CONFIG_EXTENSION}"));
}
/// <summary>
/// This test reads the dab-config.CosmosDb_NoSql.json file and validates that the
/// deserialization succeeds.
/// </summary>
[TestMethod("Validates if deserialization of the cosmosdb_nosql config file succeeds."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public void TestReadingRuntimeConfigForCosmos()
{
ConfigFileDeserializationValidationHelper(File.ReadAllText($"{RuntimeConfigPath.CONFIGFILE_NAME}.{COSMOS_ENVIRONMENT}{RuntimeConfigPath.CONFIG_EXTENSION}"));
}
/// <summary>
/// Helper method to validate the deserialization of the "entities" section of the config file
/// This is used in unit tests that validate the deserialiation of the config files
/// </summary>
/// <param name="runtimeConfig"></param>
private static void ConfigFileDeserializationValidationHelper(string jsonString)
{
Mock<ILogger> logger = new();
RuntimeConfig.TryGetDeserializedRuntimeConfig(jsonString, out RuntimeConfig runtimeConfig, logger.Object);
Assert.IsNotNull(runtimeConfig.Schema);
Assert.IsInstanceOfType(runtimeConfig.DataSource, typeof(DataSource));
Assert.IsTrue(runtimeConfig.DataSource.CosmosDbNoSql == null
|| runtimeConfig.DataSource.CosmosDbNoSql.GetType() == typeof(CosmosDbNoSqlOptions));
Assert.IsTrue(runtimeConfig.DataSource.MsSql == null
|| runtimeConfig.DataSource.MsSql.GetType() == typeof(MsSqlOptions));
Assert.IsTrue(runtimeConfig.DataSource.PostgreSql == null
|| runtimeConfig.DataSource.PostgreSql.GetType() == typeof(PostgreSqlOptions));
Assert.IsTrue(runtimeConfig.DataSource.MySql == null
|| runtimeConfig.DataSource.MySql.GetType() == typeof(MySqlOptions));
foreach (Entity entity in runtimeConfig.Entities.Values)
{
Assert.IsTrue(((JsonElement)entity.Source).ValueKind is JsonValueKind.String
|| ((JsonElement)entity.Source).ValueKind is JsonValueKind.Object);
Assert.IsTrue(entity.Rest is null
|| ((JsonElement)entity.Rest).ValueKind is JsonValueKind.True
|| ((JsonElement)entity.Rest).ValueKind is JsonValueKind.False
|| ((JsonElement)entity.Rest).ValueKind is JsonValueKind.Object);
if (entity.Rest != null
&& ((JsonElement)entity.Rest).ValueKind is JsonValueKind.Object)
{
JsonElement restConfigElement = (JsonElement)entity.Rest;
if (!restConfigElement.TryGetProperty("methods", out JsonElement _))
{
RestEntitySettings rest = JsonSerializer.Deserialize<RestEntitySettings>(restConfigElement, RuntimeConfig.SerializerOptions);
Assert.IsTrue(((JsonElement)rest.Path).ValueKind is JsonValueKind.String
|| ((JsonElement)rest.Path).ValueKind is JsonValueKind.True
|| ((JsonElement)rest.Path).ValueKind is JsonValueKind.False);
}
else
{
if (!restConfigElement.TryGetProperty("path", out JsonElement _))
{
RestStoredProcedureEntitySettings rest = JsonSerializer.Deserialize<RestStoredProcedureEntitySettings>(restConfigElement, RuntimeConfig.SerializerOptions);
Assert.AreEqual(typeof(RestMethod[]), rest.RestMethods.GetType());
}
else
{
RestStoredProcedureEntityVerboseSettings rest = JsonSerializer.Deserialize<RestStoredProcedureEntityVerboseSettings>(restConfigElement, RuntimeConfig.SerializerOptions);
Assert.AreEqual(typeof(RestMethod[]), rest.RestMethods.GetType());
Assert.IsTrue((((JsonElement)rest.Path).ValueKind is JsonValueKind.String)
|| (((JsonElement)rest.Path).ValueKind is JsonValueKind.True)
|| (((JsonElement)rest.Path).ValueKind is JsonValueKind.False));
}
}
}
Assert.IsTrue(entity.GraphQL is null
|| entity.GraphQL.GetType() == typeof(bool)
|| entity.GraphQL.GetType() == typeof(GraphQLEntitySettings)
|| entity.GraphQL.GetType() == typeof(GraphQLStoredProcedureEntityOperationSettings)
|| entity.GraphQL.GetType() == typeof(GraphQLStoredProcedureEntityVerboseSettings));
if (entity.GraphQL is not null)
{
if (entity.GraphQL.GetType() == typeof(GraphQLEntitySettings))
{
GraphQLEntitySettings graphQL = (GraphQLEntitySettings)entity.GraphQL;
Assert.IsTrue(graphQL.Type.GetType() == typeof(string)
|| graphQL.Type.GetType() == typeof(SingularPlural));
}
else if (entity.GraphQL.GetType() == typeof(GraphQLStoredProcedureEntityOperationSettings))
{
GraphQLStoredProcedureEntityOperationSettings graphQL = (GraphQLStoredProcedureEntityOperationSettings)entity.GraphQL;
Assert.AreEqual(typeof(string), graphQL.GraphQLOperation.GetType());
}
else if (entity.GraphQL.GetType() == typeof(GraphQLStoredProcedureEntityVerboseSettings))
{
GraphQLStoredProcedureEntityVerboseSettings graphQL = (GraphQLStoredProcedureEntityVerboseSettings)entity.GraphQL;
Assert.AreEqual(typeof(string), graphQL.GraphQLOperation.GetType());
Assert.IsTrue(graphQL.Type.GetType() == typeof(bool)
|| graphQL.Type.GetType() == typeof(string)
|| graphQL.Type.GetType() == typeof(SingularPlural));
}
}
Assert.IsInstanceOfType(entity.Permissions, typeof(PermissionSetting[]));
HashSet<Config.Operation> allowedActions =
new() { Config.Operation.All, Config.Operation.Create, Config.Operation.Read,
Config.Operation.Update, Config.Operation.Delete, Config.Operation.Execute };
foreach (PermissionSetting permission in entity.Permissions)
{
foreach (object operation in permission.Operations)
{
Assert.IsTrue(((JsonElement)operation).ValueKind == JsonValueKind.String ||
((JsonElement)operation).ValueKind == JsonValueKind.Object);
if (((JsonElement)operation).ValueKind == JsonValueKind.Object)
{
Config.PermissionOperation configOperation =
((JsonElement)operation).Deserialize<Config.PermissionOperation>(RuntimeConfig.SerializerOptions);
Assert.IsTrue(allowedActions.Contains(configOperation.Name));
Assert.IsTrue(configOperation.Policy == null
|| configOperation.Policy.GetType() == typeof(Policy));
Assert.IsTrue(configOperation.Fields == null
|| configOperation.Fields.GetType() == typeof(Field));
}
else
{
Config.Operation name = AuthorizationResolver.WILDCARD.Equals(operation.ToString()) ? Config.Operation.All : ((JsonElement)operation).Deserialize<Config.Operation>(RuntimeConfig.SerializerOptions);
Assert.IsTrue(allowedActions.Contains(name));
}
}
}
Assert.IsTrue(entity.Relationships == null ||
entity.Relationships.GetType()
== typeof(Dictionary<string, Relationship>));
Assert.IsTrue(entity.Mappings == null ||
entity.Mappings.GetType()
== typeof(Dictionary<string, string>));
}
}
/// <summary>
/// This function verifies command line configuration provider takes higher
/// precendence than default configuration file dab-config.json
/// </summary>
[TestMethod("Validates command line configuration provider."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public void TestCommandLineConfigurationProvider()
{
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, MSSQL_ENVIRONMENT);
string[] args = new[]
{
$"--ConfigFileName={RuntimeConfigPath.CONFIGFILE_NAME}." +
$"{COSMOS_ENVIRONMENT}{RuntimeConfigPath.CONFIG_EXTENSION}"
};
TestServer server = new(Program.CreateWebHostBuilder(args));
ValidateCosmosDbSetup(server);
}
/// <summary>
/// This function verifies the environment variable DAB_ENVIRONMENT
/// takes precendence than ASPNETCORE_ENVIRONMENT for the configuration file.
/// </summary>
[TestMethod("Validates precedence is given to DAB_ENVIRONMENT environment variable name."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public void TestRuntimeEnvironmentVariable()
{
Environment.SetEnvironmentVariable(
ASP_NET_CORE_ENVIRONMENT_VAR_NAME, MSSQL_ENVIRONMENT);
Environment.SetEnvironmentVariable(
RuntimeConfigPath.RUNTIME_ENVIRONMENT_VAR_NAME, COSMOS_ENVIRONMENT);
TestServer server = new(Program.CreateWebHostBuilder(Array.Empty<string>()));
ValidateCosmosDbSetup(server);
}
[TestMethod("Validates the runtime configuration file."), TestCategory(TestCategory.MSSQL)]
public void TestConfigIsValid()
{
RuntimeConfigPath configPath =
TestHelper.GetRuntimeConfigPath(MSSQL_ENVIRONMENT);
RuntimeConfigProvider configProvider = TestHelper.GetRuntimeConfigProvider(configPath);
Mock<ILogger<RuntimeConfigValidator>> configValidatorLogger = new();
IConfigValidator configValidator =
new RuntimeConfigValidator(
configProvider,
new MockFileSystem(),
configValidatorLogger.Object);
configValidator.ValidateConfig();
}
/// <summary>
/// Set the connection string to an invalid value and expect the service to be unavailable
/// since without this env var, it would be available - guaranteeing this env variable
/// has highest precedence irrespective of what the connection string is in the config file.
/// Verifying the Exception thrown.
/// </summary>
[TestMethod("Validates that environment variable DAB_CONNSTRING has highest precedence."), TestCategory(TestCategory.COSMOSDBNOSQL)]
public void TestConnectionStringEnvVarHasHighestPrecedence()
{
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, COSMOS_ENVIRONMENT);
Environment.SetEnvironmentVariable(
$"{RuntimeConfigPath.ENVIRONMENT_PREFIX}{nameof(RuntimeConfigPath.CONNSTRING)}",
"Invalid Connection String");
try
{
TestServer server = new(Program.CreateWebHostBuilder(Array.Empty<string>()));
_ = server.Services.GetService(typeof(CosmosClientProvider)) as CosmosClientProvider;
Assert.Fail($"{RuntimeConfigPath.ENVIRONMENT_PREFIX}{nameof(RuntimeConfigPath.CONNSTRING)} is not given highest precedence");
}
catch (Exception e)
{
Assert.AreEqual(typeof(ApplicationException), e.GetType());
Assert.AreEqual(
$"Could not initialize the engine with the runtime config file: " +
$"{RuntimeConfigPath.CONFIGFILE_NAME}.{COSMOS_ENVIRONMENT}{RuntimeConfigPath.CONFIG_EXTENSION}",
e.Message);
}
}
/// <summary>
/// Test to verify the precedence logic for config file based on Environment variables.
/// </summary>
[DataTestMethod]
[DataRow("HostTest", "Test", false, $"{CONFIGFILE_NAME}.Test{CONFIG_EXTENSION}", DisplayName = "hosting and dab environment set, without considering overrides.")]
[DataRow("HostTest", "", false, $"{CONFIGFILE_NAME}.HostTest{CONFIG_EXTENSION}", DisplayName = "only hosting environment set, without considering overrides.")]
[DataRow("", "Test1", false, $"{CONFIGFILE_NAME}.Test1{CONFIG_EXTENSION}", DisplayName = "only dab environment set, without considering overrides.")]
[DataRow("", "Test2", true, $"{CONFIGFILE_NAME}.Test2.overrides{CONFIG_EXTENSION}", DisplayName = "only dab environment set, considering overrides.")]
[DataRow("HostTest1", "", true, $"{CONFIGFILE_NAME}.HostTest1.overrides{CONFIG_EXTENSION}", DisplayName = "only hosting environment set, considering overrides.")]
public void TestGetConfigFileNameForEnvironment(
string hostingEnvironmentValue,
string environmentValue,
bool considerOverrides,
string expectedRuntimeConfigFile)
{
if (!File.Exists(expectedRuntimeConfigFile))
{
File.Create(expectedRuntimeConfigFile);
}
Environment.SetEnvironmentVariable(ASP_NET_CORE_ENVIRONMENT_VAR_NAME, hostingEnvironmentValue);
Environment.SetEnvironmentVariable(RUNTIME_ENVIRONMENT_VAR_NAME, environmentValue);
string actualRuntimeConfigFile = GetFileNameForEnvironment(hostingEnvironmentValue, considerOverrides);
Assert.AreEqual(expectedRuntimeConfigFile, actualRuntimeConfigFile);
}
/// <summary>
/// Test different graphql endpoints in different host modes
/// when accessed interactively via browser.
/// </summary>
/// <param name="endpoint">The endpoint route</param>
/// <param name="hostModeType">The mode in which the service is executing.</param>
/// <param name="expectedStatusCode">Expected Status Code.</param>
/// <param name="expectedContent">The expected phrase in the response body.</param>
[DataTestMethod]
[TestCategory(TestCategory.MSSQL)]
[DataRow("/graphql/", HostModeType.Development, HttpStatusCode.OK, "Banana Cake Pop",
DisplayName = "GraphQL endpoint with no query in development mode.")]
[DataRow("/graphql", HostModeType.Production, HttpStatusCode.BadRequest,
"Either the parameter query or the parameter id has to be set",
DisplayName = "GraphQL endpoint with no query in production mode.")]
[DataRow("/graphql/ui", HostModeType.Development, HttpStatusCode.NotFound,
DisplayName = "Default BananaCakePop in development mode.")]
[DataRow("/graphql/ui", HostModeType.Production, HttpStatusCode.NotFound,
DisplayName = "Default BananaCakePop in production mode.")]
[DataRow("/graphql?query={book_by_pk(id: 1){title}}",
HostModeType.Development, HttpStatusCode.Moved,
DisplayName = "GraphQL endpoint with query in development mode.")]
[DataRow("/graphql?query={book_by_pk(id: 1){title}}",
HostModeType.Production, HttpStatusCode.OK, "data",
DisplayName = "GraphQL endpoint with query in production mode.")]
[DataRow(RestController.REDIRECTED_ROUTE, HostModeType.Development, HttpStatusCode.BadRequest,
"GraphQL request redirected to favicon.ico.",
DisplayName = "Redirected endpoint in development mode.")]
[DataRow(RestController.REDIRECTED_ROUTE, HostModeType.Production, HttpStatusCode.BadRequest,
"GraphQL request redirected to favicon.ico.",
DisplayName = "Redirected endpoint in production mode.")]
public async Task TestInteractiveGraphQLEndpoints(
string endpoint,
HostModeType hostModeType,
HttpStatusCode expectedStatusCode,
string expectedContent = "")
{
const string CUSTOM_CONFIG = "custom-config.json";
RuntimeConfigProvider configProvider = TestHelper.GetRuntimeConfigProvider(MSSQL_ENVIRONMENT);
RuntimeConfig config = configProvider.GetRuntimeConfiguration();
HostGlobalSettings customHostGlobalSettings = config.HostGlobalSettings with { Mode = hostModeType };
JsonElement serializedCustomHostGlobalSettings =
JsonSerializer.SerializeToElement(customHostGlobalSettings, RuntimeConfig.SerializerOptions);
Dictionary<GlobalSettingsType, object> customRuntimeSettings = new(config.RuntimeSettings);
customRuntimeSettings.Remove(GlobalSettingsType.Host);
customRuntimeSettings.Add(GlobalSettingsType.Host, serializedCustomHostGlobalSettings);
RuntimeConfig configWithCustomHostMode =
config with { RuntimeSettings = customRuntimeSettings };
File.WriteAllText(
CUSTOM_CONFIG,
JsonSerializer.Serialize(configWithCustomHostMode, RuntimeConfig.SerializerOptions));
string[] args = new[]
{
$"--ConfigFileName={CUSTOM_CONFIG}"
};
using TestServer server = new(Program.CreateWebHostBuilder(args));
using HttpClient client = server.CreateClient();
{
HttpRequestMessage request = new(HttpMethod.Get, endpoint);
// Adding the following headers simulates an interactive browser request.
request.Headers.Add("user-agent", BROWSER_USER_AGENT_HEADER);
request.Headers.Add("accept", BROWSER_ACCEPT_HEADER);
HttpResponseMessage response = await client.SendAsync(request);
Assert.AreEqual(expectedStatusCode, response.StatusCode);
string actualBody = await response.Content.ReadAsStringAsync();
Assert.IsTrue(actualBody.Contains(expectedContent));
}
}
/// <summary>
/// Tests that the custom path rewriting middleware properly rewrites the
/// first segment of a path (/segment1/.../segmentN) when the segment matches
/// the custom configured GraphQLEndpoint.
/// Note: The GraphQL service is always internally mapped to /graphql
/// </summary>
/// <param name="graphQLConfiguredPath">The custom configured GraphQL path in configuration</param>
/// <param name="requestPath">The path used in the web request executed in the test.</param>
/// <param name="expectedStatusCode">Expected Http success/error code</param>
[DataTestMethod]
[TestCategory(TestCategory.MSSQL)]
[DataRow("/graphql", "/gql", HttpStatusCode.BadRequest, DisplayName = "Request to non-configured graphQL endpoint is handled by REST controller.")]
[DataRow("/graphql", "/graphql", HttpStatusCode.OK, DisplayName = "Request to configured default GraphQL endpoint succeeds, path not rewritten.")]
[DataRow("/gql", "/gql/additionalURLsegment", HttpStatusCode.OK, DisplayName = "GraphQL request path (with extra segments) rewritten to match internally set GraphQL endpoint /graphql.")]
[DataRow("/gql", "/gql", HttpStatusCode.OK, DisplayName = "GraphQL request path rewritten to match internally set GraphQL endpoint /graphql.")]
[DataRow("/gql", "/api/book", HttpStatusCode.NotFound, DisplayName = "Non-GraphQL request's path is not rewritten and is handled by REST controller.")]
[DataRow("/gql", "/graphql", HttpStatusCode.NotFound, DisplayName = "Requests to default/internally set graphQL endpoint fail when configured endpoint differs.")]
public async Task TestPathRewriteMiddlewareForGraphQL(
string graphQLConfiguredPath,
string requestPath,
HttpStatusCode expectedStatusCode)
{
Dictionary<GlobalSettingsType, object> settings = new()
{
{ GlobalSettingsType.GraphQL, JsonSerializer.SerializeToElement(new GraphQLGlobalSettings(){ Path = graphQLConfiguredPath, AllowIntrospection = true }) },
{ GlobalSettingsType.Rest, JsonSerializer.SerializeToElement(new RestGlobalSettings()) }
};
DataSource dataSource = new(DatabaseType.mssql)
{
ConnectionString = GetConnectionStringFromEnvironmentConfig(environment: TestCategory.MSSQL)
};
RuntimeConfig configuration = InitMinimalRuntimeConfig(globalSettings: settings, dataSource: dataSource);
const string CUSTOM_CONFIG = "custom-config.json";
File.WriteAllText(
CUSTOM_CONFIG,
JsonSerializer.Serialize(configuration, RuntimeConfig.SerializerOptions));
string[] args = new[]
{
$"--ConfigFileName={CUSTOM_CONFIG}"
};
using (TestServer server = new(Program.CreateWebHostBuilder(args)))
using (HttpClient client = server.CreateClient())
{
string query = @"{
book_by_pk(id: 1) {
id,
title,
publisher_id
}
}";
object payload = new { query };
HttpRequestMessage request = new(HttpMethod.Post, requestPath)
{
Content = JsonContent.Create(payload)
};
HttpResponseMessage response = await client.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
Assert.AreEqual(expectedStatusCode, response.StatusCode);
}
}
/// <summary>
/// Validates the error message that is returned for REST requests with incorrect parameter type