Skip to content

Commit

Permalink
Fix missing "Publisert av" developer name in deploy page (#13360)
Browse files Browse the repository at this point in the history
* get CreatedBy from AuthenticationHelper instead of Claims and add more assertions

* Remove claims from DeploymentServiceTest.cs

* Remove claims from GiteaAPIWrapperTest.cs

* Remove claims from PreviewHubTests.cs

* Remove claims from SourceControlILoggingDecoratorTests.cs

* Remove claims from ReleaseServiceTests.cs

* Remove AltinnCoreClaimTypes.Developer from SourceControlSITest.cs

* Remove PrincipalUtil.cs since code is not in use

* Remove AltinnCoreClaimTypes.Developer from RepositorySITests.cs

* Revert back GetHttpContextForTestUser in SourceControlSITest.cs to conform to similar code elsewhere

* Revert back GetHttpContextForTestUser in PreviewHubTest.cs to conform to similar code elsewhere

* get CreatedBy from AuthenticationHelper instead of Claims and add more assertions

* Remove claims from DeploymentServiceTest.cs

* Remove claims from GiteaAPIWrapperTest.cs

* Remove claims from PreviewHubTests.cs

* Remove claims from SourceControlILoggingDecoratorTests.cs

* Remove claims from ReleaseServiceTests.cs

* Remove AltinnCoreClaimTypes.Developer from SourceControlSITest.cs

* Remove PrincipalUtil.cs since code is not in use

* Remove AltinnCoreClaimTypes.Developer from RepositorySITests.cs

* Revert back GetHttpContextForTestUser in SourceControlSITest.cs to conform to similar code elsewhere

* Revert back GetHttpContextForTestUser in PreviewHubTest.cs to conform to similar code elsewhere

* Make variable names more clear
  • Loading branch information
ErlingHauan authored Aug 22, 2024
1 parent 13e41e5 commit f0afd1a
Show file tree
Hide file tree
Showing 9 changed files with 40 additions and 151 deletions.
8 changes: 2 additions & 6 deletions backend/src/Designer/Repository/Models/EntityExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using AltinnCore.Authentication.Constants;
using Altinn.Studio.Designer.Helpers;
using Microsoft.AspNetCore.Http;

namespace Altinn.Studio.Designer.Repository.Models
Expand All @@ -22,11 +19,10 @@ public static class EntityExtensions
/// <returns></returns>
public static BaseEntity PopulateBaseProperties(this BaseEntity entity, string org, string app, HttpContext httpContext)
{
List<Claim> claims = httpContext.User.Claims.ToList();
entity.Org = org;
entity.App = app;
entity.Created = DateTime.UtcNow;
entity.CreatedBy = claims.FirstOrDefault(x => x.Type == AltinnCoreClaimTypes.Developer)?.Value;
entity.CreatedBy = AuthenticationHelper.GetDeveloperUserName(httpContext);

return entity;
}
Expand Down
10 changes: 3 additions & 7 deletions backend/tests/Designer.Tests/Hubs/PreviewHubTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Altinn.Studio.Designer.Hubs;
using AltinnCore.Authentication.Constants;
Expand Down Expand Up @@ -62,19 +63,14 @@ public async Task SignalR_ClientWithDifferentDeveloperName_ShouldNotReceiveMessa

private static HttpContext GetHttpContextForTestUser(string userName)
{
List<Claim> claims = new()
{
new Claim(AltinnCoreClaimTypes.Developer, userName, ClaimValueTypes.String, "altinn.no"),
new Claim(ClaimTypes.Name, "testUser")
};
List<Claim> claims = new();
claims.Add(new Claim(ClaimTypes.Name, userName));
ClaimsIdentity identity = new("TestUserLogin");
identity.AddClaims(claims);

ClaimsPrincipal principal = new(identity);
HttpContext c = new DefaultHttpContext();
c.Request.HttpContext.User = principal;
c.Request.RouteValues.Add("org", "ttd");
c.Request.RouteValues.Add("app", "apps-test-tba");

return c;
}
Expand Down
33 changes: 10 additions & 23 deletions backend/tests/Designer.Tests/Services/DeploymentServiceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Altinn.Studio.Designer.Events;
Expand All @@ -17,14 +16,13 @@
using Altinn.Studio.Designer.TypedHttpClients.AzureDevOps.Models;
using Altinn.Studio.Designer.ViewModels.Request;
using Altinn.Studio.Designer.ViewModels.Response;
using AltinnCore.Authentication.Constants;
using MediatR;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Moq;
using Newtonsoft.Json;
using Xunit;
using Xunit.Abstractions;

namespace Designer.Tests.Services
{
Expand All @@ -39,10 +37,10 @@ public class DeploymentServiceTest
private readonly Mock<IAzureDevOpsBuildClient> _azureDevOpsBuildClient;
private readonly Mock<IPublisher> _mediatrMock;

public DeploymentServiceTest()
public DeploymentServiceTest(ITestOutputHelper testOutputHelper)
{
_httpContextAccessor = new Mock<IHttpContextAccessor>();
_httpContextAccessor.Setup(req => req.HttpContext).Returns(GetHttpContextForTestUser("testuser"));
_httpContextAccessor.Setup(req => req.HttpContext).Returns(new DefaultHttpContext());
_deploymentLogger = new Mock<ILogger<DeploymentService>>();
_deploymentRepository = new Mock<IDeploymentRepository>();
_releaseRepository = new Mock<IReleaseRepository>();
Expand Down Expand Up @@ -103,6 +101,13 @@ public async Task CreateAsync_OK(string org, string app, bool newApp)

// Assert
Assert.NotNull(deploymentEntity);

var properties = deploymentEntity.GetType().GetProperties();
foreach (var property in properties)
{
Assert.NotNull(property.GetValue(deploymentEntity));
}

_releaseRepository.Verify(
r => r.GetSucceededReleaseFromDb(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()),
Times.Once);
Expand Down Expand Up @@ -189,24 +194,6 @@ public async Task UpdateAsync()
_deploymentRepository.Verify(r => r.Update(It.IsAny<DeploymentEntity>()), Times.Once);
}

private static HttpContext GetHttpContextForTestUser(string userName)
{
List<Claim> claims = new()
{
new Claim(AltinnCoreClaimTypes.Developer, userName, ClaimValueTypes.String, "altinn.no")
};
ClaimsIdentity identity = new("TestUserLogin");
identity.AddClaims(claims);

ClaimsPrincipal principal = new(identity);
HttpContext c = new DefaultHttpContext();
c.Request.HttpContext.User = principal;
c.Request.RouteValues.Add("org", "ttd");
c.Request.RouteValues.Add("app", "apps-test-tba");

return c;
}

private static List<ReleaseEntity> GetReleases(string filename)
{
string unitTestFolder =
Expand Down
44 changes: 14 additions & 30 deletions backend/tests/Designer.Tests/Services/GiteaAPIWrapperTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,13 @@
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Altinn.Studio.Designer.Configuration;
using Altinn.Studio.Designer.RepositoryClient.Model;
using Altinn.Studio.Designer.Services.Implementation;
using AltinnCore.Authentication.Constants;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -48,7 +46,7 @@ public async Task CreateBranch_Successfull_BranchReturned()
BaseAddress = new Uri("http://studio.localhost/repos/api/v1")
};

GiteaAPIWrapper sut = GetServiceForTest("testUser", httpClient);
GiteaAPIWrapper sut = GetServiceForTest(httpClient);

// Act
Branch actual = await sut.CreateBranch("ttd", "apps-test-2021", "master");
Expand Down Expand Up @@ -80,7 +78,7 @@ public async Task CreateBranch_ConflictFromGitea_ThrowsException()
BaseAddress = new Uri("http://studio.localhost/repos/api/v1")
};

GiteaAPIWrapper sut = GetServiceForTest("testUser", httpClient);
GiteaAPIWrapper sut = GetServiceForTest(httpClient);

// Act
await Assert.ThrowsAsync<GiteaApiWrapperException>(() => sut.CreateBranch("ttd", "apps-test-2021", "master"));
Expand Down Expand Up @@ -117,7 +115,7 @@ public async Task Search_Successfull_Repo_Returned_One_Page()
BaseAddress = new Uri("http://studio.localhost/repos/api/v1")
};

GiteaAPIWrapper giteaApi = GetServiceForTest("testUser", httpClient);
GiteaAPIWrapper giteaApi = GetServiceForTest(httpClient);

SearchResults result = await giteaApi.SearchRepo(GetSearchOptions());
Assert.Equal(searchResult.Data.Count, result.TotalCount);
Expand Down Expand Up @@ -158,7 +156,7 @@ public async Task Search_Successfull_Repo_Returned_Multiple_Pages()
BaseAddress = new Uri("http://studio.localhost/repos/api/v1")
};

GiteaAPIWrapper giteaApi = GetServiceForTest("testUser", httpClient);
GiteaAPIWrapper giteaApi = GetServiceForTest(httpClient);

SearchOptions searchOptions = GetSearchOptions();
searchOptions.Limit = 10;
Expand Down Expand Up @@ -192,7 +190,7 @@ public async Task Search_Failed()
BaseAddress = new Uri("http://studio.localhost/repos/api/v1")
};

GiteaAPIWrapper giteaApi = GetServiceForTest("testUser", httpClient);
GiteaAPIWrapper giteaApi = GetServiceForTest(httpClient);

SearchResults result = await giteaApi.SearchRepo(GetSearchOptions());

Expand Down Expand Up @@ -226,9 +224,9 @@ public async Task Get_StarredRepos_Ok()
BaseAddress = new Uri("http://studio.localhost/designer/api/user/starred")
};

GiteaAPIWrapper giteaApi = GetServiceForTest("testUser", httpClient);
GiteaAPIWrapper giteaApi = GetServiceForTest(httpClient);

IList<Repository> result = await giteaApi.GetStarred();
await giteaApi.GetStarred();
Assert.Equal(10, repositories.Count);
}

Expand Down Expand Up @@ -258,7 +256,7 @@ public async Task Put_StarredRepos(bool expectedResult, HttpStatusCode httpStatu
BaseAddress = new Uri("http://studio.localhost/designer/api/user/starred")
};

GiteaAPIWrapper giteaApi = GetServiceForTest("testUser", httpClient);
GiteaAPIWrapper giteaApi = GetServiceForTest(httpClient);

bool result = await giteaApi.PutStarred("org", "repository");

Expand Down Expand Up @@ -291,7 +289,7 @@ public async Task Delete_StarredRepos(bool expectedResult, HttpStatusCode httpSt
BaseAddress = new Uri("http://studio.localhost/designer/api/user/starred")
};

GiteaAPIWrapper giteaApi = GetServiceForTest("testUser", httpClient);
GiteaAPIWrapper giteaApi = GetServiceForTest(httpClient);

bool result = await giteaApi.DeleteStarred("org", "repository");

Expand Down Expand Up @@ -346,7 +344,7 @@ public async Task Get_Repository()
};

// Passing the test specific mock setup in, sprinkles a bit more mock setup and returns a valid GiteaAPIWrapper
GiteaAPIWrapper giteaApi = GetServiceForTest("testUser", httpClient);
GiteaAPIWrapper giteaApi = GetServiceForTest(httpClient);

// Act
Repository result = await giteaApi.GetRepository("ttd", "repo");
Expand All @@ -355,26 +353,12 @@ public async Task Get_Repository()
Assert.Equal(1769, result.Id);
}

private static HttpContext GetHttpContextForTestUser(string userName)
private static GiteaAPIWrapper GetServiceForTest(HttpClient client)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(AltinnCoreClaimTypes.Developer, userName, ClaimValueTypes.String, "altinn.no"));
ClaimsIdentity identity = new ClaimsIdentity("TestUserLogin");
identity.AddClaims(claims);

ClaimsPrincipal principal = new ClaimsPrincipal(identity);
HttpContext c = new DefaultHttpContext();
c.Request.HttpContext.User = principal;

return c;
}

private static GiteaAPIWrapper GetServiceForTest(string developer, HttpClient c)
{
HttpContext ctx = GetHttpContextForTestUser(developer);
HttpContext context = new DefaultHttpContext();

Mock<IHttpContextAccessor> httpContextAccessorMock = new Mock<IHttpContextAccessor>();
httpContextAccessorMock.Setup(s => s.HttpContext).Returns(ctx);
httpContextAccessorMock.Setup(s => s.HttpContext).Returns(context);

string unitTestFolder = Path.GetDirectoryName(new Uri(typeof(RepositorySITests).Assembly.Location).LocalPath);
var repoSettings = new ServiceRepositorySettings()
Expand All @@ -387,7 +371,7 @@ private static GiteaAPIWrapper GetServiceForTest(string developer, HttpClient c)
httpContextAccessorMock.Object,
new MemoryCache(new MemoryCacheOptions()),
new Mock<ILogger<GiteaAPIWrapper>>().Object,
c);
client);

return service;
}
Expand Down
27 changes: 9 additions & 18 deletions backend/tests/Designer.Tests/Services/ReleaseServiceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;
using Altinn.Studio.Designer.Infrastructure.Models;
using Altinn.Studio.Designer.Repository;
Expand All @@ -14,7 +13,6 @@
using Altinn.Studio.Designer.TypedHttpClients.AzureDevOps.Models;
using Altinn.Studio.Designer.ViewModels.Request;
using Altinn.Studio.Designer.ViewModels.Response;
using AltinnCore.Authentication.Constants;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Rest.TransientFaultHandling;
Expand All @@ -36,7 +34,7 @@ public class ReleaseServiceTest
public ReleaseServiceTest()
{
_httpContextAccessor = new Mock<IHttpContextAccessor>();
_httpContextAccessor.Setup(req => req.HttpContext).Returns(GetHttpContextForTestUser("testuser"));
_httpContextAccessor.Setup(req => req.HttpContext).Returns(new DefaultHttpContext());
_releaseLogger = new Mock<ILogger<ReleaseService>>();
_releaseRepository = new Mock<IReleaseRepository>();
_azureDevOpsBuildClient = new Mock<IAzureDevOpsBuildClient>();
Expand Down Expand Up @@ -78,6 +76,14 @@ public async Task CreateAsync_OK()
ReleaseEntity result = await releaseService.CreateAsync(releaseEntity);

// Assert
Assert.NotNull(result);

var properties = result.GetType().GetProperties();
foreach (var property in properties)
{
Assert.NotNull(property.GetValue(result));
}

_releaseRepository.Verify(r => r.Get(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), buildStatus, buildResult), Times.Once);
_releaseRepository.Verify(r => r.Create(It.IsAny<ReleaseEntity>()), Times.Once);
_azureDevOpsBuildClient.Verify(b => b.QueueAsync(It.IsAny<QueueBuildParameters>(), It.IsAny<int>()), Times.Once);
Expand Down Expand Up @@ -178,21 +184,6 @@ public async Task UpdateAsync_OK()
_releaseRepository.Verify(r => r.Update(It.IsAny<ReleaseEntity>()), Times.Once);
}

private static HttpContext GetHttpContextForTestUser(string userName)
{
List<Claim> claims = new() { new Claim(AltinnCoreClaimTypes.Developer, userName, ClaimValueTypes.String, "altinn.no") };
ClaimsIdentity identity = new("TestUserLogin");
identity.AddClaims(claims);

ClaimsPrincipal principal = new(identity);
HttpContext c = new DefaultHttpContext();
c.Request.HttpContext.User = principal;
c.Request.RouteValues.Add("org", "ttd");
c.Request.RouteValues.Add("app", "apps-test-tba");

return c;
}

private static List<ReleaseEntity> GetReleases(string filename)
{
string unitTestFolder = Path.GetDirectoryName(new Uri(typeof(ReleaseServiceTest).Assembly.Location).LocalPath);
Expand Down
2 changes: 0 additions & 2 deletions backend/tests/Designer.Tests/Services/RepositorySITests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
using Altinn.Studio.Designer.Services.Implementation;
using Altinn.Studio.Designer.Services.Interfaces;
using Altinn.Studio.Designer.TypedHttpClients.AltinnStorage;
using AltinnCore.Authentication.Constants;

using Designer.Tests.Mocks;
using Designer.Tests.Utils;
Expand Down Expand Up @@ -261,7 +260,6 @@ public async Task DeleteRepository_SourceControlServiceIsCalled()
private static HttpContext GetHttpContextForTestUser(string userName)
{
List<Claim> claims = new();
claims.Add(new Claim(AltinnCoreClaimTypes.Developer, userName, ClaimValueTypes.String, "altinn.no"));
claims.Add(new Claim(ClaimTypes.Name, userName));
ClaimsIdentity identity = new("TestUserLogin");
identity.AddClaims(claims);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Claims;
using System.Threading.Tasks;
using Altinn.Studio.Designer.Models;
using Altinn.Studio.Designer.RepositoryClient.Model;
using Altinn.Studio.Designer.Services.Implementation;
using Altinn.Studio.Designer.Services.Interfaces;
using AltinnCore.Authentication.Constants;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
Expand Down Expand Up @@ -423,7 +418,7 @@ public void DecoratedISourceControlService_StoreAppTokenForUser_LogsErrorWithAdd

public IServiceProvider GetServiceProvider(Mock<ILoggerFactory> loggerFactoryMock)
{
HttpContext httpContext = GetHttpContextForTestUser("testUser");
HttpContext httpContext = new DefaultHttpContext();

Mock<IHttpContextAccessor> httpContextAccessorMock = new Mock<IHttpContextAccessor>();
httpContextAccessorMock.Setup(s => s.HttpContext).Returns(httpContext);
Expand All @@ -444,23 +439,6 @@ public IServiceProvider GetServiceProvider(Mock<ILoggerFactory> loggerFactoryMoc
// Create a scope to obtain a reference to a scoped service provider
return services.CreateScope().ServiceProvider;
}

private static HttpContext GetHttpContextForTestUser(string userName)
{
var claims = new List<Claim>();
claims.Add(new Claim(AltinnCoreClaimTypes.Developer, userName, ClaimValueTypes.String, "altinn.no"));
claims.Add(new Claim(ClaimTypes.Name, userName));
ClaimsIdentity identity = new ClaimsIdentity("TestUserLogin");
identity.AddClaims(claims);

ClaimsPrincipal principal = new ClaimsPrincipal(identity);
HttpContext c = new DefaultHttpContext();
c.Request.HttpContext.User = principal;
c.Request.RouteValues.Add("org", "ttd");
c.Request.RouteValues.Add("app", "apps-test-tba");

return c;
}
}

public class SourceControlStub : ISourceControl
Expand Down
Loading

0 comments on commit f0afd1a

Please sign in to comment.