|
2 | 2 | // Licensed under the MIT License. |
3 | 3 |
|
4 | 4 | using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.IO; |
| 7 | +using System.Net.Http; |
5 | 8 | using System.Text.Json; |
6 | 9 | using System.Threading.Tasks; |
| 10 | +using Azure.DataApiBuilder.Config.NamingPolicies; |
| 11 | +using Azure.DataApiBuilder.Config.ObjectModel; |
| 12 | +using Azure.DataApiBuilder.Core.Authorization; |
| 13 | +using Azure.DataApiBuilder.Core.Configurations; |
7 | 14 | using Azure.DataApiBuilder.Core.Resolvers; |
8 | 15 | using Azure.DataApiBuilder.Service.Exceptions; |
| 16 | +using Azure.DataApiBuilder.Service.Tests.Configuration; |
| 17 | +using Microsoft.AspNetCore.TestHost; |
9 | 18 | using Microsoft.Azure.Cosmos; |
10 | 19 | using Microsoft.Extensions.DependencyInjection; |
11 | 20 | using Microsoft.VisualStudio.TestTools.UnitTesting; |
@@ -390,6 +399,245 @@ public async Task UpdateMutationWithOnlyTypenameInSelectionSet() |
390 | 399 | Assert.AreEqual(expected, actual); |
391 | 400 | } |
392 | 401 |
|
| 402 | + /// <summary> |
| 403 | + /// For mutation operations, both the respective operation(create/update/delete) + read permissions are needed to receive a valid response. |
| 404 | + /// In this test, Anonymous role is configured with only create permission. |
| 405 | + /// So, a create mutation executed in the context of Anonymous role is expected to result in |
| 406 | + /// 1) Creation of a new item in the database |
| 407 | + /// 2) An error response containing the error message : "The mutation operation {operation_name} was successful but the current user is unauthorized to view the response due to lack of read permissions" |
| 408 | + /// |
| 409 | + /// A create mutation operation in the context of Anonymous role is executed and the expected error message is validated. |
| 410 | + /// Authenticated role has read permission configured. A pk query is executed in the context of Authenticated role to validate that a new |
| 411 | + /// record was created in the database. |
| 412 | + /// </summary> |
| 413 | + [TestMethod] |
| 414 | + public async Task ValidateErrorMessageForMutationWithoutReadPermission() |
| 415 | + { |
| 416 | + const string SCHEMA = @" |
| 417 | +type Planet @model(name:""Planet"") { |
| 418 | + id : ID!, |
| 419 | + name : String, |
| 420 | + age : Int, |
| 421 | +}"; |
| 422 | + GraphQLRuntimeOptions graphqlOptions = new(Enabled: true); |
| 423 | + RestRuntimeOptions restRuntimeOptions = new(Enabled: false); |
| 424 | + Dictionary<string, JsonElement> dbOptions = new(); |
| 425 | + HyphenatedNamingPolicy namingPolicy = new(); |
| 426 | + |
| 427 | + dbOptions.Add(namingPolicy.ConvertName(nameof(CosmosDbNoSQLDataSourceOptions.Database)), JsonSerializer.SerializeToElement("graphqldb")); |
| 428 | + dbOptions.Add(namingPolicy.ConvertName(nameof(CosmosDbNoSQLDataSourceOptions.Container)), JsonSerializer.SerializeToElement(_containerName)); |
| 429 | + dbOptions.Add(namingPolicy.ConvertName(nameof(CosmosDbNoSQLDataSourceOptions.Schema)), JsonSerializer.SerializeToElement("custom-schema.gql")); |
| 430 | + DataSource dataSource = new(DatabaseType.CosmosDB_NoSQL, |
| 431 | + ConfigurationTests.GetConnectionStringFromEnvironmentConfig(environment: TestCategory.COSMOSDBNOSQL), dbOptions); |
| 432 | + |
| 433 | + EntityAction createAction = new( |
| 434 | + Action: EntityActionOperation.Create, |
| 435 | + Fields: null, |
| 436 | + Policy: new()); |
| 437 | + |
| 438 | + EntityAction readAction = new( |
| 439 | + Action: EntityActionOperation.Read, |
| 440 | + Fields: null, |
| 441 | + Policy: new()); |
| 442 | + |
| 443 | + EntityAction deleteAction = new( |
| 444 | + Action: EntityActionOperation.Delete, |
| 445 | + Fields: null, |
| 446 | + Policy: new()); |
| 447 | + |
| 448 | + EntityPermission[] permissions = new[] {new EntityPermission( Role: AuthorizationResolver.ROLE_ANONYMOUS , Actions: new[] { createAction }), |
| 449 | + new EntityPermission( Role: AuthorizationResolver.ROLE_AUTHENTICATED , Actions: new[] { readAction, createAction, deleteAction })}; |
| 450 | + |
| 451 | + Entity entity = new(Source: new($"graphqldb.{_containerName}", null, null, null), |
| 452 | + Rest: null, |
| 453 | + GraphQL: new(Singular: "Planet", Plural: "Planets"), |
| 454 | + Permissions: permissions, |
| 455 | + Relationships: null, |
| 456 | + Mappings: null); |
| 457 | + |
| 458 | + string entityName = "Planet"; |
| 459 | + RuntimeConfig configuration = ConfigurationTests.InitMinimalRuntimeConfig(dataSource, graphqlOptions, restRuntimeOptions, entity, entityName); |
| 460 | + |
| 461 | + const string CUSTOM_CONFIG = "custom-config.json"; |
| 462 | + const string CUSTOM_SCHEMA = "custom-schema.gql"; |
| 463 | + File.WriteAllText(CUSTOM_CONFIG, configuration.ToJson()); |
| 464 | + File.WriteAllText(CUSTOM_SCHEMA, SCHEMA); |
| 465 | + |
| 466 | + string[] args = new[] |
| 467 | + { |
| 468 | + $"--ConfigFileName={CUSTOM_CONFIG}", |
| 469 | + }; |
| 470 | + |
| 471 | + string id = Guid.NewGuid().ToString(); |
| 472 | + string authToken = AuthTestHelper.CreateStaticWebAppsEasyAuthToken(); |
| 473 | + using (TestServer server = new(Program.CreateWebHostBuilder(args))) |
| 474 | + using (HttpClient client = server.CreateClient()) |
| 475 | + { |
| 476 | + try |
| 477 | + { |
| 478 | + var input = new |
| 479 | + { |
| 480 | + id, |
| 481 | + name = "test_name", |
| 482 | + }; |
| 483 | + |
| 484 | + // A create mutation operation is executed in the context of Anonymous role. The Anonymous role has create action configured but lacks |
| 485 | + // read action. As a result, a new record should be created in the database but the mutation operation should return an error message. |
| 486 | + JsonElement mutationResponse = await GraphQLRequestExecutor.PostGraphQLRequestAsync( |
| 487 | + client, |
| 488 | + server.Services.GetRequiredService<RuntimeConfigProvider>(), |
| 489 | + query: _createPlanetMutation, |
| 490 | + queryName: "createPlanet", |
| 491 | + variables: new() { { "item", input } }, |
| 492 | + clientRoleHeader: null |
| 493 | + ); |
| 494 | + |
| 495 | + Assert.IsTrue(mutationResponse.ToString().Contains("The mutation operation createPlanet was successful but the current user is unauthorized to view the response due to lack of read permissions")); |
| 496 | + |
| 497 | + // pk_query is executed in the context of Authenticated role to validate that the create mutation executed in the context of Anonymous role |
| 498 | + // resulted in the creation of a new record in the database. |
| 499 | + string graphQLQuery = @$" |
| 500 | +query {{ |
| 501 | + planet_by_pk (id: ""{id}"") {{ |
| 502 | + id |
| 503 | + name |
| 504 | + }} |
| 505 | +}}"; |
| 506 | + string queryName = "planet_by_pk"; |
| 507 | + |
| 508 | + JsonElement queryResponse = await GraphQLRequestExecutor.PostGraphQLRequestAsync( |
| 509 | + client, |
| 510 | + server.Services.GetRequiredService<RuntimeConfigProvider>(), |
| 511 | + query: graphQLQuery, |
| 512 | + queryName: queryName, |
| 513 | + variables: null, |
| 514 | + authToken: authToken, |
| 515 | + clientRoleHeader: AuthorizationResolver.ROLE_AUTHENTICATED); |
| 516 | + |
| 517 | + Assert.IsFalse(!queryResponse.ToString().Contains(id), "The query response was not expected to have errors. The document did not return successfully."); |
| 518 | + } |
| 519 | + finally |
| 520 | + { |
| 521 | + // Clean-up steps. The record created by the create mutation operation is deleted to reset the database |
| 522 | + // back to its original state. |
| 523 | + _ = await GraphQLRequestExecutor.PostGraphQLRequestAsync( |
| 524 | + client, |
| 525 | + server.Services.GetRequiredService<RuntimeConfigProvider>(), |
| 526 | + query: _deletePlanetMutation, |
| 527 | + queryName: "deletePlanet", |
| 528 | + variables: new() { { "id", id }, { "partitionKeyValue", id } }, |
| 529 | + authToken: authToken, |
| 530 | + clientRoleHeader: AuthorizationResolver.ROLE_AUTHENTICATED); |
| 531 | + } |
| 532 | + } |
| 533 | + } |
| 534 | + |
| 535 | + /// <summary> |
| 536 | + /// For mutation operations, the respective mutation operation type(create/update/delete) + read permissions are needed to receive a valid response. |
| 537 | + /// For graphQL requests, if read permission is configured for Anonymous role, then it is inherited by other roles. |
| 538 | + /// In this test, Anonymous role has read permission configured. Authenticated role has only create permission configured. |
| 539 | + /// A create mutation operation is executed in the context of Authenticated role and the response is expected to have no errors because |
| 540 | + /// the read permission is inherited from Anonymous role. |
| 541 | + /// </summary> |
| 542 | + [TestMethod] |
| 543 | + public async Task ValidateInheritanceOfReadPermissionFromAnonymous() |
| 544 | + { |
| 545 | + const string SCHEMA = @" |
| 546 | +type Planet @model(name:""Planet"") { |
| 547 | + id : ID!, |
| 548 | + name : String, |
| 549 | + age : Int, |
| 550 | +}"; |
| 551 | + GraphQLRuntimeOptions graphqlOptions = new(Enabled: true); |
| 552 | + RestRuntimeOptions restRuntimeOptions = new(Enabled: false); |
| 553 | + Dictionary<string, JsonElement> dbOptions = new(); |
| 554 | + HyphenatedNamingPolicy namingPolicy = new(); |
| 555 | + |
| 556 | + dbOptions.Add(namingPolicy.ConvertName(nameof(CosmosDbNoSQLDataSourceOptions.Database)), JsonSerializer.SerializeToElement("graphqldb")); |
| 557 | + dbOptions.Add(namingPolicy.ConvertName(nameof(CosmosDbNoSQLDataSourceOptions.Container)), JsonSerializer.SerializeToElement(_containerName)); |
| 558 | + dbOptions.Add(namingPolicy.ConvertName(nameof(CosmosDbNoSQLDataSourceOptions.Schema)), JsonSerializer.SerializeToElement("custom-schema.gql")); |
| 559 | + DataSource dataSource = new(DatabaseType.CosmosDB_NoSQL, |
| 560 | + ConfigurationTests.GetConnectionStringFromEnvironmentConfig(environment: TestCategory.COSMOSDBNOSQL), dbOptions); |
| 561 | + |
| 562 | + EntityAction createAction = new( |
| 563 | + Action: EntityActionOperation.Create, |
| 564 | + Fields: null, |
| 565 | + Policy: new()); |
| 566 | + |
| 567 | + EntityAction readAction = new( |
| 568 | + Action: EntityActionOperation.Read, |
| 569 | + Fields: null, |
| 570 | + Policy: new()); |
| 571 | + |
| 572 | + EntityAction deleteAction = new( |
| 573 | + Action: EntityActionOperation.Delete, |
| 574 | + Fields: null, |
| 575 | + Policy: new()); |
| 576 | + |
| 577 | + EntityPermission[] permissions = new[] {new EntityPermission( Role: AuthorizationResolver.ROLE_ANONYMOUS , Actions: new[] { createAction, readAction, deleteAction }), |
| 578 | + new EntityPermission( Role: AuthorizationResolver.ROLE_AUTHENTICATED , Actions: new[] { createAction })}; |
| 579 | + |
| 580 | + Entity entity = new(Source: new($"graphqldb.{_containerName}", null, null, null), |
| 581 | + Rest: null, |
| 582 | + GraphQL: new(Singular: "Planet", Plural: "Planets"), |
| 583 | + Permissions: permissions, |
| 584 | + Relationships: null, |
| 585 | + Mappings: null); |
| 586 | + |
| 587 | + string entityName = "Planet"; |
| 588 | + RuntimeConfig configuration = ConfigurationTests.InitMinimalRuntimeConfig(dataSource, graphqlOptions, restRuntimeOptions, entity, entityName); |
| 589 | + |
| 590 | + const string CUSTOM_CONFIG = "custom-config.json"; |
| 591 | + const string CUSTOM_SCHEMA = "custom-schema.gql"; |
| 592 | + File.WriteAllText(CUSTOM_CONFIG, configuration.ToJson()); |
| 593 | + File.WriteAllText(CUSTOM_SCHEMA, SCHEMA); |
| 594 | + |
| 595 | + string id = Guid.NewGuid().ToString(); |
| 596 | + string[] args = new[] |
| 597 | + { |
| 598 | + $"--ConfigFileName={CUSTOM_CONFIG}" |
| 599 | + }; |
| 600 | + |
| 601 | + using (TestServer server = new(Program.CreateWebHostBuilder(args))) |
| 602 | + using (HttpClient client = server.CreateClient()) |
| 603 | + { |
| 604 | + try |
| 605 | + { |
| 606 | + var input = new |
| 607 | + { |
| 608 | + id, |
| 609 | + name = "test_name", |
| 610 | + }; |
| 611 | + |
| 612 | + // A create mutation operation is executed in the context of Authenticated role and the response is expected to be a valid |
| 613 | + // response without any errors. |
| 614 | + JsonElement mutationResponse = await GraphQLRequestExecutor.PostGraphQLRequestAsync( |
| 615 | + client, |
| 616 | + server.Services.GetRequiredService<RuntimeConfigProvider>(), |
| 617 | + query: _createPlanetMutation, |
| 618 | + queryName: "createPlanet", |
| 619 | + variables: new() { { "item", input } }, |
| 620 | + authToken: AuthTestHelper.CreateStaticWebAppsEasyAuthToken(), |
| 621 | + clientRoleHeader: AuthorizationResolver.ROLE_AUTHENTICATED |
| 622 | + ); |
| 623 | + |
| 624 | + Assert.IsFalse(!mutationResponse.ToString().Contains(id), "The mutation response was not expected to have errors. The document did not create successfully."); |
| 625 | + } |
| 626 | + finally |
| 627 | + { |
| 628 | + // Clean-up steps. The record created by the create mutation operation is deleted to reset the database |
| 629 | + // back to its original state. |
| 630 | + _ = await GraphQLRequestExecutor.PostGraphQLRequestAsync( |
| 631 | + client, |
| 632 | + server.Services.GetRequiredService<RuntimeConfigProvider>(), |
| 633 | + query: _deletePlanetMutation, |
| 634 | + queryName: "deletePlanet", |
| 635 | + variables: new() { { "id", id }, { "partitionKeyValue", id } }, |
| 636 | + clientRoleHeader: null); |
| 637 | + } |
| 638 | + } |
| 639 | + } |
| 640 | + |
393 | 641 | /// <summary> |
394 | 642 | /// Runs once after all tests in this class are executed |
395 | 643 | /// </summary> |
|
0 commit comments