From 999b43135946201081aa676327597cf6e50a209c Mon Sep 17 00:00:00 2001 From: Martin Othamar Date: Mon, 24 Feb 2025 10:06:36 +0100 Subject: [PATCH] Remove roles from IAuthenticationContext, API and IAuthorizationClient (#1113) --- .../Controllers/AuthorizationController.cs | 65 --------- .../Features/Auth/Authenticated.cs | 17 +-- .../Features/Auth/AuthenticationContext.cs | 6 +- .../Telemetry.Authorization.Client.cs | 9 -- .../Authorization/AuthorizationClient.cs | 50 ------- .../Internal/Auth/IAuthorizationClient.cs | 9 -- .../Mocks/AuthorizationMock.cs | 13 -- ...angeDetection.SaveJsonSwagger.verified.txt | 117 --------------- .../Altinn.App.Api.Tests/OpenApi/swagger.json | 117 --------------- .../Utils/TestAuthentication.cs | 7 - .../Features/Auth/AuthenticatedTests.cs | 7 +- .../Authorization/AuthorizationClientTests.cs | 135 ------------------ 12 files changed, 6 insertions(+), 546 deletions(-) diff --git a/src/Altinn.App.Api/Controllers/AuthorizationController.cs b/src/Altinn.App.Api/Controllers/AuthorizationController.cs index b26db73f0..88de545cf 100644 --- a/src/Altinn.App.Api/Controllers/AuthorizationController.cs +++ b/src/Altinn.App.Api/Controllers/AuthorizationController.cs @@ -2,7 +2,6 @@ using Altinn.App.Core.Configuration; using Altinn.App.Core.Features.Auth; using Altinn.App.Core.Internal.Auth; -using Authorization.Platform.Authorization.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; @@ -152,68 +151,4 @@ public async Task ValidateSelectedParty(int userId, int partyId) return StatusCode(500, $"Something went wrong when trying to validate party {partyId} for user {userId}"); } } - - /// - /// Fetches roles for current party. - /// - /// List of roles for the current user and party. - // [Authorize] - // [HttpGet("{org}/{app}/api/authorization/roles")] - // [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] - public async Task GetRolesForCurrentParty() - { - var context = _authenticationContext.Current; - switch (context) - { - case Authenticated.None: - return Unauthorized(); - case Authenticated.User user: - { - var details = await user.LoadDetails(validateSelectedParty: true); - if (details.CanRepresent is not bool canRepresent) - throw new Exception("Couldn't validate selected party"); - if (!canRepresent) - { - // automatically switch to the user's own party - var reportee = details.Profile.Party; - if (user.SelectedPartyId != reportee.PartyId) - { - // Setting cookie to partyID of logged in user if it varies from previus value. - Response.Cookies.Append( - _settings.GetAltinnPartyCookieName, - reportee.PartyId.ToString(CultureInfo.InvariantCulture), - new CookieOptions { Domain = _settings.HostName } - ); - } - return Unauthorized(); - } - - return Ok(details.Roles); - } - case Authenticated.SelfIdentifiedUser: - { - return Ok(Array.Empty()); - } - case Authenticated.Org: - { - return Ok(Array.Empty()); - } - case Authenticated.ServiceOwner: - { - return Ok(Array.Empty()); - } - case Authenticated.SystemUser: - { - // NOTE: system users can't have Altinn 2 roles, but they will get support for tilgangspakker, as of 26.01.2025 - return Ok(Array.Empty()); - } - default: - throw new Exception($"Unknown authentication context: {context.GetType().Name}"); - } - } } diff --git a/src/Altinn.App.Core/Features/Auth/Authenticated.cs b/src/Altinn.App.Core/Features/Auth/Authenticated.cs index 3158de1c9..c540c2ad2 100644 --- a/src/Altinn.App.Core/Features/Auth/Authenticated.cs +++ b/src/Altinn.App.Core/Features/Auth/Authenticated.cs @@ -12,7 +12,6 @@ using Altinn.Platform.Profile.Models; using Altinn.Platform.Register.Models; using AltinnCore.Authentication.Constants; -using Authorization.Platform.Authorization.Models; namespace Altinn.App.Core.Features.Auth; @@ -125,7 +124,6 @@ public sealed class User : Authenticated private readonly Func> _lookupParty; private readonly Func?>> _getPartyList; private readonly Func> _validateSelectedParty; - private readonly Func>> _getUserRoles; private readonly ApplicationMetadata _appMetadata; internal User( @@ -143,7 +141,6 @@ internal User( Func> lookupParty, Func?>> getPartyList, Func> validateSelectedParty, - Func>> getUserRoles, ApplicationMetadata appMetadata ) : base(tokenIssuer, tokenIsExchanged, scopes, token) @@ -158,7 +155,6 @@ ApplicationMetadata appMetadata _lookupParty = lookupParty; _getPartyList = getPartyList; _validateSelectedParty = validateSelectedParty; - _getUserRoles = getUserRoles; _appMetadata = appMetadata; } @@ -174,7 +170,6 @@ ApplicationMetadata appMetadata /// True if the user represents itself (user party will equal selected party) /// List of parties the user can represent /// List of parties the user can instantiate as - /// List of roles the user has /// True if the user can represent the selected party. Only set if details were loaded with validateSelectedParty set to true public sealed record Details( Party UserParty, @@ -183,7 +178,6 @@ public sealed record Details( bool RepresentsSelf, IReadOnlyList Parties, IReadOnlyList PartiesAllowedToInstantiate, - IReadOnlyList Roles, bool? CanRepresent = null ) { @@ -305,8 +299,6 @@ await _getUserProfile(UserId) canRepresent = await _validateSelectedParty(UserId, SelectedPartyId); } - var roles = await _getUserRoles(UserId, SelectedPartyId); - var partiesAllowedToInstantiate = InstantiationHelper.FilterPartiesByAllowedPartyTypes( parties, _appMetadata.PartyTypesAllowed @@ -319,7 +311,6 @@ await _getUserProfile(UserId) representsSelf, parties, partiesAllowedToInstantiate, - roles.ToArray(), canRepresent ); return _extra; @@ -706,8 +697,7 @@ internal static Authenticated FromLocalTest( Func> lookupUserParty, Func> lookupOrgParty, Func?>> getPartyList, - Func> validateSelectedParty, - Func>> getUserRoles + Func> validateSelectedParty ) { if (string.IsNullOrWhiteSpace(tokenStr)) @@ -828,7 +818,6 @@ Func>> getUserRoles lookupUserParty, getPartyList, validateSelectedParty, - getUserRoles, appMetadata ); } @@ -842,8 +831,7 @@ internal static Authenticated From( Func> lookupUserParty, Func> lookupOrgParty, Func?>> getPartyList, - Func> validateSelectedParty, - Func>> getUserRoles + Func> validateSelectedParty ) { if (string.IsNullOrWhiteSpace(tokenStr)) @@ -1056,7 +1044,6 @@ Func>> getUserRoles lookupUserParty, getPartyList, validateSelectedParty, - getUserRoles, appMetadata ); } diff --git a/src/Altinn.App.Core/Features/Auth/AuthenticationContext.cs b/src/Altinn.App.Core/Features/Auth/AuthenticationContext.cs index a7811e2fa..5e9125648 100644 --- a/src/Altinn.App.Core/Features/Auth/AuthenticationContext.cs +++ b/src/Altinn.App.Core/Features/Auth/AuthenticationContext.cs @@ -75,8 +75,7 @@ public Authenticated Current _altinnPartyClient.GetParty, (string orgNr) => _altinnPartyClient.LookupParty(new PartyLookup { OrgNo = orgNr }), _authorizationClient.GetPartyList, - _authorizationClient.ValidateSelectedParty, - _authorizationClient.GetUserRoles + _authorizationClient.ValidateSelectedParty ); } else @@ -91,8 +90,7 @@ public Authenticated Current _altinnPartyClient.GetParty, (string orgNr) => _altinnPartyClient.LookupParty(new PartyLookup { OrgNo = orgNr }), _authorizationClient.GetPartyList, - _authorizationClient.ValidateSelectedParty, - _authorizationClient.GetUserRoles + _authorizationClient.ValidateSelectedParty ); } diff --git a/src/Altinn.App.Core/Features/Telemetry/Telemetry.Authorization.Client.cs b/src/Altinn.App.Core/Features/Telemetry/Telemetry.Authorization.Client.cs index 7edbc6033..0abd5c909 100644 --- a/src/Altinn.App.Core/Features/Telemetry/Telemetry.Authorization.Client.cs +++ b/src/Altinn.App.Core/Features/Telemetry/Telemetry.Authorization.Client.cs @@ -15,15 +15,6 @@ partial class Telemetry return activity; } - internal Activity? StartClientGetPartyRoleListActivity(int userId, int partyId) - { - var activity = ActivitySource.StartActivity($"{Prefix}.GetUserRoles"); - activity?.SetUserPartyId(partyId); - activity?.SetUserId(userId); - - return activity; - } - internal Activity? StartClientValidateSelectedPartyActivity(int userId, int partyId) { var activity = ActivitySource.StartActivity($"{Prefix}.ValidateSelectedParty"); diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Authorization/AuthorizationClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Authorization/AuthorizationClient.cs index d5077e0f2..f86ad9976 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Authorization/AuthorizationClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Authorization/AuthorizationClient.cs @@ -1,4 +1,3 @@ -using System.Net; using System.Net.Http.Headers; using System.Security.Claims; using Altinn.App.Core.Configuration; @@ -14,7 +13,6 @@ using Altinn.Platform.Register.Models; using Altinn.Platform.Storage.Interface.Models; using AltinnCore.Authentication.Utils; -using Authorization.Platform.Authorization.Models; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -181,52 +179,4 @@ List actions } return MultiDecisionHelper.ValidatePdpMultiDecision(actionsResult, response.Response, user); } - - /// - /// Retrieves roles for a user on a specified party. - /// - /// The user id. - /// The user party id. - /// A list of roles for the user on the specified party. - public async Task> GetUserRoles(int userId, int userPartyId) - { - using var activity = _telemetry?.StartClientGetPartyRoleListActivity(userId, userPartyId); - - List roles = new(); - string apiUrl = $"roles?coveredByUserId={userId}&offeredByPartyId={userPartyId}"; - string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName); - - try - { - HttpResponseMessage response = await _client.GetAsync(token, apiUrl); - if (response.StatusCode == HttpStatusCode.NotFound) - return roles; - - if (response.IsSuccessStatusCode) - { - string responseContent = await response.Content.ReadAsStringAsync(); - var deserialized = JsonConvert.DeserializeObject>(responseContent); - if (deserialized is not null) - { - roles = deserialized; - } - } - else - { - throw new Exception("Unexpected response from auth API:" + response.StatusCode); - } - } - catch (Exception ex) - { - _logger.LogError( - ex, - "An error occurred while retrieving roles for userId {UserId} and partyId {PartyId}", - userId, - userPartyId - ); - throw; - } - - return roles; - } } diff --git a/src/Altinn.App.Core/Internal/Auth/IAuthorizationClient.cs b/src/Altinn.App.Core/Internal/Auth/IAuthorizationClient.cs index ed4b630ba..7cefe1a91 100644 --- a/src/Altinn.App.Core/Internal/Auth/IAuthorizationClient.cs +++ b/src/Altinn.App.Core/Internal/Auth/IAuthorizationClient.cs @@ -2,7 +2,6 @@ using Altinn.App.Core.Models; using Altinn.Platform.Register.Models; using Altinn.Platform.Storage.Interface.Models; -using Authorization.Platform.Authorization.Models; namespace Altinn.App.Core.Internal.Auth; @@ -51,12 +50,4 @@ Task AuthorizeAction( /// /// Task> AuthorizeActions(Instance instance, ClaimsPrincipal user, List actions); - - /// - /// Retrieves roles for a user on a specified party. - /// - /// The user id. - /// The user party id. - /// A list of roles for the user on the specified party. - Task> GetUserRoles(int userId, int userPartyId); } diff --git a/test/Altinn.App.Api.Tests/Mocks/AuthorizationMock.cs b/test/Altinn.App.Api.Tests/Mocks/AuthorizationMock.cs index 83237ad35..f054ef0b9 100644 --- a/test/Altinn.App.Api.Tests/Mocks/AuthorizationMock.cs +++ b/test/Altinn.App.Api.Tests/Mocks/AuthorizationMock.cs @@ -3,7 +3,6 @@ using Altinn.App.Core.Models; using Altinn.Platform.Register.Models; using Altinn.Platform.Storage.Interface.Models; -using Authorization.Platform.Authorization.Models; namespace Altinn.App.Api.Tests.Mocks; @@ -70,16 +69,4 @@ List actions return authorizedActions; } - - public async Task> GetUserRoles(int userId, int userPartyId) - { - await Task.CompletedTask; - List roles = new List - { - new Role { Type = "altinn", Value = "bobet" }, - new Role { Type = "altinn", Value = "bobes" }, - }; - - return roles; - } } diff --git a/test/Altinn.App.Api.Tests/OpenApi/OpenApiSpecChangeDetection.SaveJsonSwagger.verified.txt b/test/Altinn.App.Api.Tests/OpenApi/OpenApiSpecChangeDetection.SaveJsonSwagger.verified.txt index 8a4a0e2ec..611b3062f 100644 --- a/test/Altinn.App.Api.Tests/OpenApi/OpenApiSpecChangeDetection.SaveJsonSwagger.verified.txt +++ b/test/Altinn.App.Api.Tests/OpenApi/OpenApiSpecChangeDetection.SaveJsonSwagger.verified.txt @@ -538,109 +538,6 @@ If org and app does not match, this returns a 409 Conflict response, } } }, - /{org}/{app}/api/authorization/roles: { - get: { - tags: [ - Authorization - ], - summary: Fetches roles for current party., - parameters: [ - { - name: org, - in: path, - required: true, - schema: { - type: string - } - }, - { - name: app, - in: path, - required: true, - schema: { - type: string - } - } - ], - responses: { - 200: { - description: OK, - content: { - text/plain: { - schema: { - type: array, - items: { - $ref: #/components/schemas/Role - } - } - }, - application/json: { - schema: { - type: array, - items: { - $ref: #/components/schemas/Role - } - } - }, - text/json: { - schema: { - type: array, - items: { - $ref: #/components/schemas/Role - } - } - }, - application/xml: { - schema: { - type: array, - items: { - $ref: #/components/schemas/Role - } - } - }, - text/xml: { - schema: { - type: array, - items: { - $ref: #/components/schemas/Role - } - } - } - } - }, - 400: { - description: Bad Request, - content: { - text/plain: { - schema: { - $ref: #/components/schemas/ProblemDetails - } - }, - application/json: { - schema: { - $ref: #/components/schemas/ProblemDetails - } - }, - text/json: { - schema: { - $ref: #/components/schemas/ProblemDetails - } - }, - application/xml: { - schema: { - $ref: #/components/schemas/ProblemDetails - } - }, - text/xml: { - schema: { - $ref: #/components/schemas/ProblemDetails - } - } - } - } - } - } - }, /{org}/{app}/instances/{instanceOwnerPartyId}/{instanceGuid}/data: { post: { tags: [ @@ -7832,20 +7729,6 @@ version that supports multiple data models in the same request. }, additionalProperties: false }, - Role: { - type: object, - properties: { - type: { - type: string, - nullable: true - }, - value: { - type: string, - nullable: true - } - }, - additionalProperties: false - }, ShadowFields: { type: object, properties: { diff --git a/test/Altinn.App.Api.Tests/OpenApi/swagger.json b/test/Altinn.App.Api.Tests/OpenApi/swagger.json index ef2a0fb6b..116972a07 100644 --- a/test/Altinn.App.Api.Tests/OpenApi/swagger.json +++ b/test/Altinn.App.Api.Tests/OpenApi/swagger.json @@ -529,109 +529,6 @@ } } }, - "/{org}/{app}/api/authorization/roles": { - "get": { - "tags": [ - "Authorization" - ], - "summary": "Fetches roles for current party.", - "parameters": [ - { - "name": "org", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "app", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Role" - } - } - }, - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Role" - } - } - }, - "text/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Role" - } - } - }, - "application/xml": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Role" - } - } - }, - "text/xml": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Role" - } - } - } - } - }, - "400": { - "description": "Bad Request", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/xml": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/xml": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - } - } - } - }, "/{org}/{app}/instances/{instanceOwnerPartyId}/{instanceGuid}/data": { "post": { "tags": [ @@ -7829,20 +7726,6 @@ }, "additionalProperties": false }, - "Role": { - "type": "object", - "properties": { - "type": { - "type": "string", - "nullable": true - }, - "value": { - "type": "string", - "nullable": true - } - }, - "additionalProperties": false - }, "ShadowFields": { "type": "object", "properties": { diff --git a/test/Altinn.App.Api.Tests/Utils/TestAuthentication.cs b/test/Altinn.App.Api.Tests/Utils/TestAuthentication.cs index ea4310474..f7bd997db 100644 --- a/test/Altinn.App.Api.Tests/Utils/TestAuthentication.cs +++ b/test/Altinn.App.Api.Tests/Utils/TestAuthentication.cs @@ -10,7 +10,6 @@ using Altinn.Platform.Register.Models; using Altinn.Platform.Storage.Interface.Models; using AltinnCore.Authentication.Constants; -using Authorization.Platform.Authorization.Models; using static Altinn.App.Core.Features.Auth.Authenticated; namespace Altinn.App.Api.Tests.Utils; @@ -190,12 +189,6 @@ public static User GetUserAuthentication( Assert.Equal(userPartyId, pid); return Task.FromResult(true); }, - getUserRoles: (uid, pid) => - { - Assert.Equal(userId, uid); - Assert.Equal(userPartyId, pid); - return Task.FromResult>([]); - }, appMetadata: NewApplicationMetadata() ); } diff --git a/test/Altinn.App.Core.Tests/Features/Auth/AuthenticatedTests.cs b/test/Altinn.App.Core.Tests/Features/Auth/AuthenticatedTests.cs index 7b62fb5a8..62a617712 100644 --- a/test/Altinn.App.Core.Tests/Features/Auth/AuthenticatedTests.cs +++ b/test/Altinn.App.Core.Tests/Features/Auth/AuthenticatedTests.cs @@ -8,7 +8,6 @@ namespace Altinn.App.Core.Tests.Features.Auth; using Altinn.Platform.Register.Enums; using Altinn.Platform.Register.Models; using AltinnCore.Authentication.Constants; -using global::Authorization.Platform.Authorization.Models; public class AuthenticatedTests { @@ -145,8 +144,7 @@ int ReadClaimInt(string claimType) lookupUserParty: _ => Task.FromResult(party), lookupOrgParty: _ => null!, getPartyList: _ => Task.FromResult?>([party]), - validateSelectedParty: (_, _) => Task.FromResult(true), - getUserRoles: (_, _) => Task.FromResult>([]) + validateSelectedParty: (_, _) => Task.FromResult(true) ); break; default: @@ -159,8 +157,7 @@ int ReadClaimInt(string claimType) lookupUserParty: _ => null!, lookupOrgParty: _ => null!, getPartyList: _ => null!, - validateSelectedParty: (_, _) => null!, - getUserRoles: (_, _) => null! + validateSelectedParty: (_, _) => null! ); break; } diff --git a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Authorization/AuthorizationClientTests.cs b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Authorization/AuthorizationClientTests.cs index 42d82d5f6..754113acb 100644 --- a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Authorization/AuthorizationClientTests.cs +++ b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Authorization/AuthorizationClientTests.cs @@ -4,21 +4,14 @@ using Altinn.App.Core.Configuration; using Altinn.App.Core.Constants; using Altinn.App.Core.Infrastructure.Clients.Authorization; -using Altinn.App.Core.Internal.Auth; using Altinn.Authorization.ABAC.Xacml.JsonProfile; using Altinn.Common.PEP.Interfaces; using Altinn.Platform.Storage.Interface.Models; -using Authorization.Platform.Authorization.Models; using FluentAssertions; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; -using WireMock.RequestBuilders; -using WireMock.ResponseBuilders; -using WireMock.Server; namespace Altinn.App.Core.Tests.Infrastructure.Clients.Authorization; @@ -115,134 +108,6 @@ public async Task AuthorizeActions_returns_empty_dictionary_if_no_response_from_ actual.Should().BeEquivalentTo(expected); } - [Fact] - public async Task GetUserRoles_Handles_200() - { - await using var fixture = Fixture.Create(); - - Role[] expectedRoles = - [ - new Role { Type = "altinn", Value = "bobet" }, - new Role { Type = "altinn", Value = "bobes" }, - ]; - - var server = fixture.Server; - server - .Given(Request.Create().WithPath(Fixture.ApiPath).UsingGet()) - .RespondWith( - Response - .Create() - .WithStatusCode(200) - .WithHeader("Content-Type", "application/json") - .WithBodyAsJson(expectedRoles) - ); - - var actualRoles = await fixture.Client.GetUserRoles(1337, 2001); - - Assert.Equivalent(expectedRoles, actualRoles); - } - - [Fact] - public async Task GetUserRoles_Handles_404() - { - await using var fixture = Fixture.Create(); - - Role[] expectedRoles = []; - - var server = fixture.Server; - server - .Given(Request.Create().WithPath(Fixture.ApiPath).UsingGet()) - .RespondWith(Response.Create().WithStatusCode(404)); - - var actualRoles = await fixture.Client.GetUserRoles(1337, 2001); - - Assert.Equivalent(expectedRoles, actualRoles); - } - - [Fact] - public async Task GetUserRoles_Throws_On_500() - { - await using var fixture = Fixture.Create(); - var server = fixture.Server; - server - .Given(Request.Create().WithPath(Fixture.ApiPath).UsingGet()) - .RespondWith(Response.Create().WithStatusCode(500)); - - await Assert.ThrowsAnyAsync(() => fixture.Client.GetUserRoles(1337, 2001)); - } - - private sealed record Fixture(WebApplication App) : IAsyncDisposable - { - internal const string ApiPath = "/authorization/api/v1/roles"; - - public Mock HttpClientFactoryMock => - Mock.Get(App.Services.GetRequiredService()); - - public WireMockServer Server => App.Services.GetRequiredService(); - - public AuthorizationClient Client => - App.Services.GetServices().OfType().Single(); - - private sealed class ReqHandler(Action? onRequest = null) : DelegatingHandler - { - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken - ) - { - onRequest?.Invoke(); - return base.SendAsync(request, cancellationToken); - } - } - - public static Fixture Create( - Action? registerCustomAppServices = default, - Action? onRequest = null - ) - { - var server = WireMockServer.Start(); - - var mockHttpClientFactory = new Mock(); - mockHttpClientFactory - .Setup(f => f.CreateClient(It.IsAny())) - .Returns(() => server.CreateClient(new ReqHandler(onRequest))); - - var app = Api.Tests.TestUtils.AppBuilder.Build( - configData: new Dictionary() - { - // API endpoint is configured this way since we have our `PlatformSettings` - // while PEP has it's own `PlatformSettings` class. - // So if we went the `services.Configure` route we would have to do it twice, - // once for ours and once for PEP's. - { "PlatformSettings:ApiAuthorizationEndpoint", server.Url + ApiPath }, - { "PlatformSettings:SubscriptionKey", "dummyKey" }, - { "AppSettings:RuntimeCookieName", "AltinnStudioRuntime" }, - }, - registerCustomAppServices: services => - { - services.AddSingleton(_ => server); - - registerCustomAppServices?.Invoke(services); - }, - overrideAltinnAppServices: services => - { - var httpContext = new DefaultHttpContext(); - httpContext.Request.Headers["Cookie"] = "AltinnStudioRuntime=myFakeJwtToken"; - - var httpContextAccessorMock = new Mock(); - httpContextAccessorMock.Setup(_ => _.HttpContext).Returns(httpContext); - - services.AddSingleton(httpContextAccessorMock.Object); - services.AddSingleton(mockHttpClientFactory.Object); - } - ); - - return new Fixture(app); - } - - public async ValueTask DisposeAsync() => await App.DisposeAsync(); - } - private static ClaimsPrincipal GetClaims(string partyId) { return new ClaimsPrincipal(