diff --git a/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs index dcb94da6bc..67e9721271 100644 --- a/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs @@ -21,6 +21,7 @@ using Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Models; using Org.Eclipse.TractusX.Portal.Backend.Framework.Async; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; +using Org.Eclipse.TractusX.Portal.Backend.Framework.Linq; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; @@ -29,6 +30,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library; +using System.Collections.Immutable; using System.Text.Json; namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLogic; @@ -82,14 +84,14 @@ public Task> ModifyCoreOfferUserRolesAsync(Guid offe offerId, companyUserId, roles, companyId, data => { - var userName = $"{data.firstname} {data.lastname}"; + var userName = $"{data.Firstname} {data.Lastname}"; return (JsonSerializer.Serialize(new { - OfferId = data.offerId, - CoreOfferName = data.offerName, + OfferId = data.OfferId, + CoreOfferName = data.OfferName, Username = string.IsNullOrWhiteSpace(userName) ? "User" : userName, - RemovedRoles = string.Join(",", data.removedRoles), - AddedRoles = string.Join(",", data.addedRoles) + RemovedRoles = string.Join(",", data.RemovedRoles), + AddedRoles = string.Join(",", data.AddedRoles) }, _options), NotificationTypeId.ROLE_UPDATE_CORE_OFFER); }); } @@ -99,18 +101,18 @@ public Task> ModifyAppUserRolesAsync(Guid appId, Gui () => _portalRepositories.GetInstance() .GetAppAssignedIamClientUserDataUntrackedAsync(appId, companyUserId, _identityData.CompanyId), (Guid companyUserId, IEnumerable roles, Guid offerId) => _portalRepositories.GetInstance() - .GetAssignedAndMatchingAppRoles(companyUserId, roles, offerId), + .GetAssignedAndMatchingAppRoles(companyUserId, roles, offerId).Select(x => new UserRoleModificationData(x.UserRoleText, x.RoleId, x.IsAssigned, true)), appId, companyUserId, roles, _identityData.CompanyId, data => { - var userName = $"{data.firstname} {data.lastname}"; + var userName = $"{data.Firstname} {data.Lastname}"; return (JsonSerializer.Serialize(new { - OfferId = data.offerId, - AppName = data.offerName, + OfferId = data.OfferId, + AppName = data.OfferName, Username = string.IsNullOrWhiteSpace(userName) ? "User" : userName, - RemovedRoles = string.Join(",", data.removedRoles), - AddedRoles = string.Join(",", data.addedRoles) + RemovedRoles = string.Join(",", data.RemovedRoles), + AddedRoles = string.Join(",", data.AddedRoles) }, _options), NotificationTypeId.ROLE_UPDATE_APP_OFFER); }); @@ -120,14 +122,14 @@ public Task> ModifyUserRoleAsync(Guid appId, UserRol () => _portalRepositories.GetInstance() .GetAppAssignedIamClientUserDataUntrackedAsync(appId, userRoleInfo.CompanyUserId, _identityData.CompanyId), (Guid companyUserId, IEnumerable roles, Guid offerId) => _portalRepositories.GetInstance() - .GetAssignedAndMatchingAppRoles(companyUserId, roles, offerId), + .GetAssignedAndMatchingAppRoles(companyUserId, roles, offerId).Select(x => new UserRoleModificationData(x.UserRoleText, x.RoleId, x.IsAssigned, true)), appId, userRoleInfo.CompanyUserId, userRoleInfo.Roles, _identityData.CompanyId, null); private async Task> ModifyUserRolesInternal( Func> getIamUserData, Func, Guid, IAsyncEnumerable> getUserRoleModificationData, Guid offerId, Guid companyUserId, IEnumerable roles, Guid adminCompanyId, - Func<(Guid offerId, string offerName, string? firstname, string? lastname, IEnumerable removedRoles, IEnumerable addedRoles), (string content, NotificationTypeId notificationTypeId)>? getNotificationData) + Func<(Guid OfferId, string OfferName, string? Firstname, string? Lastname, IEnumerable RemovedRoles, IEnumerable AddedRoles), (string Content, NotificationTypeId NotificationTypeId)>? getNotificationData) { var result = await getIamUserData().ConfigureAwait(false); if (result == default) @@ -158,19 +160,19 @@ private async Task> ModifyUserRolesInternal( var iamUserId = await _provisioningManager.GetUserByUserName(companyUserId.ToString()).ConfigureAwait(false) ?? throw new ConflictException($"user {companyUserId} is not associated with any iamUser"); - var distinctRoles = roles.Where(role => !string.IsNullOrWhiteSpace(role)).Distinct().ToList(); + var distinctRoles = roles.Where(role => !string.IsNullOrWhiteSpace(role)).Distinct().ToImmutableList(); var existingRoles = await getUserRoleModificationData(companyUserId, distinctRoles, offerId).ToListAsync().ConfigureAwait(false); - var nonExistingRoles = distinctRoles.Except(existingRoles.Select(r => r.CompanyUserRoleText)); - if (nonExistingRoles.Any()) - { - throw new ControllerArgumentException($"Invalid roles {string.Join(",", nonExistingRoles)}", nameof(roles)); - } - var rolesToAdd = existingRoles.Where(role => !role.IsAssignedToUser); - var rolesToDelete = existingRoles.Where(x => x.IsAssignedToUser).ExceptBy(distinctRoles, role => role.CompanyUserRoleText); + existingRoles.DuplicatesBy(x => x.CompanyUserRoleText).IfAny( + duplicateRoles => throw new ConflictException($"roles {string.Join(",", $"{duplicateRoles.Select(role => $"[{role.CompanyUserRoleText}, {role.CompanyUserRoleId}]")}")} are ambigous")); + + distinctRoles.Except(existingRoles.Where(r => r.IsAssignable).Select(r => r.CompanyUserRoleText)).IfAny( + nonExistingRoles => throw new ControllerArgumentException($"Invalid roles {string.Join(",", nonExistingRoles)}", nameof(roles))); + + var rolesToAdd = existingRoles.Where(role => !role.IsAssigned && role.IsAssignable); + var rolesToDelete = existingRoles.Where(role => role.IsAssigned).ExceptBy(distinctRoles, role => role.CompanyUserRoleText).ToImmutableList(); - var rolesNotAdded = rolesToAdd.Any() - ? rolesToAdd.Except(await AddRoles(companyUserId, result.IamClientIds, rolesToAdd, iamUserId).ConfigureAwait(false)) - : Enumerable.Empty(); + var rolesAdded = await AddRoles(companyUserId, result.IamClientIds, rolesToAdd, iamUserId).ConfigureAwait(false); + var rolesNotAdded = rolesToAdd.ExceptBy(rolesAdded.Select(role => role.CompanyUserRoleId), role => role.CompanyUserRoleId); if (rolesToDelete.Any()) { @@ -185,14 +187,14 @@ private async Task> ModifyUserRolesInternal( result.Firstname, result.Lastname, rolesToDelete.Select(x => x.CompanyUserRoleText), - rolesToAdd.Select(x => x.CompanyUserRoleText) + rolesAdded.Select(x => x.CompanyUserRoleText) ); var notificationData = getNotificationData(data); _portalRepositories.GetInstance().CreateNotification(companyUserId, - notificationData.notificationTypeId, false, + notificationData.NotificationTypeId, false, notification => { - notification.Content = notificationData.content; + notification.Content = notificationData.Content; }); } diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/ClearinghouseData.cs b/src/portalbackend/PortalBackend.DBAccess/Models/ClearinghouseData.cs index 6f05a87365..943a588064 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/ClearinghouseData.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/ClearinghouseData.cs @@ -39,4 +39,4 @@ public record ParticipantDetails( [property: JsonPropertyName("countryAlpha2Code")] string CountryAlpha2Code ); -public record UniqueIdData(string Type, string Value); +public record UniqueIdData([property: JsonPropertyName("type")] string Type, [property: JsonPropertyName("value")] string Value); diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserRoleWithId.cs b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserRoleWithId.cs index b1341b2006..e812bf325b 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserRoleWithId.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserRoleWithId.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -22,4 +21,4 @@ namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; public record UserRoleWithId(string CompanyUserRoleText, Guid CompanyUserRoleId); -public record UserRoleModificationData(string CompanyUserRoleText, Guid CompanyUserRoleId, bool IsAssignedToUser); +public record UserRoleModificationData(string CompanyUserRoleText, Guid CompanyUserRoleId, bool IsAssigned, bool IsAssignable); diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRolesRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRolesRepository.cs index 732ecbc8c5..131774227d 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRolesRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRolesRepository.cs @@ -55,8 +55,8 @@ public interface IUserRolesRepository /// Returns a list of user role ids IAsyncEnumerable GetUserRolesForOfferIdAsync(Guid offerId); - IAsyncEnumerable GetAssignedAndMatchingAppRoles(Guid companyUserId, IEnumerable userRoles, Guid offerId); - IAsyncEnumerable GetAssignedAndMatchingCoreOfferRoles(Guid companyUserId, IEnumerable userRoles, Guid offerId); + IAsyncEnumerable<(string UserRoleText, Guid RoleId, bool IsAssigned)> GetAssignedAndMatchingAppRoles(Guid identityId, IEnumerable userRoles, Guid offerId); + IAsyncEnumerable GetAssignedAndMatchingCoreOfferRoles(Guid identityId, IEnumerable userRoles, Guid offerId); /// /// Get user name data by assinged roles diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRolesRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRolesRepository.cs index 29f8f3f6b1..5dca6ef6f8 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRolesRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRolesRepository.cs @@ -97,32 +97,44 @@ public async IAsyncEnumerable GetUserRoleIdsUntrackedAsync(IEnumerable GetAssignedAndMatchingAppRoles(Guid companyUserId, IEnumerable userRoles, Guid offerId) => + public IAsyncEnumerable<(string UserRoleText, Guid RoleId, bool IsAssigned)> GetAssignedAndMatchingAppRoles(Guid identityId, IEnumerable userRoles, Guid offerId) => _dbContext.UserRoles .AsNoTracking() - .Where(role => - role.OfferId == offerId && - (userRoles.Contains(role.UserRoleText) || - role.IdentityAssignedRoles.Select(u => u.Identity!).Any(user => user.Id == companyUserId))) - .Select(userRole => new UserRoleModificationData( - userRole.UserRoleText, - userRole.Id, - userRole.IdentityAssignedRoles.Select(u => u.Identity!).Any(user => user.Id == companyUserId) + .Where(role => role.OfferId == offerId) + .Select(role => new + { + Role = role, + IsAssigned = role.IdentityAssignedRoles.Any(iar => iar.IdentityId == identityId) + }) + .Where(x => + userRoles.Contains(x.Role.UserRoleText) || + x.IsAssigned) + .Select(x => new ValueTuple( + x.Role.UserRoleText, + x.Role.Id, + x.IsAssigned )) .ToAsyncEnumerable(); - public IAsyncEnumerable GetAssignedAndMatchingCoreOfferRoles(Guid companyUserId, IEnumerable userRoles, Guid offerId) => + public IAsyncEnumerable GetAssignedAndMatchingCoreOfferRoles(Guid identityId, IEnumerable userRoles, Guid offerId) => _dbContext.UserRoles .AsNoTracking() - .Where(role => - role.OfferId == offerId && - role.UserRoleCollections.Any(collection => collection.CompanyRoleAssignedRoleCollection!.CompanyRole!.CompanyAssignedRoles.Any(assigned => assigned.Company!.Identities.Any(user => user.Id == companyUserId))) && - (userRoles.Contains(role.UserRoleText) || - role.IdentityAssignedRoles.Select(u => u.Identity!).Any(user => user.Id == companyUserId))) - .Select(userRole => new UserRoleModificationData( - userRole.UserRoleText, - userRole.Id, - userRole.IdentityAssignedRoles.Select(u => u.Identity!).Any(user => user.Id == companyUserId) + .Where(role => role.OfferId == offerId) + .Select(role => new + { + Role = role, + IsAssigned = role.IdentityAssignedRoles.Any(iar => iar.IdentityId == identityId), + IsAssignable = role.UserRoleCollections.Any(collection => collection.CompanyRoleAssignedRoleCollection!.CompanyRole!.CompanyAssignedRoles.Any(assigned => assigned.Company!.Identities.Any(identity => identity.Id == identityId))) + }) + .Where(x => + userRoles.Contains(x.Role.UserRoleText) || + x.IsAssigned || + x.IsAssignable) + .Select(x => new UserRoleModificationData( + x.Role.UserRoleText, + x.Role.Id, + x.IsAssigned, + x.IsAssignable )) .ToAsyncEnumerable(); diff --git a/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs b/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs index 64a0c949fa..82e518c4cb 100644 --- a/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs +++ b/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs @@ -29,7 +29,7 @@ public interface IRegistrationBusinessLogic { Task GetCompanyBpdmDetailDataByBusinessPartnerNumber(string businessPartnerNumber, string token, CancellationToken cancellationToken); IAsyncEnumerable GetClientRolesCompositeAsync(); - Task UploadDocumentAsync(Guid applicationId, IFormFile document, DocumentTypeId documentTypeId, CancellationToken cancellationToken); + Task UploadDocumentAsync(Guid applicationId, IFormFile document, DocumentTypeId documentTypeId, CancellationToken cancellationToken); /// /// Gets the file content from the persistence store for the given user diff --git a/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs b/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs index b340a0f061..a517fc7013 100644 --- a/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs +++ b/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs @@ -144,7 +144,7 @@ private async Task GetCompanyBpdmDetailDataByBusinessPart } } - public async Task UploadDocumentAsync(Guid applicationId, IFormFile document, DocumentTypeId documentTypeId, CancellationToken cancellationToken) + public async Task UploadDocumentAsync(Guid applicationId, IFormFile document, DocumentTypeId documentTypeId, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(document.FileName)) { @@ -167,6 +167,7 @@ public async Task UploadDocumentAsync(Guid applicationId, IFormFile documen { throw new ForbiddenException($"The users company is not assigned with application {applicationId}"); } + _portalRepositories.GetInstance().AttachAndModifyCompanyApplication(applicationId, application => { application.DateLastChanged = _dateTimeProvider.OffsetNow; @@ -178,7 +179,8 @@ public async Task UploadDocumentAsync(Guid applicationId, IFormFile documen { doc.CompanyUserId = _identityData.IdentityId; }); - return await _portalRepositories.SaveAsync().ConfigureAwait(false); + + await _portalRepositories.SaveAsync().ConfigureAwait(false); } public async Task<(string FileName, byte[] Content, string MediaType)> GetDocumentContentAsync(Guid documentId) diff --git a/src/registration/Registration.Service/Controllers/RegistrationController.cs b/src/registration/Registration.Service/Controllers/RegistrationController.cs index 6995f19581..49e31955a9 100644 --- a/src/registration/Registration.Service/Controllers/RegistrationController.cs +++ b/src/registration/Registration.Service/Controllers/RegistrationController.cs @@ -79,7 +79,7 @@ public Task GetCompanyBpdmDetailDataAsync([FromRoute] str /// CancellationToken (provided by controller) /// /// Example: Post: /api/registration/application/{applicationId}/documentType/{documentTypeId}/documents - /// Successfully uploaded the document + /// Successfully uploaded the document /// The user is not assigned with the CompanyApplication. /// Only PDF files are supported. /// Input is incorrect. @@ -90,12 +90,16 @@ public Task GetCompanyBpdmDetailDataAsync([FromRoute] str [Consumes("multipart/form-data")] [Route("application/{applicationId}/documentType/{documentTypeId}/documents")] [RequestFormLimits(ValueLengthLimit = 819200, MultipartBodyLengthLimit = 819200)] - [ProducesResponseType(typeof(int), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status415UnsupportedMediaType)] - public Task UploadDocumentAsync([FromRoute] Guid applicationId, [FromRoute] DocumentTypeId documentTypeId, [FromForm(Name = "document")] IFormFile document, CancellationToken cancellationToken) => - _registrationBusinessLogic.UploadDocumentAsync(applicationId, document, documentTypeId, cancellationToken); + public async Task UploadDocumentAsync([FromRoute] Guid applicationId, [FromRoute] DocumentTypeId documentTypeId, [FromForm(Name = "document")] IFormFile document, CancellationToken cancellationToken) + { + await _registrationBusinessLogic.UploadDocumentAsync(applicationId, document, documentTypeId, + cancellationToken).ConfigureAwait(false); + return NoContent(); + } /// /// Gets a specific document by its id diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs index 052391fbdb..743bfef254 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs @@ -72,7 +72,8 @@ public class UserBusinessLogicTests private readonly Guid _createdCentralCompanyId; private readonly string _displayName; private readonly IIdentityData _identity; - private readonly ICollection _companyUserAssignedRole = new HashSet(); + private readonly ICollection _addedRoles = new HashSet(); + private readonly ICollection _removedRoles = new HashSet(); private readonly Func _processLine; private readonly Func _companyUserSelectFunction; private readonly Exception _error; @@ -667,7 +668,7 @@ public async Task ModifyUserRoleAsync_WithTwoNewRoles_AddsTwoRolesToTheDatabase( await sut.ModifyUserRoleAsync(_validOfferId, userRoleInfo).ConfigureAwait(false); // Assert - _companyUserAssignedRole.Should().HaveCount(2); + _addedRoles.Should().HaveCount(2); } [Fact] @@ -814,7 +815,11 @@ public async Task ModifyCoreOfferUserRolesAsync_WithTwoNewRoles_AddsTwoRolesToTh await sut.ModifyCoreOfferUserRolesAsync(_validOfferId, _companyUserId, userRoles).ConfigureAwait(false); // Assert - _companyUserAssignedRole.Should().HaveCount(2); + _addedRoles.Should().HaveCount(2).And.Satisfy( + x => x.UserRoleId == new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47660"), + x => x.UserRoleId == new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47663")); + _removedRoles.Should().ContainSingle().Which.Should().Match( + x => x.UserRoleId == new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47664")); notifications.Should().ContainSingle(); notifications.Single().ReceiverUserId.Should().Be(_companyUserId); notifications.Single().NotificationTypeId.Should().Be(NotificationTypeId.ROLE_UPDATE_CORE_OFFER); @@ -851,7 +856,7 @@ public async Task ModifyAppUserRolesAsync_WithTwoNewRoles_AddsTwoRolesToTheDatab await sut.ModifyAppUserRolesAsync(_validOfferId, _companyUserId, userRoles).ConfigureAwait(false); // Assert - _companyUserAssignedRole.Should().HaveCount(2); + _addedRoles.Should().HaveCount(2); notifications.Should().ContainSingle(); notifications.Single().ReceiverUserId.Should().Be(_companyUserId); notifications.Single().NotificationTypeId.Should().Be(NotificationTypeId.ROLE_UPDATE_APP_OFFER); @@ -872,12 +877,12 @@ public async Task ModifyAppUserRoleAsync_WithMultipleClients_AddsTwoRolesToTheDa .Returns(new OfferIamUserData(true, new[] { iamClientId, iamClientId1 }, true, "The offer", "Tony", "Stark")); A.CallTo(() => _userRolesRepository.GetAssignedAndMatchingAppRoles(A._, A>._, A._)) - .Returns(new UserRoleModificationData[] + .Returns(new[] { - new("Existing Role", Guid.NewGuid(), false), - new("Buyer", buyerRoleId, true), - new("Company Admin", adminRoleId, true), - new("Supplier", supplierRoleId, false), + ("Existing Role", Guid.NewGuid(), false), + ("Buyer", buyerRoleId, true), + ("Company Admin", adminRoleId, true), + ("Supplier", supplierRoleId, false), }.ToAsyncEnumerable()); A.CallTo(() => _userRolesRepository.CreateIdentityAssignedRole(A._, A._)) @@ -886,8 +891,7 @@ public async Task ModifyAppUserRoleAsync_WithMultipleClients_AddsTwoRolesToTheDa var companyUserId = x.Arguments.Get("companyUserId"); var companyUserRoleId = x.Arguments.Get("companyUserRoleId"); - var companyUserAssignedRole = new IdentityAssignedRole(companyUserId, companyUserRoleId); - _companyUserAssignedRole.Add(companyUserAssignedRole); + _addedRoles.Add(new IdentityAssignedRole(companyUserId, companyUserRoleId)); }); A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(A.That.Matches(x => x == _iamUserId), A>>._)) @@ -911,7 +915,7 @@ public async Task ModifyAppUserRoleAsync_WithMultipleClients_AddsTwoRolesToTheDa await sut.ModifyAppUserRolesAsync(_validOfferId, _companyUserId, userRoles).ConfigureAwait(false); // Assert - _companyUserAssignedRole.Should().HaveCount(2); + _addedRoles.Should().HaveCount(2); } [Fact] @@ -931,12 +935,12 @@ public async Task ModifyAppUserRoleAsync_WithFailingAssignement_ThrowsServiceExc .Returns(new OfferIamUserData(true, new[] { iamClientId, iamClientId1 }, true, "The offer", "Tony", "Stark")); A.CallTo(() => _userRolesRepository.GetAssignedAndMatchingAppRoles(A._, A>._, A._)) - .Returns(new UserRoleModificationData[] + .Returns(new[] { - new("Existing Role", Guid.NewGuid(), false), - new("Buyer", buyerRoleId, true), - new("Company Admin", adminRoleId, true), - new("Supplier", supplierRoleId, false), + ("Existing Role", Guid.NewGuid(), false), + ("Buyer", buyerRoleId, true), + ("Company Admin", adminRoleId, true), + ("Supplier", supplierRoleId, false), }.ToAsyncEnumerable()); A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(A.That.Matches(x => x == _iamUserId), A>>._)) @@ -1592,9 +1596,11 @@ private void SetupFakesForUserDeletion() private void SetupFakesForUserRoleModification(List? notifications = null) { var iamClientId = "Cl1-CX-Registration"; + var existingRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47660"); var adminRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47661"); var buyerRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47662"); var supplierRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47663"); + var unassignableRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47664"); A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_validOfferId, _companyUserId, A.That.Matches(x => x == _adminCompanyId || x == _createdCentralCompanyId))) .Returns(new OfferIamUserData(true, new[] { iamClientId }, true, "The offer", "Tony", "Stark")); A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_offerWithoutNameId, _companyUserId, A.That.Matches(x => x == _adminCompanyId || x == _createdCentralCompanyId))) @@ -1609,34 +1615,36 @@ private void SetupFakesForUserRoleModification(List? notifications .Returns(_createdCentralIamUserId); A.CallTo(() => _userRolesRepository.GetAssignedAndMatchingAppRoles(A._, A>._, A._)) - .Returns(new UserRoleModificationData[] + .Returns(new[] { - new("Existing Role", Guid.NewGuid(), false), - new("Buyer", buyerRoleId, true), - new("Company Admin", adminRoleId, true), - new("Supplier", supplierRoleId, false), + ("Existing Role", Guid.NewGuid(), false), + ("Buyer", buyerRoleId, true), + ("Company Admin", adminRoleId, true), + ("Supplier", supplierRoleId, false), }.ToAsyncEnumerable()); A.CallTo(() => _userRolesRepository.GetAssignedAndMatchingCoreOfferRoles(A._, A>._, A._)) .Returns(new UserRoleModificationData[] { - new("Existing Role", Guid.NewGuid(), false), - new("Buyer", buyerRoleId, true), - new("Company Admin", adminRoleId, true), - new("Supplier", supplierRoleId, false), + new("Existing Role", existingRoleId, false, true), + new("Buyer", buyerRoleId, true, true), + new("Company Admin", adminRoleId, true, true), + new("Supplier", supplierRoleId, false, true), + new("Foo", unassignableRoleId, true, false) }.ToAsyncEnumerable()); A.CallTo(() => _userRepository.GetCoreOfferAssignedIamClientUserDataUntrackedAsync(A.That.Matches(x => x == _validOfferId), A.That.Matches(x => x == _companyUserId), A.That.Matches(x => x == _adminCompanyId || x == _createdCentralCompanyId))) .Returns(new CoreOfferIamUserData(true, new[] { iamClientId }, true, "Tony", "Stark")); A.CallTo(() => _userRolesRepository.CreateIdentityAssignedRole(A._, A._)) - .Invokes(x => - { - var companyUserId = x.Arguments.Get("companyUserId"); - var companyUserRoleId = x.Arguments.Get("companyUserRoleId"); + .Invokes((Guid companyUserId, Guid companyUserRoleId) => + _addedRoles.Add(new IdentityAssignedRole(companyUserId, companyUserRoleId))); - var companyUserAssignedRole = new IdentityAssignedRole(companyUserId, companyUserRoleId); - _companyUserAssignedRole.Add(companyUserAssignedRole); + A.CallTo(() => _portalRepositories.RemoveRange(A>._)) + .Invokes((IEnumerable roles) => + { + foreach (var role in roles) + _removedRoles.Add(role); }); A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(A.That.Matches(x => x == _iamUserId), A>>._)) diff --git a/tests/endtoend/InterfacePartnerHealthCheck/BpdmEndToEndTests.cs b/tests/endtoend/InterfacePartnerHealthCheck/BpdmEndToEndTests.cs index 250db62a15..b098c84f6a 100644 --- a/tests/endtoend/InterfacePartnerHealthCheck/BpdmEndToEndTests.cs +++ b/tests/endtoend/InterfacePartnerHealthCheck/BpdmEndToEndTests.cs @@ -32,10 +32,9 @@ public class BpdmEndToEndTests : EndToEndTestBase { private static readonly string BaseUrl = TestResources.BpdmUrl; - private static readonly string TokenUrl = - TestResources.BaseCentralIdpUrl + "/auth/realms/CX-Central/protocol/openid-connect/token"; + private static readonly string TokenUrl = $"{TestResources.BaseCentralIdpUrl}/auth/realms/CX-Central/protocol/openid-connect/token"; - private const string EndPoint = "/api/catena/legal-entities"; + private const string EndPoint = "/companies/test-company/api/catena/input/legal-entities?page=0&size=10"; private string? _interfaceHealthCheckTechUserToken; private static readonly Secrets Secrets = new(); diff --git a/tests/endtoend/InterfacePartnerHealthCheck/SdFactoryEndPointTests.cs b/tests/endtoend/InterfacePartnerHealthCheck/SdFactoryEndPointTests.cs index b8378efd9d..0c2100d09c 100644 --- a/tests/endtoend/InterfacePartnerHealthCheck/SdFactoryEndPointTests.cs +++ b/tests/endtoend/InterfacePartnerHealthCheck/SdFactoryEndPointTests.cs @@ -32,25 +32,22 @@ public class SdFactoryEndpointTests : EndToEndTestBase { private static readonly string BaseUrl = TestResources.SdFactoryBaseUrl; - private static readonly string TokenUrl = - TestResources.BaseCentralIdpUrl + "/auth/realms/CX-Central/protocol/openid-connect/token"; + private static readonly string TokenUrl = TestResources.BaseCentralIdpUrl + "/auth/realms/CX-Central/protocol/openid-connect/token"; private const string EndPoint = "/api/rel3/selfdescription"; - private string? InterfaceHealthCheckTechUserToken; + private readonly string? _interfaceHealthCheckTechUserToken; private static readonly Secrets Secrets = new(); public SdFactoryEndpointTests(ITestOutputHelper output) : base(output) { + _interfaceHealthCheckTechUserToken = TechTokenRetriever.GetToken(TokenUrl, Secrets.InterfaceHealthCheckTechClientId, Secrets.InterfaceHealthCheckTechClientSecret); } [Fact] public void InterfaceHealthCheck_SdDocCreation() { - InterfaceHealthCheckTechUserToken = TechTokenRetriever.GetToken(TokenUrl, - Secrets.InterfaceHealthCheckTechClientId, - Secrets.InterfaceHealthCheckTechClientSecret); - if (InterfaceHealthCheckTechUserToken.IsNullOrEmpty()) + if (_interfaceHealthCheckTechUserToken.IsNullOrEmpty()) throw new Exception("Could not fetch token for interface partner health check"); var body = DataHandleHelper.SerializeData( @@ -70,7 +67,7 @@ public void InterfaceHealthCheck_SdDocCreation() .DisableSslCertificateValidation() .Header( "authorization", - $"Bearer {InterfaceHealthCheckTechUserToken}") + $"Bearer {_interfaceHealthCheckTechUserToken}") .When() .Body(body) .Post($"{BaseUrl}{EndPoint}") diff --git a/tests/endtoend/InterfacePartnerHealthCheck/WalletEndPointTests.cs b/tests/endtoend/InterfacePartnerHealthCheck/WalletEndPointTests.cs index df680f8f33..4aa92dc1c6 100644 --- a/tests/endtoend/InterfacePartnerHealthCheck/WalletEndPointTests.cs +++ b/tests/endtoend/InterfacePartnerHealthCheck/WalletEndPointTests.cs @@ -18,6 +18,7 @@ ********************************************************************************/ using Castle.Core.Internal; +using Microsoft.Extensions.DependencyInjection; using RestAssured.Response.Logging; using Xunit; using Xunit.Abstractions; @@ -48,9 +49,7 @@ public WalletEndpointTests(ITestOutputHelper output) : base(output) public void WalletCreationInterface_CreateAndDuplicationCheck() { Bpn = $"TestAutomation_{DateTime.Now:s}"; - InterfaceHealthCheckTechUserToken = - TechTokenRetriever.GetToken(TokenUrl, Secrets.InterfaceHealthCheckTechClientId, - Secrets.InterfaceHealthCheckTechClientSecret); + InterfaceHealthCheckTechUserToken = TechTokenRetriever.GetToken(TokenUrl, Secrets.InterfaceHealthCheckTechClientId, Secrets.InterfaceHealthCheckTechClientSecret); if (InterfaceHealthCheckTechUserToken.IsNullOrEmpty()) throw new Exception("Could not fetch token for interface partner health check"); GetListOfWallets(); @@ -64,15 +63,15 @@ public void WalletCreationInterface_CreateAndDuplicationCheck() private static void GetListOfWallets() { Given() - .DisableSslCertificateValidation() - .Header( - "authorization", - $"Bearer {InterfaceHealthCheckTechUserToken}") - .When() - .Get($"{WalletBaseUrl}{WalletEndPoint}") - .Then() - .Log(ResponseLogLevel.OnError) - .StatusCode(200); + .DisableSslCertificateValidation() + .Header( + "authorization", + $"Bearer {InterfaceHealthCheckTechUserToken}") + .When() + .Get($"{WalletBaseUrl}{WalletEndPoint}") + .Then() + .Log(ResponseLogLevel.OnError) + .StatusCode(200); } //POST: /api/wallets diff --git a/tests/endtoend/NotificationInitScenario/ModifyCoreUserRoleScenario.cs b/tests/endtoend/NotificationInitScenario/ModifyCoreUserRoleScenario.cs index 6c6a6a23d4..b22b1c7dc6 100644 --- a/tests/endtoend/NotificationInitScenario/ModifyCoreUserRoleScenario.cs +++ b/tests/endtoend/NotificationInitScenario/ModifyCoreUserRoleScenario.cs @@ -77,9 +77,7 @@ public async Task Scenario_HappyPath_AssignAndUnassignCoreUserRoles() private async Task GetPortalUserToken() { - _portalUserToken = - await new AuthFlow(_portalUserCompanyName).GetAccessToken(Secrets.PortalUserName, - Secrets.PortalUserPassword); + _portalUserToken = await new AuthFlow(_portalUserCompanyName).GetAccessToken(Secrets.PortalUserName, Secrets.PortalUserPassword); } //GET: api/administration/user/owncompany/roles/coreoffers diff --git a/tests/endtoend/PortalHealthCheck/BaseDataLoadCheck.cs b/tests/endtoend/PortalHealthCheck/BaseDataLoadCheck.cs index cb12a88246..24e67f8236 100644 --- a/tests/endtoend/PortalHealthCheck/BaseDataLoadCheck.cs +++ b/tests/endtoend/PortalHealthCheck/BaseDataLoadCheck.cs @@ -27,13 +27,13 @@ namespace Org.Eclipse.TractusX.Portal.Backend.EndToEnd.Tests; [Trait("Category", "PortalHC")] -[TestCaseOrderer("Org.Eclipse.TractusX.Portal.Backend.EndToEnd.Tests.AlphabeticalOrderer", - "EndToEnd.Tests")] +[TestCaseOrderer("Org.Eclipse.TractusX.Portal.Backend.EndToEnd.Tests.AlphabeticalOrderer", "EndToEnd.Tests")] [Collection("PortalHC")] public class BaseDataLoadCheck : EndToEndTestBase { + private const string EndPoint = "/api/administration"; + private static readonly string BaseUrl = TestResources.BasePortalBackendUrl; - private static readonly string EndPoint = "/api/administration"; private static readonly Secrets Secrets = new(); private static string? PortalUserToken; private static readonly string PortalUserCompanyName = TestResources.PortalUserCompanyName; @@ -53,10 +53,10 @@ public async Task GetAccessToken() // in order to just get token once, ensure th // GET: /api/administration/staticdata/usecases [Fact] - public void GetUseCaseData() + public async Task GetUseCaseData() { if (PortalUserToken.IsNullOrEmpty()) - throw new Exception("Portal user token could not be fetched"); + await GetAccessToken(); var response = Given() .DisableSslCertificateValidation() @@ -76,10 +76,10 @@ public void GetUseCaseData() // GET: /api/administration/staticdata/languagetags [Fact] - public void GetAppLanguageTags() + public async Task GetAppLanguageTags() { if (PortalUserToken.IsNullOrEmpty()) - throw new Exception("Portal user token could not be fetched"); + await GetAccessToken(); var response = Given() .DisableSslCertificateValidation() @@ -99,10 +99,10 @@ public void GetAppLanguageTags() // GET: /api/administration/staticdata/licenseType [Fact] - public void GetAllLicenseTypes() + public async Task GetAllLicenseTypes() { if (PortalUserToken.IsNullOrEmpty()) - throw new Exception("Portal user token could not be fetched"); + await GetAccessToken(); var response = Given() .DisableSslCertificateValidation() @@ -122,10 +122,10 @@ public void GetAllLicenseTypes() // GET: api/administration/user/owncompany/users [Fact] - public void GetCompanyUserData() + public async Task GetCompanyUserData() { if (PortalUserToken.IsNullOrEmpty()) - throw new Exception("Portal user token could not be fetched"); + await GetAccessToken(); var response = Given() .DisableSslCertificateValidation() @@ -145,10 +145,10 @@ public void GetCompanyUserData() // GET: api/administration/companydata/ownCompanyDetails [Fact] - public void GetOwnCompanyDetails() + public async Task GetOwnCompanyDetails() { if (PortalUserToken.IsNullOrEmpty()) - throw new Exception("Portal user token could not be fetched"); + await GetAccessToken(); var response = Given() .DisableSslCertificateValidation() diff --git a/tests/endtoend/PortalHealthCheck/RegistrationHealthCheck.cs b/tests/endtoend/PortalHealthCheck/RegistrationHealthCheck.cs index 04fb1ac6bf..2a64b6ed3b 100644 --- a/tests/endtoend/PortalHealthCheck/RegistrationHealthCheck.cs +++ b/tests/endtoend/PortalHealthCheck/RegistrationHealthCheck.cs @@ -17,6 +17,7 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ +using Castle.Core.Internal; using FluentAssertions; using Xunit; using Xunit.Abstractions; @@ -50,8 +51,11 @@ public async Task GetAccessToken() // in order to just get token once, ensure th } [Fact] - public void GetCompanyRoles() + public async Task GetCompanyRoles() { + if (PortalUserToken.IsNullOrEmpty()) + await GetAccessToken().ConfigureAwait(false); + var response = Given() .DisableSslCertificateValidation() .Header( @@ -68,8 +72,11 @@ public void GetCompanyRoles() } [Fact] - public void GetCompanyRoleAgreementData() + public async Task GetCompanyRoleAgreementData() { + if (PortalUserToken.IsNullOrEmpty()) + await GetAccessToken().ConfigureAwait(false); + var response = Given() .DisableSslCertificateValidation() .Header( @@ -87,8 +94,11 @@ public void GetCompanyRoleAgreementData() } [Fact] - public void GetClientRolesComposite() + public async Task GetClientRolesComposite() { + if (PortalUserToken.IsNullOrEmpty()) + await GetAccessToken().ConfigureAwait(false); + var response = Given() .DisableSslCertificateValidation() .Header( @@ -105,8 +115,11 @@ public void GetClientRolesComposite() } [Fact] - public void GetApplicationsWithStatus() + public async Task GetApplicationsWithStatus() { + if (PortalUserToken.IsNullOrEmpty()) + await GetAccessToken().ConfigureAwait(false); + var response = Given() .DisableSslCertificateValidation() .Header( diff --git a/tests/endtoend/RegistrationScenarios/BpdmContent.cs b/tests/endtoend/RegistrationScenarios/BpdmContent.cs index 41452799fb..21de23087c 100644 --- a/tests/endtoend/RegistrationScenarios/BpdmContent.cs +++ b/tests/endtoend/RegistrationScenarios/BpdmContent.cs @@ -17,12 +17,15 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; using System.Text.Json.Serialization; namespace Org.Eclipse.TractusX.Portal.Backend.EndToEnd.Tests; +public record BpdmPaginationContent( + [property: JsonPropertyName("totalElements")] int Total, + [property: JsonPropertyName("content")] IEnumerable Content +); + public record BpdmContent( - [property: JsonPropertyName("score")] float Score, - [property: JsonPropertyName("legalEntity")] BpdmLegalEntityDto LegalEntity + [property: JsonPropertyName("bpnl")] string Bpn ); diff --git a/tests/endtoend/RegistrationScenarios/RegistrationEndpointHelper.cs b/tests/endtoend/RegistrationScenarios/RegistrationEndpointHelper.cs index 8b363a46e8..29a0dd6dd3 100644 --- a/tests/endtoend/RegistrationScenarios/RegistrationEndpointHelper.cs +++ b/tests/endtoend/RegistrationScenarios/RegistrationEndpointHelper.cs @@ -27,6 +27,7 @@ using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Model; using PasswordGenerator; using RestAssured.Response.Logging; +using System.Net; using static RestAssured.Dsl; namespace Org.Eclipse.TractusX.Portal.Backend.EndToEnd.Tests; @@ -46,31 +47,31 @@ public static class RegistrationEndpointHelper public static async Task GetBpn() { - _portalUserToken = - await new AuthFlow(PortalUserCompanyName).GetAccessToken(Secrets.PortalUserName, - Secrets.PortalUserPassword); + const string endpoint = "/companies/test-company/api/catena/input/legal-entities?page=0&size=10"; + _portalUserToken = await new AuthFlow(PortalUserCompanyName) + .GetAccessToken(Secrets.PortalUserName, Secrets.PortalUserPassword); - var endpoint = "/api/catena/legal-entities?page=0&size=20"; var data = Given() .DisableSslCertificateValidation() .Header( "authorization", $"Bearer {_portalUserToken}") .When() - .Get(bpdmBaseUrl + endpoint) + .Post($"{bpdmBaseUrl}{endpoint}") .Then() - .StatusCode(200) .And() - .Extract() - .Response(); - var bpdmLegalEntityDatas = - DataHandleHelper.DeserializeData>(data.Content.ReadAsStringAsync().Result); + .StatusCode(200) + .And() + .Extract() + .Response(); + + var bpdmLegalEntityDatas = DataHandleHelper.DeserializeData(data.Content.ReadAsStringAsync().Result); if (bpdmLegalEntityDatas is null) { throw new Exception($"Could not get bpn from {endpoint} should not be null."); } - return bpdmLegalEntityDatas.Content.ElementAt(new Random().Next(bpdmLegalEntityDatas.Content.Count())) - .LegalEntity.Bpn; + + return bpdmLegalEntityDatas.Content.ElementAt(new Random().Next(bpdmLegalEntityDatas.Content.Count())).Bpn; } //GET /api/registration/legalEntityAddress/{bpn} @@ -95,6 +96,7 @@ public static CompanyDetailData GetCompanyBpdmDetailData(string bpn) { throw new Exception($"Could not get bpdm detail data from {endpoint} should not be null."); } + return bpdmDetailData; } @@ -358,8 +360,7 @@ public static string SubmitCompanyRoleConsentToAgreements(List co // POST /api/registration/application/{applicationId}/documentType/{documentTypeId}/documents - public static int UploadDocument_WithEmptyTitle(string? documentTypeId, - string? documentName) + public static void UploadDocument_WithEmptyTitle(string? documentTypeId, string? documentName) { if (documentTypeId is null || documentName is null) throw new Exception("No document type id or name provided but expected"); @@ -376,16 +377,14 @@ public static int UploadDocument_WithEmptyTitle(string? documentTypeId, .Post($"{BaseUrl}{EndPoint}/application/{_applicationId}/documentType/{documentTypeId}/documents") .Then() .Log(ResponseLogLevel.OnError) - .StatusCode(200) + .StatusCode(204) .Extract() .Response(); - var result = DataHandleHelper.DeserializeData(response.Content.ReadAsStringAsync().Result); - - if (result == 1) + if (response.StatusCode == HttpStatusCode.NoContent) + { SetApplicationStatus(CompanyApplicationStatusId.VERIFY.ToString()); - - return result; + } } // POST /api/registration/application/{applicationId}/submitRegistration diff --git a/tests/endtoend/RegistrationScenarios/RegistrationScenarios.cs b/tests/endtoend/RegistrationScenarios/RegistrationScenarios.cs index 347e4d2451..113f3bda33 100644 --- a/tests/endtoend/RegistrationScenarios/RegistrationScenarios.cs +++ b/tests/endtoend/RegistrationScenarios/RegistrationScenarios.cs @@ -57,9 +57,7 @@ public async Task CompanyRegistration_WithManualDataInput(TestDataRegistrationMo int.Parse(roleSubmissionResult).Should().BeGreaterThan(0); Thread.Sleep(3000); - var docUploadResult = RegistrationEndpointHelper.UploadDocument_WithEmptyTitle(testEntry.DocumentTypeId, - testEntry.DocumentName); - docUploadResult.Should().Be(1); + RegistrationEndpointHelper.UploadDocument_WithEmptyTitle(testEntry.DocumentTypeId, testEntry.DocumentName); Thread.Sleep(3000); var status = RegistrationEndpointHelper.SubmitRegistration(); @@ -129,9 +127,7 @@ public async Task CompanyRegistration_ByBpn(TestDataRegistrationModel testEntry) int.Parse(roleSubmissionResult).Should().BeGreaterThan(0); Thread.Sleep(3000); - var docUploadResult = - RegistrationEndpointHelper.UploadDocument_WithEmptyTitle(testEntry.DocumentTypeId, testEntry.DocumentName); - docUploadResult.Should().Be(1); + RegistrationEndpointHelper.UploadDocument_WithEmptyTitle(testEntry.DocumentTypeId, testEntry.DocumentName); Thread.Sleep(3000); var status = RegistrationEndpointHelper.SubmitRegistration(); diff --git a/tests/endtoend/ServiceAccountCUDScenarios/AdministrationEndpointHelper.cs b/tests/endtoend/ServiceAccountCUDScenarios/AdministrationEndpointHelper.cs index 99e8ae8551..a9a5a9232c 100644 --- a/tests/endtoend/ServiceAccountCUDScenarios/AdministrationEndpointHelper.cs +++ b/tests/endtoend/ServiceAccountCUDScenarios/AdministrationEndpointHelper.cs @@ -40,9 +40,7 @@ public static class AdministrationEndpointHelper public static async Task GetOperatorToken() { - PortalUserToken = - await new AuthFlow(PortalUserCompanyName).GetAccessToken(Secrets.PortalUserName, - Secrets.PortalUserPassword); + PortalUserToken = await new AuthFlow(PortalUserCompanyName).GetAccessToken(Secrets.PortalUserName, Secrets.PortalUserPassword); return !PortalUserToken.IsNullOrEmpty(); } @@ -104,12 +102,10 @@ public static ServiceAccountDetails CreateNewServiceAccount(string[] permissions foreach (var p in permissions) { - userRoleIds.AddRange( - from t in allServiceAccountsRoles where t.UserRoleText.Contains(p) select t.UserRoleId); + userRoleIds.AddRange(from t in allServiceAccountsRoles where t.UserRoleText.Contains(p) select t.UserRoleId); } - var serviceAccountCreationInfo = - new ServiceAccountCreationInfo(techUserName, Description, IamClientAuthMethod.SECRET, userRoleIds); + var serviceAccountCreationInfo = new ServiceAccountCreationInfo(techUserName, Description, IamClientAuthMethod.SECRET, userRoleIds); var endpoint = $"{EndPoint}/serviceaccount/owncompany/serviceaccounts"; var response = Given() .DisableSslCertificateValidation() diff --git a/tests/endtoend/ServiceAccountCUDScenarios/ServiceAccountCUDScenarios.cs b/tests/endtoend/ServiceAccountCUDScenarios/ServiceAccountCUDScenarios.cs index 4767123485..5a44c659d0 100644 --- a/tests/endtoend/ServiceAccountCUDScenarios/ServiceAccountCUDScenarios.cs +++ b/tests/endtoend/ServiceAccountCUDScenarios/ServiceAccountCUDScenarios.cs @@ -32,8 +32,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.EndToEnd.Tests; [Collection("Portal")] public class ServiceAccountCUDScenarios : EndToEndTestBase { - private static readonly string TokenUrl = - TestResources.BaseCentralIdpUrl + "/auth/realms/CX-Central/protocol/openid-connect/token"; + private static readonly string TokenUrl = TestResources.BaseCentralIdpUrl + "/auth/realms/CX-Central/protocol/openid-connect/token"; public ServiceAccountCUDScenarios(ITestOutputHelper output) : base(output) { @@ -42,9 +41,10 @@ public ServiceAccountCUDScenarios(ITestOutputHelper output) : base(output) //Scenario - Create a new service account [Theory(DisplayName = "Service Account Creation")] [MemberData(nameof(GetDataEntries))] - public void ServiceAccount_Creation(string[] permissions) + public async Task ServiceAccount_Creation(string[] permissions) { List? existingServiceAccounts = null; + await AdministrationEndpointHelper.GetOperatorToken().ConfigureAwait(false); // get a snapshot of current existing service accounts try @@ -58,8 +58,7 @@ public void ServiceAccount_Creation(string[] permissions) finally { //create a new service account - var newServiceAccount = - AdministrationEndpointHelper.CreateNewServiceAccount(permissions); + var newServiceAccount = AdministrationEndpointHelper.CreateNewServiceAccount(permissions); try { @@ -68,9 +67,8 @@ public void ServiceAccount_Creation(string[] permissions) if (!existingServiceAccounts.IsNullOrEmpty()) { - var checkAccountIsNew = - existingServiceAccounts!.Where(t => - t.ServiceAccountId == newServiceAccount.ServiceAccountId); + var checkAccountIsNew = existingServiceAccounts! + .Where(t => t.ServiceAccountId == newServiceAccount.ServiceAccountId); checkAccountIsNew.Should().BeEmpty(); } @@ -100,11 +98,12 @@ public void ServiceAccount_Creation(string[] permissions) //Scenario - Create a new service account and update the same [Theory(DisplayName = "Service Account Data Update")] [MemberData(nameof(GetDataEntries))] - public void ServiceAccount_DataUpdate(string[] permissions) + public async Task ServiceAccount_DataUpdate(string[] permissions) { + await AdministrationEndpointHelper.GetOperatorToken().ConfigureAwait(false); + //create a new service account - var newServiceAccount = - AdministrationEndpointHelper.CreateNewServiceAccount(permissions); + var newServiceAccount = AdministrationEndpointHelper.CreateNewServiceAccount(permissions); //update the previous created service account details by changing "name" and "description" var now = DateTime.Now; @@ -114,8 +113,7 @@ public void ServiceAccount_DataUpdate(string[] permissions) newTechUserName, newDescription); //check if the change of the serviceAccount got successfully saved - var updatedServiceAccount = - AdministrationEndpointHelper.GetServiceAccountDetailsById(newServiceAccount.ServiceAccountId.ToString()); + var updatedServiceAccount = AdministrationEndpointHelper.GetServiceAccountDetailsById(newServiceAccount.ServiceAccountId.ToString()); updatedServiceAccount.Name.Should().Be(newTechUserName, "Updated technical user name was not stored correctly."); updatedServiceAccount.Description.Should().Be(newDescription, "Updated description of service account was not stored correctly"); @@ -125,8 +123,10 @@ public void ServiceAccount_DataUpdate(string[] permissions) //Scenario - Create a new service account and update the credentials [Theory(DisplayName = "Service Account credential refresh")] [MemberData(nameof(GetDataEntries))] - public void ServiceAccount_CredentialRefresh(string[] permissions) + public async Task ServiceAccount_CredentialRefresh(string[] permissions) { + await AdministrationEndpointHelper.GetOperatorToken().ConfigureAwait(false); + // create a new service account var newServiceAccount = AdministrationEndpointHelper.CreateNewServiceAccount(permissions); @@ -150,8 +150,10 @@ public void ServiceAccount_CredentialRefresh(string[] permissions) //Scenario - Create and delete a new service account [Theory(DisplayName = "Service Account Deletion")] [MemberData(nameof(GetDataEntries))] - public void ServiceAccount_Deletion(string[] permissions) + public async Task ServiceAccount_Deletion(string[] permissions) { + await AdministrationEndpointHelper.GetOperatorToken().ConfigureAwait(false); + // create a new service account var newServiceAccount = AdministrationEndpointHelper.CreateNewServiceAccount(permissions);