1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-21 12:05:42 +01:00

[EC-394] SCIM server integration tests (#2197)

* [EC-394] Added ScimApplicationFactory to handle tests for Scim controllers

* [EC-394] Added Scim.IntegrationTest project with GroupsControllerTests

* [EC-394] Fixed getting Guid Id from Operation Path

* [EC-394] Added tests for GroupsController Patch action

* [EC-394] Moved tests mock data setup to ScimApplicationFactory

* [EC-394] Updated IntegrationTestCommon packages.lock.json

* [EC-394] Updated ScimApplicationFactory and GroupsControllerTests; Added UsersController Tests

* [EC-394] dotnet format

* [EC-394] Updated Identity.IntegrationTest packages.lock.json

* [EC-394] Updated Scim.IntegrationTest packages.lock.json

* [EC-394] dotnet format

* [EC-394] Reverted change on getting GUID from GetOperationPathId

* [EC-394] Fixed sending userId on Patch_AddSingleMember_Success and Patch_RemoveSingleMember_Success

* [EC-394] Updated test to send request with two operations

* [EC-394] Removed Scim dependency from IntegrationTestCommon

* [EC-394] Reverted changes to packages.lock.json.
Ran dotnet format

* [EC-394] Updated Scim.IntegrationTest packages.lock.json

* [EC-394] Updated GroupsControllerTests and UsersControllerTests to implement IAsyncLifetime to cleanup database before each test

* [EC-394] Declared variables for GetList parameters

* [EC-394] Updated AssertHelper.AssertPropertyEqual to compare each item in an IEnumerable property

* [EC-394] Updated AssertHelper.AssertPropertyEqual to check if type is comparable

* [EC-394] Removed unused variable from ScimApplicationFactory

* Apply suggestions from code review

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* [EC-394] Changed test users emails to domain example.com

* [EC-394] Restore solution file

* [EC-394] Added Scim.IntegrationTest to sln

* [EC-394] Updated integration tests to be clearer and check responses in detail

* [EC-394] Using NoopMailService to mock sending email invitations in tests

* [EC-394] Removed multiple references to the same variable ScimApplicationFactory.TestOrganizationId1

* [EC-394] Updated const variable names

* [EC-394] Using AssertPropertyEqualPredicate for IEnumerable properties

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
This commit is contained in:
Rui Tomé 2022-09-08 09:00:59 +01:00 committed by GitHub
parent c085f5d49c
commit 5ecf7b9440
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 4889 additions and 4 deletions

View File

@ -96,6 +96,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure.EFIntegratio
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.IntegrationTest", "test\Api.IntegrationTest\Api.IntegrationTest.csproj", "{CBE96C6D-A4D6-46E1-94C5-42D6CAD8531C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Scim.IntegrationTest", "bitwarden_license\test\Scim.IntegrationTest\Scim.IntegrationTest.csproj", "{FE998849-5FC8-41A2-B7C9-9227901471A0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -232,6 +234,10 @@ Global
{CBE96C6D-A4D6-46E1-94C5-42D6CAD8531C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CBE96C6D-A4D6-46E1-94C5-42D6CAD8531C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CBE96C6D-A4D6-46E1-94C5-42D6CAD8531C}.Release|Any CPU.Build.0 = Release|Any CPU
{FE998849-5FC8-41A2-B7C9-9227901471A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FE998849-5FC8-41A2-B7C9-9227901471A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FE998849-5FC8-41A2-B7C9-9227901471A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FE998849-5FC8-41A2-B7C9-9227901471A0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -269,6 +275,7 @@ Global
{BC3B3F8C-621A-4CB8-9563-6EC0A2C8C747} = {4FDB6543-F68B-4202-9EA6-7FEA984D2D0A}
{7EFB1124-F40A-40EB-9EDA-94FD540AA8FD} = {DD5BD056-4AAE-43EF-BBD2-0B569B8DA84F}
{CBE96C6D-A4D6-46E1-94C5-42D6CAD8531C} = {DD5BD056-4AAE-43EF-BBD2-0B569B8DA84F}
{FE998849-5FC8-41A2-B7C9-9227901471A0} = {287CFF34-BBDB-4BC4-AF88-1E19A5A4679B}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E01CBF68-2E20-425F-9EDB-E0A6510CA92F}

View File

@ -0,0 +1,601 @@
using System.Text.Json;
using Bit.Scim.IntegrationTest.Factories;
using Bit.Scim.Models;
using Bit.Scim.Utilities;
using Bit.Test.Common.Helpers;
using Xunit;
namespace Bit.Scim.IntegrationTest.Controllers.v2;
public class GroupsControllerTests : IClassFixture<ScimApplicationFactory>, IAsyncLifetime
{
private const int _initialGroupCount = 3;
private const int _initialGroupUsersCount = 2;
private readonly ScimApplicationFactory _factory;
public GroupsControllerTests(ScimApplicationFactory factory)
{
_factory = factory;
_factory.DatabaseName = "test_database_groups";
}
public Task InitializeAsync()
{
var databaseContext = _factory.GetDatabaseContext();
_factory.ReinitializeDbForTests(databaseContext);
return Task.CompletedTask;
}
Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask;
[Fact]
public async Task Get_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = ScimApplicationFactory.TestGroupId1;
var expectedResponse = new ScimGroupResponseModel
{
Id = groupId,
DisplayName = "Test Group 1",
ExternalId = "A",
Schemas = new List<string> { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsGetAsync(organizationId, groupId);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimGroupResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task Get_NotFound()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = Guid.NewGuid().ToString();
var expectedResponse = new ScimErrorResponseModel
{
Status = StatusCodes.Status404NotFound,
Detail = "Group not found.",
Schemas = new List<string> { ScimConstants.Scim2SchemaError }
};
var context = await _factory.GroupsGetAsync(organizationId, groupId);
Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimErrorResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task GetList_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
string filter = null;
int? itemsPerPage = 2;
int? startIndex = 1;
var expectedResponse = new ScimListResponseModel<ScimGroupResponseModel>
{
ItemsPerPage = itemsPerPage.Value,
TotalResults = 3,
StartIndex = startIndex.Value,
Resources = new List<ScimGroupResponseModel>
{
new ScimGroupResponseModel
{
Id = ScimApplicationFactory.TestGroupId1,
DisplayName = "Test Group 1",
ExternalId = "A",
Schemas = new List<string> { ScimConstants.Scim2SchemaGroup }
},
new ScimGroupResponseModel
{
Id = ScimApplicationFactory.TestGroupId2,
DisplayName = "Test Group 2",
ExternalId = "B",
Schemas = new List<string> { ScimConstants.Scim2SchemaGroup }
}
},
Schemas = new List<string> { ScimConstants.Scim2SchemaListResponse }
};
var context = await _factory.GroupsGetListAsync(organizationId, filter, itemsPerPage, startIndex);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimListResponseModel<ScimGroupResponseModel>>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task GetList_SearchDisplayName_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
string filter = "displayName eq Test Group 2";
int? itemsPerPage = 10;
int? startIndex = 1;
var expectedResponse = new ScimListResponseModel<ScimGroupResponseModel>
{
ItemsPerPage = itemsPerPage.Value,
TotalResults = 1,
StartIndex = startIndex.Value,
Resources = new List<ScimGroupResponseModel>
{
new ScimGroupResponseModel
{
Id = ScimApplicationFactory.TestGroupId2,
DisplayName = "Test Group 2",
ExternalId = "B",
Schemas = new List<string> { ScimConstants.Scim2SchemaGroup }
}
},
Schemas = new List<string> { ScimConstants.Scim2SchemaListResponse }
};
var context = await _factory.GroupsGetListAsync(organizationId, filter, itemsPerPage, startIndex);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimListResponseModel<ScimGroupResponseModel>>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task GetList_SearchExternalId_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
string filter = "externalId eq C";
int? itemsPerPage = 10;
int? startIndex = 1;
var expectedResponse = new ScimListResponseModel<ScimGroupResponseModel>
{
ItemsPerPage = itemsPerPage.Value,
TotalResults = 1,
StartIndex = startIndex.Value,
Resources = new List<ScimGroupResponseModel>
{
new ScimGroupResponseModel
{
Id = ScimApplicationFactory.TestGroupId3,
DisplayName = "Test Group 3",
ExternalId = "C",
Schemas = new List<string> { ScimConstants.Scim2SchemaGroup }
}
},
Schemas = new List<string> { ScimConstants.Scim2SchemaListResponse }
};
var context = await _factory.GroupsGetListAsync(organizationId, filter, itemsPerPage, startIndex);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimListResponseModel<ScimGroupResponseModel>>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task GetList_EmptyResult_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
string filter = "externalId eq Z";
int? itemsPerPage = 10;
int? startIndex = 1;
var expectedResponse = new ScimListResponseModel<ScimGroupResponseModel>
{
ItemsPerPage = itemsPerPage.Value,
TotalResults = 0,
StartIndex = startIndex.Value,
Resources = new List<ScimGroupResponseModel>(),
Schemas = new List<string> { ScimConstants.Scim2SchemaListResponse }
};
var context = await _factory.GroupsGetListAsync(organizationId, filter, itemsPerPage, startIndex);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimListResponseModel<ScimGroupResponseModel>>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task Post_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var displayName = "New Group";
var externalId = Guid.NewGuid().ToString();
var inputModel = new ScimGroupRequestModel
{
DisplayName = displayName,
ExternalId = externalId.ToString(),
Members = new List<ScimGroupRequestModel.GroupMembersModel>
{
new ScimGroupRequestModel.GroupMembersModel { Display = "user1@example.com", Value = ScimApplicationFactory.TestOrganizationUserId1 }
},
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var expectedResponse = new ScimGroupResponseModel
{
DisplayName = displayName,
ExternalId = externalId,
Schemas = new List<string> { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPostAsync(organizationId, inputModel);
Assert.Equal(StatusCodes.Status201Created, context.Response.StatusCode);
// Verifying that the response includes a header with the URL of the created Group
Assert.Contains(context.Response.Headers, h => h.Key == "Location");
var responseModel = JsonSerializer.Deserialize<ScimGroupResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel, "Id");
Assert.NotNull(responseModel.Id);
var databaseContext = _factory.GetDatabaseContext();
Assert.Equal(_initialGroupCount + 1, databaseContext.Groups.Count());
Assert.True(databaseContext.Groups.Any(g => g.Name == displayName && g.ExternalId == externalId));
Assert.Equal(_initialGroupUsersCount + 1, databaseContext.GroupUsers.Count());
Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId.ToString() == responseModel.Id && gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId1));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task Post_InvalidDisplayName_BadRequest(string displayName)
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var model = new ScimGroupRequestModel
{
DisplayName = displayName,
ExternalId = null,
Members = null,
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPostAsync(organizationId, model);
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);
}
[Fact]
public async Task Post_ExistingExternalId_Conflict()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var model = new ScimGroupRequestModel
{
DisplayName = "New Group",
ExternalId = "A",
Members = null,
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPostAsync(organizationId, model);
Assert.Equal(StatusCodes.Status409Conflict, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
Assert.Equal(_initialGroupCount, databaseContext.Groups.Count());
Assert.False(databaseContext.Groups.Any(g => g.Name == "New Group"));
}
[Fact]
public async Task Put_ChangeNameAndMembers_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = ScimApplicationFactory.TestGroupId1;
var newGroupName = Guid.NewGuid().ToString();
var inputModel = new ScimGroupRequestModel
{
DisplayName = newGroupName,
ExternalId = "A",
Members = new List<ScimGroupRequestModel.GroupMembersModel>
{
new ScimGroupRequestModel.GroupMembersModel { Display = "user2@example.com", Value = ScimApplicationFactory.TestOrganizationUserId2 },
new ScimGroupRequestModel.GroupMembersModel { Display = "user3@example.com", Value = ScimApplicationFactory.TestOrganizationUserId3 }
},
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var expectedResponse = new ScimGroupResponseModel
{
Id = groupId,
DisplayName = newGroupName,
ExternalId = "A",
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPutAsync(organizationId, groupId, inputModel);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimGroupResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
var databaseContext = _factory.GetDatabaseContext();
var firstGroup = databaseContext.Groups.FirstOrDefault(g => g.Id.ToString() == groupId);
Assert.Equal(newGroupName, firstGroup.Name);
Assert.Equal(2, databaseContext.GroupUsers.Count(gu => gu.GroupId.ToString() == groupId));
Assert.NotNull(databaseContext.GroupUsers.FirstOrDefault(gu => gu.GroupId.ToString() == groupId && gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId2));
Assert.NotNull(databaseContext.GroupUsers.FirstOrDefault(gu => gu.GroupId.ToString() == groupId && gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId3));
}
[Fact]
public async Task Put_NotFound()
{
var newGroupName = "Test Group 1 New Name";
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = Guid.NewGuid().ToString();
var inputModel = new ScimGroupRequestModel
{
DisplayName = newGroupName,
ExternalId = "A",
Members = new List<ScimGroupRequestModel.GroupMembersModel>(),
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var expectedResponse = new ScimErrorResponseModel
{
Status = StatusCodes.Status404NotFound,
Detail = "Group not found.",
Schemas = new List<string> { ScimConstants.Scim2SchemaError }
};
var context = await _factory.GroupsPutAsync(organizationId, groupId, inputModel);
Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimErrorResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task Patch_ReplaceDisplayName_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = ScimApplicationFactory.TestGroupId1;
var newDisplayName = "Patch Display Name";
var inputModel = new ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>()
{
new ScimPatchModel.OperationModel
{
Op = "replace",
Value = JsonDocument.Parse($"{{\"displayName\":\"{newDisplayName}\"}}").RootElement
}
},
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
var group = databaseContext.Groups.FirstOrDefault(g => g.Id.ToString() == groupId);
Assert.Equal(newDisplayName, group.Name);
Assert.Equal(_initialGroupUsersCount, databaseContext.GroupUsers.Count());
Assert.True(databaseContext.GroupUsers.Any(gu => gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId1));
Assert.True(databaseContext.GroupUsers.Any(gu => gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId4));
}
[Fact]
public async Task Patch_ReplaceMembers_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = ScimApplicationFactory.TestGroupId1;
var inputModel = new ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>()
{
new ScimPatchModel.OperationModel
{
Op = "replace",
Path = "members",
Value = JsonDocument.Parse($"[{{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId2}\"}}]").RootElement
}
},
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
Assert.Single(databaseContext.GroupUsers);
Assert.Equal(_initialGroupUsersCount - 1, databaseContext.GroupUsers.Count());
var groupUser = databaseContext.GroupUsers.FirstOrDefault();
Assert.Equal(ScimApplicationFactory.TestOrganizationUserId2, groupUser.OrganizationUserId.ToString());
}
[Fact]
public async Task Patch_AddSingleMember_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = ScimApplicationFactory.TestGroupId1;
var inputModel = new ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>()
{
new ScimPatchModel.OperationModel
{
Op = "add",
Path = $"members[value eq \"{ScimApplicationFactory.TestOrganizationUserId2}\"]",
Value = JsonDocument.Parse("{}").RootElement
}
},
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
Assert.Equal(_initialGroupUsersCount + 1, databaseContext.GroupUsers.Count());
Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId.ToString() == groupId && gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId1));
Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId.ToString() == groupId && gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId2));
Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId.ToString() == groupId && gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId4));
}
[Fact]
public async Task Patch_AddListMembers_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = ScimApplicationFactory.TestGroupId2;
var inputModel = new ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>()
{
new ScimPatchModel.OperationModel
{
Op = "add",
Path = "members",
Value = JsonDocument.Parse($"[{{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId2}\"}},{{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId3}\"}}]").RootElement
}
},
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId.ToString() == groupId && gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId2));
Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId.ToString() == groupId && gu.OrganizationUserId.ToString() == ScimApplicationFactory.TestOrganizationUserId3));
}
[Fact]
public async Task Patch_RemoveSingleMember_ReplaceDisplayName_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = ScimApplicationFactory.TestGroupId1;
var newDisplayName = "Patch Display Name";
var inputModel = new ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>()
{
new ScimPatchModel.OperationModel
{
Op = "remove",
Path = $"members[value eq \"{ScimApplicationFactory.TestOrganizationUserId1}\"]",
Value = JsonDocument.Parse("{}").RootElement
},
new ScimPatchModel.OperationModel
{
Op = "replace",
Value = JsonDocument.Parse($"{{\"displayName\":\"{newDisplayName}\"}}").RootElement
}
},
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
Assert.Equal(_initialGroupUsersCount - 1, databaseContext.GroupUsers.Count());
Assert.Equal(_initialGroupCount, databaseContext.Groups.Count());
var group = databaseContext.Groups.FirstOrDefault(g => g.Id.ToString() == groupId);
Assert.Equal(newDisplayName, group.Name);
}
[Fact]
public async Task Patch_RemoveListMembers_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = ScimApplicationFactory.TestGroupId1;
var inputModel = new ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>()
{
new ScimPatchModel.OperationModel
{
Op = "remove",
Path = "members",
Value = JsonDocument.Parse($"[{{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId1}\"}}, {{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId4}\"}}]").RootElement
}
},
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
Assert.Empty(databaseContext.GroupUsers);
}
[Fact]
public async Task Patch_NotFound()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = Guid.NewGuid().ToString();
var inputModel = new Models.ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>(),
Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup }
};
var expectedResponse = new ScimErrorResponseModel
{
Status = StatusCodes.Status404NotFound,
Detail = "Group not found.",
Schemas = new List<string> { ScimConstants.Scim2SchemaError }
};
var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel);
Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimErrorResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task Delete_Success()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = ScimApplicationFactory.TestGroupId3;
var context = await _factory.GroupsDeleteAsync(organizationId, groupId);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
Assert.Equal(_initialGroupCount - 1, databaseContext.Groups.Count());
Assert.True(databaseContext.Groups.FirstOrDefault(g => g.Id.ToString() == groupId) == null);
}
[Fact]
public async Task Delete_NotFound()
{
var organizationId = ScimApplicationFactory.TestOrganizationId1;
var groupId = Guid.NewGuid().ToString();
var expectedResponse = new ScimErrorResponseModel
{
Status = StatusCodes.Status404NotFound,
Detail = "Group not found.",
Schemas = new List<string> { ScimConstants.Scim2SchemaError }
};
var context = await _factory.GroupsDeleteAsync(organizationId, groupId);
Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimErrorResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
}

View File

@ -0,0 +1,547 @@
using System.Text.Json;
using Bit.Core.Enums;
using Bit.Scim.IntegrationTest.Factories;
using Bit.Scim.Models;
using Bit.Scim.Utilities;
using Bit.Test.Common.Helpers;
using Xunit;
namespace Bit.Scim.IntegrationTest.Controllers.v2;
public class UsersControllerTests : IClassFixture<ScimApplicationFactory>, IAsyncLifetime
{
private const int _initialUserCount = 4;
private readonly ScimApplicationFactory _factory;
public UsersControllerTests(ScimApplicationFactory factory)
{
_factory = factory;
_factory.DatabaseName = "test_database_users";
}
public Task InitializeAsync()
{
var databaseContext = _factory.GetDatabaseContext();
_factory.ReinitializeDbForTests(databaseContext);
return Task.CompletedTask;
}
Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask;
[Fact]
public async Task Get_Success()
{
var organizationUserId = ScimApplicationFactory.TestOrganizationUserId1;
var expectedResponse = new ScimUserResponseModel
{
Id = ScimApplicationFactory.TestOrganizationUserId1,
DisplayName = "Test User 1",
ExternalId = "UA",
Active = true,
Emails = new List<BaseScimUserModel.EmailModel>
{
new BaseScimUserModel.EmailModel { Primary = true, Type = "work", Value = "user1@example.com" }
},
Groups = new List<string>(),
Name = new BaseScimUserModel.NameModel("Test User 1"),
UserName = "user1@example.com",
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
};
var context = await _factory.UsersGetAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimUserResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task Get_NotFound()
{
var organizationUserId = Guid.NewGuid().ToString();
var expectedResponse = new ScimErrorResponseModel
{
Status = StatusCodes.Status404NotFound,
Detail = "User not found.",
Schemas = new List<string> { ScimConstants.Scim2SchemaError }
};
var context = await _factory.UsersGetAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId);
Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimErrorResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task GetList_Success()
{
string filter = null;
int? itemsPerPage = 2;
int? startIndex = 1;
var expectedResponse = new ScimListResponseModel<ScimUserResponseModel>
{
ItemsPerPage = itemsPerPage.Value,
// Note: total matching results is larger than resources actually returned due to pagination settings. See https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2
TotalResults = 4,
StartIndex = startIndex.Value,
Resources = new List<ScimUserResponseModel>
{
new ScimUserResponseModel
{
Id = ScimApplicationFactory.TestOrganizationUserId1,
DisplayName = "Test User 1",
ExternalId = "UA",
Active = true,
Emails = new List<BaseScimUserModel.EmailModel>
{
new BaseScimUserModel.EmailModel { Primary = true, Type = "work", Value = "user1@example.com" }
},
Groups = new List<string>(),
Name = new BaseScimUserModel.NameModel("Test User 1"),
UserName = "user1@example.com",
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
},
new ScimUserResponseModel
{
Id = ScimApplicationFactory.TestOrganizationUserId2,
DisplayName = "Test User 2",
ExternalId = "UB",
Active = true,
Emails = new List<BaseScimUserModel.EmailModel>
{
new BaseScimUserModel.EmailModel { Primary = true, Type = "work", Value = "user2@example.com" }
},
Groups = new List<string>(),
Name = new BaseScimUserModel.NameModel("Test User 2"),
UserName = "user2@example.com",
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
}
},
Schemas = new List<string> { ScimConstants.Scim2SchemaListResponse }
};
var context = await _factory.UsersGetListAsync(ScimApplicationFactory.TestOrganizationId1, filter, itemsPerPage, startIndex);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimListResponseModel<ScimUserResponseModel>>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task GetList_SearchUserName_Success()
{
string filter = "userName eq user2@example.com";
int? itemsPerPage = 10;
int? startIndex = 1;
var expectedResponse = new ScimListResponseModel<ScimUserResponseModel>
{
ItemsPerPage = itemsPerPage.Value,
TotalResults = 1,
StartIndex = startIndex.Value,
Resources = new List<ScimUserResponseModel>
{
new ScimUserResponseModel
{
Id = ScimApplicationFactory.TestOrganizationUserId2,
DisplayName = "Test User 2",
ExternalId = "UB",
Active = true,
Emails = new List<BaseScimUserModel.EmailModel>
{
new BaseScimUserModel.EmailModel { Primary = true, Type = "work", Value = "user2@example.com" }
},
Groups = new List<string>(),
Name = new BaseScimUserModel.NameModel("Test User 2"),
UserName = "user2@example.com",
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
}
},
Schemas = new List<string> { ScimConstants.Scim2SchemaListResponse }
};
var context = await _factory.UsersGetListAsync(ScimApplicationFactory.TestOrganizationId1, filter, itemsPerPage, startIndex);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimListResponseModel<ScimUserResponseModel>>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task GetList_SearchExternalId_Success()
{
string filter = "externalId eq UC";
int? itemsPerPage = 10;
int? startIndex = 1;
var expectedResponse = new ScimListResponseModel<ScimUserResponseModel>
{
ItemsPerPage = itemsPerPage.Value,
TotalResults = 1,
StartIndex = startIndex.Value,
Resources = new List<ScimUserResponseModel>
{
new ScimUserResponseModel
{
Id = ScimApplicationFactory.TestOrganizationUserId3,
DisplayName = "Test User 3",
ExternalId = "UC",
Active = false,
Emails = new List<BaseScimUserModel.EmailModel>
{
new BaseScimUserModel.EmailModel { Primary = true, Type = "work", Value = "user3@example.com" }
},
Groups = new List<string>(),
Name = new BaseScimUserModel.NameModel("Test User 3"),
UserName = "user3@example.com",
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
}
},
Schemas = new List<string> { ScimConstants.Scim2SchemaListResponse }
};
var context = await _factory.UsersGetListAsync(ScimApplicationFactory.TestOrganizationId1, filter, itemsPerPage, startIndex);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimListResponseModel<ScimUserResponseModel>>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task GetList_EmptyResult_Success()
{
string filter = "externalId eq UZ";
int? itemsPerPage = 10;
int? startIndex = 1;
var expectedResponse = new ScimListResponseModel<ScimUserResponseModel>
{
ItemsPerPage = itemsPerPage.Value,
TotalResults = 0,
StartIndex = startIndex.Value,
Resources = new List<ScimUserResponseModel>(),
Schemas = new List<string> { ScimConstants.Scim2SchemaListResponse }
};
var context = await _factory.UsersGetListAsync(ScimApplicationFactory.TestOrganizationId1, filter, itemsPerPage, startIndex);
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimListResponseModel<ScimUserResponseModel>>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task Post_Success()
{
var email = "user5@example.com";
var displayName = "Test User 5";
var externalId = "UE";
var inputModel = new ScimUserRequestModel
{
Name = new BaseScimUserModel.NameModel(displayName),
DisplayName = displayName,
Emails = new List<BaseScimUserModel.EmailModel> { new BaseScimUserModel.EmailModel(email) },
ExternalId = externalId,
Active = true,
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
};
var expectedResponse = new ScimUserResponseModel
{
// DisplayName is not being saved
ExternalId = externalId,
Active = true,
Emails = new List<BaseScimUserModel.EmailModel>
{
new BaseScimUserModel.EmailModel { Primary = true, Type = "work", Value = email }
},
Groups = new List<string>(),
Name = new BaseScimUserModel.NameModel(),
UserName = email,
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
};
var context = await _factory.UsersPostAsync(ScimApplicationFactory.TestOrganizationId1, inputModel);
Assert.Equal(StatusCodes.Status201Created, context.Response.StatusCode);
// Verifying that the response includes a header with the URL of the created Group
Assert.Contains(context.Response.Headers, h => h.Key == "Location");
var responseModel = JsonSerializer.Deserialize<ScimUserResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel, "Id");
Assert.NotNull(responseModel.Id);
var databaseContext = _factory.GetDatabaseContext();
Assert.Equal(_initialUserCount + 1, databaseContext.OrganizationUsers.Count());
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task Post_InvalidEmail_BadRequest(string email)
{
var displayName = "Test User 5";
var externalId = "UE";
var inputModel = new ScimUserRequestModel
{
Name = new BaseScimUserModel.NameModel(displayName),
DisplayName = displayName,
Emails = new List<BaseScimUserModel.EmailModel> { new BaseScimUserModel.EmailModel(email) },
ExternalId = externalId,
Active = true,
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
};
var context = await _factory.UsersPostAsync(ScimApplicationFactory.TestOrganizationId1, inputModel);
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);
}
[Fact]
public async Task Post_Inactive_BadRequest()
{
var displayName = "Test User 5";
var inputModel = new ScimUserRequestModel
{
DisplayName = displayName,
ExternalId = null,
Active = false,
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
};
var context = await _factory.UsersPostAsync(ScimApplicationFactory.TestOrganizationId1, inputModel);
Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);
}
[Theory]
[InlineData("user1@example.com", "UZ")]
[InlineData("userZ@example.com", "UA")]
public async Task Post_ExistingData_Conflict(string email, string externalId)
{
var inputModel = new ScimUserRequestModel
{
DisplayName = "New User",
Emails = new List<BaseScimUserModel.EmailModel> { new BaseScimUserModel.EmailModel(email) },
ExternalId = externalId,
Schemas = null,
Active = true
};
var context = await _factory.UsersPostAsync(ScimApplicationFactory.TestOrganizationId1, inputModel);
Assert.Equal(StatusCodes.Status409Conflict, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
Assert.Equal(_initialUserCount, databaseContext.OrganizationUsers.Count());
}
[Fact]
public async Task Put_RevokeUser_Success()
{
var organizationUserId = ScimApplicationFactory.TestOrganizationUserId2;
var inputModel = new ScimUserRequestModel
{
Active = false
};
var expectedResponse = new ScimUserResponseModel
{
Id = ScimApplicationFactory.TestOrganizationUserId2,
DisplayName = "Test User 2",
ExternalId = "UB",
Active = false,
Emails = new List<BaseScimUserModel.EmailModel>
{
new BaseScimUserModel.EmailModel { Primary = true, Type = "work", Value = "user2@example.com" }
},
Groups = new List<string>(),
Name = new BaseScimUserModel.NameModel("Test User 2"),
UserName = "user2@example.com",
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
};
var context = await _factory.UsersPutAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId, inputModel);
var responseModel = JsonSerializer.Deserialize<ScimUserResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
var databaseContext = _factory.GetDatabaseContext();
var revokedUser = databaseContext.OrganizationUsers.FirstOrDefault(g => g.Id.ToString() == organizationUserId);
Assert.Equal(OrganizationUserStatusType.Revoked, revokedUser.Status);
}
[Fact]
public async Task Put_RestoreUser_Success()
{
var organizationUserId = ScimApplicationFactory.TestOrganizationUserId3;
var inputModel = new ScimUserRequestModel
{
Active = true
};
var expectedResponse = new ScimUserResponseModel
{
Id = ScimApplicationFactory.TestOrganizationUserId3,
DisplayName = "Test User 3",
ExternalId = "UC",
Active = true,
Emails = new List<BaseScimUserModel.EmailModel>
{
new BaseScimUserModel.EmailModel { Primary = true, Type = "work", Value = "user3@example.com" }
},
Groups = new List<string>(),
Name = new BaseScimUserModel.NameModel("Test User 3"),
UserName = "user3@example.com",
Schemas = new List<string> { ScimConstants.Scim2SchemaUser }
};
var context = await _factory.UsersPutAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId, inputModel);
var responseModel = JsonSerializer.Deserialize<ScimUserResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
var databaseContext = _factory.GetDatabaseContext();
var revokedUser = databaseContext.OrganizationUsers.FirstOrDefault(g => g.Id.ToString() == organizationUserId);
Assert.NotEqual(OrganizationUserStatusType.Revoked, revokedUser.Status);
}
[Fact]
public async Task Put_NotFound()
{
var organizationUserId = Guid.NewGuid();
var inputModel = new ScimUserRequestModel
{
DisplayName = "Test Group 1",
ExternalId = "AA",
Schemas = new List<string>()
};
var expectedResponse = new ScimErrorResponseModel
{
Status = StatusCodes.Status404NotFound,
Detail = "User not found.",
Schemas = new List<string> { ScimConstants.Scim2SchemaError }
};
var context = await _factory.UsersPutAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId.ToString(), inputModel);
Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimErrorResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task Patch_ReplaceRevoke_Success()
{
var organizationUserId = ScimApplicationFactory.TestOrganizationUserId2;
var inputModel = new ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>()
{
new ScimPatchModel.OperationModel { Op = "replace", Value = JsonDocument.Parse("{\"active\":false}").RootElement },
},
Schemas = new List<string>()
};
var context = await _factory.UsersPatchAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId, inputModel);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
var organizationUser = databaseContext.OrganizationUsers.FirstOrDefault(g => g.Id.ToString() == organizationUserId);
Assert.Equal(OrganizationUserStatusType.Revoked, organizationUser.Status);
}
[Fact]
public async Task Patch_ReplaceRestore_Success()
{
var organizationUserId = ScimApplicationFactory.TestOrganizationUserId3;
var inputModel = new ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>()
{
new ScimPatchModel.OperationModel { Op = "replace", Value = JsonDocument.Parse("{\"active\":true}").RootElement },
},
Schemas = new List<string>()
};
var context = await _factory.UsersPatchAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId, inputModel);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
var organizationUser = databaseContext.OrganizationUsers.FirstOrDefault(g => g.Id.ToString() == organizationUserId);
Assert.NotEqual(OrganizationUserStatusType.Revoked, organizationUser.Status);
}
[Fact]
public async Task Patch_NotFound()
{
var organizationUserId = Guid.NewGuid().ToString();
var inputModel = new Models.ScimPatchModel
{
Operations = new List<ScimPatchModel.OperationModel>(),
Schemas = new List<string>()
};
var expectedResponse = new ScimErrorResponseModel
{
Status = StatusCodes.Status404NotFound,
Detail = "User not found.",
Schemas = new List<string> { ScimConstants.Scim2SchemaError }
};
var context = await _factory.UsersPatchAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId, inputModel);
Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimErrorResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
}
[Fact]
public async Task Delete_Success()
{
var organizationUserId = ScimApplicationFactory.TestOrganizationUserId1;
var inputModel = new ScimUserRequestModel();
var context = await _factory.UsersDeleteAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId, inputModel);
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
var databaseContext = _factory.GetDatabaseContext();
Assert.Equal(_initialUserCount - 1, databaseContext.OrganizationUsers.Count());
Assert.False(databaseContext.OrganizationUsers.Any(g => g.Id.ToString() == organizationUserId));
}
[Fact]
public async Task Delete_NotFound()
{
var organizationUserId = Guid.NewGuid().ToString();
var inputModel = new ScimUserRequestModel();
var expectedResponse = new ScimErrorResponseModel
{
Status = StatusCodes.Status404NotFound,
Detail = "User not found.",
Schemas = new List<string> { ScimConstants.Scim2SchemaError }
};
var context = await _factory.UsersDeleteAsync(ScimApplicationFactory.TestOrganizationId1, organizationUserId, inputModel);
Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode);
var responseModel = JsonSerializer.Deserialize<ScimErrorResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
AssertHelper.AssertPropertyEqual(expectedResponse, responseModel);
var databaseContext = _factory.GetDatabaseContext();
Assert.Equal(_initialUserCount, databaseContext.OrganizationUsers.Count());
}
}

View File

@ -0,0 +1,253 @@
using System.Net.Mime;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using Bit.Core.Services;
using Bit.Infrastructure.EntityFramework.Repositories;
using Bit.IntegrationTestCommon.Factories;
using Bit.Scim.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
namespace Bit.Scim.IntegrationTest.Factories;
public class ScimApplicationFactory : WebApplicationFactoryBase<Startup>
{
public readonly new TestServer Server;
public const string TestUserId1 = "2e8173db-8e8d-4de1-ac38-91b15c6d8dcb";
public const string TestUserId2 = "b57846fc-0e94-4c93-9de5-9d0389eeadfb";
public const string TestUserId3 = "20713eb8-d0c5-4655-b855-1a0f3472ccb5";
public const string TestUserId4 = "cee613af-d0cb-4db9-ab9d-579bb120fd2a";
public const string TestGroupId1 = "dcb232e8-761d-4152-a510-be2778d037cb";
public const string TestGroupId2 = "562e5371-7020-40b6-b092-099ac66dbdf9";
public const string TestGroupId3 = "362c2782-0f1f-4c86-95dd-edbdf7d6040b";
public const string TestOrganizationId1 = "fb98e04f-0303-4914-9b37-a983943bf1ca";
public const string TestOrganizationUserId1 = "5d421196-8c59-485b-8926-2d6d0101e05f";
public const string TestOrganizationUserId2 = "3a63d520-0d84-4679-b887-13fe2058d53b";
public const string TestOrganizationUserId3 = "be2f9045-e2b6-4173-ad44-4c69c3ea8140";
public const string TestOrganizationUserId4 = "1f5689b7-e96e-4840-b0b1-eb3d5b5fd514";
public ScimApplicationFactory()
{
WebApplicationFactory<Startup> webApplicationFactory = WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services
.AddAuthentication("Test")
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", options => { });
// Override to bypass SCIM authorization
services.AddAuthorization(config =>
{
config.AddPolicy("Scim", policy =>
{
policy.RequireAssertion(a => true);
});
});
var mailService = services.First(sd => sd.ServiceType == typeof(IMailService));
services.Remove(mailService);
services.AddSingleton<IMailService, NoopMailService>();
});
});
Server = webApplicationFactory.Server;
}
public async Task<HttpContext> GroupsGetAsync(string organizationId, string id)
{
return await Server.GetAsync($"/v2/{organizationId}/groups/{id}");
}
public async Task<HttpContext> GroupsGetListAsync(string organizationId, string filter, int? count, int? startIndex)
{
var queryString = new QueryString("?");
if (!string.IsNullOrWhiteSpace(filter))
{
queryString = queryString.Add("filter", filter);
}
if (count.HasValue)
{
queryString = queryString.Add("count", count.ToString());
}
if (startIndex.HasValue)
{
queryString = queryString.Add("startIndex", startIndex.ToString());
}
return await Server.GetAsync($"/v2/{organizationId}/groups", httpContext => httpContext.Request.QueryString = queryString);
}
public async Task<HttpContext> GroupsPostAsync(string organizationId, ScimGroupRequestModel model)
{
return await Server.PostAsync($"/v2/{organizationId}/groups", GetStringContent(model), httpContext => httpContext.Request.Headers.Add(HeaderNames.UserAgent, "Okta"));
}
public async Task<HttpContext> GroupsPutAsync(string organizationId, string id, ScimGroupRequestModel model)
{
return await Server.PutAsync($"/v2/{organizationId}/groups/{id}", GetStringContent(model), httpContext => httpContext.Request.Headers.Add(HeaderNames.UserAgent, "Okta"));
}
public async Task<HttpContext> GroupsPatchAsync(string organizationId, string id, ScimPatchModel model)
{
return await Server.PatchAsync($"/v2/{organizationId}/groups/{id}", GetStringContent(model));
}
public async Task<HttpContext> GroupsDeleteAsync(string organizationId, string id)
{
return await Server.DeleteAsync($"/v2/{organizationId}/groups/{id}", null);
}
public async Task<HttpContext> UsersGetAsync(string organizationId, string id)
{
return await Server.GetAsync($"/v2/{organizationId}/users/{id}");
}
public async Task<HttpContext> UsersGetListAsync(string organizationId, string filter, int? count, int? startIndex)
{
var queryString = new QueryString("?");
if (!string.IsNullOrWhiteSpace(filter))
{
queryString = queryString.Add("filter", filter);
}
if (count.HasValue)
{
queryString = queryString.Add("count", count.ToString());
}
if (startIndex.HasValue)
{
queryString = queryString.Add("startIndex", startIndex.ToString());
}
return await Server.GetAsync($"/v2/{organizationId}/users", httpContext => httpContext.Request.QueryString = queryString);
}
public async Task<HttpContext> UsersPostAsync(string organizationId, ScimUserRequestModel model)
{
return await Server.PostAsync($"/v2/{organizationId}/users", GetStringContent(model));
}
public async Task<HttpContext> UsersPutAsync(string organizationId, string id, ScimUserRequestModel model)
{
return await Server.PutAsync($"/v2/{organizationId}/users/{id}", GetStringContent(model));
}
public async Task<HttpContext> UsersPatchAsync(string organizationId, string id, ScimPatchModel model)
{
return await Server.PatchAsync($"/v2/{organizationId}/users/{id}", GetStringContent(model));
}
public async Task<HttpContext> UsersDeleteAsync(string organizationId, string id, ScimUserRequestModel model)
{
return await Server.DeleteAsync($"/v2/{organizationId}/users/{id}", GetStringContent(model));
}
public void InitializeDbForTests(DatabaseContext databaseContext)
{
databaseContext.Organizations.AddRange(GetSeedingOrganizations());
databaseContext.Groups.AddRange(GetSeedingGroups());
databaseContext.Users.AddRange(GetSeedingUsers());
databaseContext.OrganizationUsers.AddRange(GetSeedingOrganizationUsers());
databaseContext.GroupUsers.AddRange(GetSeedingGroupUsers());
databaseContext.SaveChanges();
}
public void ReinitializeDbForTests(DatabaseContext databaseContext)
{
databaseContext.Organizations.RemoveRange(databaseContext.Organizations);
databaseContext.Groups.RemoveRange(databaseContext.Groups);
databaseContext.Users.RemoveRange(databaseContext.Users);
databaseContext.OrganizationUsers.RemoveRange(databaseContext.OrganizationUsers);
databaseContext.GroupUsers.RemoveRange(databaseContext.GroupUsers);
databaseContext.SaveChanges();
InitializeDbForTests(databaseContext);
}
private List<Infrastructure.EntityFramework.Models.User> GetSeedingUsers()
{
return new List<Infrastructure.EntityFramework.Models.User>()
{
new Infrastructure.EntityFramework.Models.User { Id = Guid.Parse(TestUserId1), Name = "Test User 1", ApiKey = "", Email = "user1@example.com", SecurityStamp = "" },
new Infrastructure.EntityFramework.Models.User { Id = Guid.Parse(TestUserId2), Name = "Test User 2", ApiKey = "", Email = "user2@example.com", SecurityStamp = "" },
new Infrastructure.EntityFramework.Models.User { Id = Guid.Parse(TestUserId3), Name = "Test User 3", ApiKey = "", Email = "user3@example.com", SecurityStamp = "" },
new Infrastructure.EntityFramework.Models.User { Id = Guid.Parse(TestUserId4), Name = "Test User 4", ApiKey = "", Email = "user4@example.com", SecurityStamp = "" },
};
}
private List<Infrastructure.EntityFramework.Models.Group> GetSeedingGroups()
{
return new List<Infrastructure.EntityFramework.Models.Group>()
{
new Infrastructure.EntityFramework.Models.Group { Id = Guid.Parse(TestGroupId1), OrganizationId = Guid.Parse(TestOrganizationId1), Name = "Test Group 1", ExternalId = "A" },
new Infrastructure.EntityFramework.Models.Group { Id = Guid.Parse(TestGroupId2), OrganizationId = Guid.Parse(TestOrganizationId1), Name = "Test Group 2", ExternalId = "B" },
new Infrastructure.EntityFramework.Models.Group { Id = Guid.Parse(TestGroupId3), OrganizationId = Guid.Parse(TestOrganizationId1), Name = "Test Group 3", ExternalId = "C" }
};
}
private List<Infrastructure.EntityFramework.Models.Organization> GetSeedingOrganizations()
{
return new List<Infrastructure.EntityFramework.Models.Organization>()
{
new Infrastructure.EntityFramework.Models.Organization { Id = Guid.Parse(TestOrganizationId1), Name = "Test Organization 1", UseGroups = true }
};
}
private List<Infrastructure.EntityFramework.Models.OrganizationUser> GetSeedingOrganizationUsers()
{
return new List<Infrastructure.EntityFramework.Models.OrganizationUser>()
{
new Infrastructure.EntityFramework.Models.OrganizationUser { Id = Guid.Parse(TestOrganizationUserId1), OrganizationId = Guid.Parse(TestOrganizationId1), UserId = Guid.Parse(TestUserId1), Status = Core.Enums.OrganizationUserStatusType.Confirmed, ExternalId = "UA", Email = "user1@example.com" },
new Infrastructure.EntityFramework.Models.OrganizationUser { Id = Guid.Parse(TestOrganizationUserId2), OrganizationId = Guid.Parse(TestOrganizationId1), UserId = Guid.Parse(TestUserId2), Status = Core.Enums.OrganizationUserStatusType.Confirmed, ExternalId = "UB", Email = "user2@example.com" },
new Infrastructure.EntityFramework.Models.OrganizationUser { Id = Guid.Parse(TestOrganizationUserId3), OrganizationId = Guid.Parse(TestOrganizationId1), UserId = Guid.Parse(TestUserId3), Status = Core.Enums.OrganizationUserStatusType.Revoked, ExternalId = "UC", Email = "user3@example.com" },
new Infrastructure.EntityFramework.Models.OrganizationUser { Id = Guid.Parse(TestOrganizationUserId4), OrganizationId = Guid.Parse(TestOrganizationId1), UserId = Guid.Parse(TestUserId4), Status = Core.Enums.OrganizationUserStatusType.Confirmed, ExternalId = "UD", Email = "user4@example.com" },
};
}
private List<Infrastructure.EntityFramework.Models.GroupUser> GetSeedingGroupUsers()
{
return new List<Infrastructure.EntityFramework.Models.GroupUser>()
{
new Infrastructure.EntityFramework.Models.GroupUser { GroupId = Guid.Parse(TestGroupId1), OrganizationUserId = Guid.Parse(TestOrganizationUserId1) },
new Infrastructure.EntityFramework.Models.GroupUser { GroupId = Guid.Parse(TestGroupId1), OrganizationUserId = Guid.Parse(TestOrganizationUserId4) }
};
}
private static StringContent GetStringContent(object obj) => new(JsonSerializer.Serialize(obj), Encoding.Default, MediaTypeNames.Application.Json);
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new[]
{
new Claim(ClaimTypes.Name, "Test user"),
new Claim("orgadmin", TestOrganizationId1)
};
var identity = new ClaimsIdentity(claims, "Test");
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "Test");
var result = AuthenticateResult.Success(ticket);
return Task.FromResult(result);
}
}
}

View File

@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="$(CoverletCollectorVersion)">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.5" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftNetTestSdkVersion)" />
<PackageReference Include="NSubstitute" Version="$(NSubstitueVersion)" />
<PackageReference Include="xunit" Version="$(XUnitVersion)" />
<PackageReference Include="xunit.runner.visualstudio" Version="$(XUnitRunnerVisualStudioVersion)">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="AutoFixture.Xunit2" Version="$(AutoFixtureXUnit2Version)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Scim\Scim.csproj" />
<ProjectReference Include="..\..\..\test\Common\Common.csproj" />
<ProjectReference Include="..\..\..\test\IntegrationTestCommon\IntegrationTestCommon.csproj" />
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Collections;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.Json;
@ -25,7 +26,7 @@ public static class AssertHelper
throw new Exception("Actual object is null but expected is not");
}
foreach (var expectedPropInfo in expected.GetType().GetProperties().Where(pi => !relevantExcludedProperties.Contains(pi.Name)))
foreach (var expectedPropInfo in expected.GetType().GetProperties().Where(pi => !relevantExcludedProperties.Contains(pi.Name) && !pi.GetIndexParameters().Any()))
{
var actualPropInfo = actual.GetType().GetProperty(expectedPropInfo.Name);
@ -36,7 +37,7 @@ public static class AssertHelper
$"Actual:\n{JsonSerializer.Serialize(actual, JsonHelpers.Indented)}"));
}
if (expectedPropInfo.PropertyType == typeof(string) || expectedPropInfo.PropertyType.IsValueType)
if (typeof(IComparable).IsAssignableFrom(expectedPropInfo.PropertyType) || expectedPropInfo.PropertyType.IsPrimitive || expectedPropInfo.PropertyType.IsValueType)
{
Assert.Equal(expectedPropInfo.GetValue(expected), actualPropInfo.GetValue(actual));
}
@ -45,6 +46,13 @@ public static class AssertHelper
static string JsonDocString(PropertyInfo info, object obj) => JsonSerializer.Serialize(info.GetValue(obj));
Assert.Equal(JsonDocString(expectedPropInfo, expected), JsonDocString(actualPropInfo, actual));
}
else if (typeof(IEnumerable).IsAssignableFrom(expectedPropInfo.PropertyType) && typeof(IEnumerable).IsAssignableFrom(actualPropInfo.PropertyType))
{
var expectedItems = ((IEnumerable)expectedPropInfo.GetValue(expected)).Cast<object>();
var actualItems = ((IEnumerable)actualPropInfo.GetValue(actual)).Cast<object>();
AssertPropertyEqualPredicate(expectedItems, excludedPropertyStrings)(actualItems);
}
else
{
var prefix = $"{expectedPropInfo.PropertyType.Name}.";

View File

@ -46,6 +46,21 @@ public static class WebApplicationFactoryExtensions
string requestUri,
Action<HttpContext> extraConfiguration = null)
=> SendAsync(server, HttpMethod.Get, requestUri, content: null, extraConfiguration);
public static Task<HttpContext> PutAsync(this TestServer server,
string requestUri,
HttpContent content,
Action<HttpContext> extraConfiguration = null)
=> SendAsync(server, HttpMethod.Put, requestUri, content, extraConfiguration);
public static Task<HttpContext> PatchAsync(this TestServer server,
string requestUri,
HttpContent content,
Action<HttpContext> extraConfiguration = null)
=> SendAsync(server, HttpMethod.Patch, requestUri, content, extraConfiguration);
public static Task<HttpContext> DeleteAsync(this TestServer server,
string requestUri,
HttpContent content,
Action<HttpContext> extraConfiguration = null)
=> SendAsync(server, HttpMethod.Delete, requestUri, content: content, extraConfiguration);
public static HttpContext SetAuthEmail(this HttpContext context, string username)
{