Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(dashboard): Improve validation for missing permissions when creating new app #14395

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
13 changes: 12 additions & 1 deletion backend/src/Designer/Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Generic;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All backend code should be reviewed in another PR: #14389

using System.Threading.Tasks;
using Altinn.Studio.Designer.Models.Dto;
using Altinn.Studio.Designer.Services.Interfaces;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authorization;
Expand All @@ -17,16 +18,18 @@
{
private readonly IGitea _giteaApi;
private readonly IAntiforgery _antiforgery;
private readonly IUserService _userService;

/// <summary>
/// Initializes a new instance of the <see cref="UserController"/> class.
/// </summary>
/// <param name="giteaWrapper">the gitea wrapper</param>
/// <param name="antiforgery">Access to the antiforgery system in .NET Core</param>
public UserController(IGitea giteaWrapper, IAntiforgery antiforgery)
public UserController(IGitea giteaWrapper, IAntiforgery antiforgery, IUserService userService)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Run integration tests against actual gitea and db

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Run integration tests against actual gitea and db

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Run dotnet build and test (ubuntu-latest)

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Run dotnet build and test (ubuntu-latest)

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Analyze

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Analyze

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Run dotnet build and test (windows-latest)

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Run dotnet build and test (windows-latest)

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Run dotnet build and test (macos-latest)

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)

Check warning on line 28 in backend/src/Designer/Controllers/UserController.cs

View workflow job for this annotation

GitHub Actions / Run dotnet build and test (macos-latest)

Parameter 'userService' has no matching param tag in the XML comment for 'UserController.UserController(IGitea, IAntiforgery, IUserService)' (but other parameters do)
{
_giteaApi = giteaWrapper;
_antiforgery = antiforgery;
_userService = userService;
}

/// <summary>
Expand Down Expand Up @@ -80,6 +83,14 @@
return success ? NoContent() : StatusCode(418);
}

[HttpGet]
[Route("org-permissions/{org}")]
public async Task<IActionResult> HasAccessToCreateRepository(string org)
{
UserOrgPermission userOrg = await _userService.GetUserOrgPermission(org);
return Ok(userOrg);
}

/// <summary>
/// Removes the star marking on the specified repository.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions backend/src/Designer/Infrastructure/ServiceRegistration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public static IServiceCollection RegisterServiceImplementations(this IServiceCol
services.AddScoped<IReleaseRepository, ORMReleaseRepository>();
services.AddScoped<IDeploymentRepository, ORMDeploymentRepository>();
services.AddScoped<IAppScopesRepository, AppScopesRepository>();
services.AddScoped<IUserService, UserService>();
services.AddTransient<IReleaseService, ReleaseService>();
services.AddTransient<IDeploymentService, DeploymentService>();
services.AddTransient<IAppScopesService, AppScopesService>();
Expand Down
6 changes: 6 additions & 0 deletions backend/src/Designer/Models/Dto/UserOrgPermission.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Altinn.Studio.Designer.Models.Dto;

public class UserOrgPermission
{
public bool CanCreateOrgRepo { get; set; }
}
2 changes: 2 additions & 0 deletions backend/src/Designer/RepositoryClient/Model/Team.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ public class Team
/// </summary>
public string Name { get; set; }

public bool can_create_org_repo { get; set; }

/// <summary>
/// The organization that owns the team
/// </summary>
Expand Down
44 changes: 44 additions & 0 deletions backend/src/Designer/Services/Implementation/UserService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Altinn.Studio.Designer.Helpers;
using Altinn.Studio.Designer.Models.Dto;
using Altinn.Studio.Designer.RepositoryClient.Model;
using Altinn.Studio.Designer.Services.Interfaces;
using Microsoft.AspNetCore.Http;

namespace Altinn.Studio.Designer.Services.Implementation;

public class UserService : IUserService
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IGitea _giteaApi;

public UserService(IHttpContextAccessor httpContextAccessor, IGitea giteaApi)
{
_httpContextAccessor = httpContextAccessor;
_giteaApi = giteaApi;
}

public async Task<UserOrgPermission> GetUserOrgPermission(string org)
{
bool canCreateOrgRepo = await HasPermissionToCreateOrgRepo(org);
return new UserOrgPermission() { CanCreateOrgRepo = canCreateOrgRepo };
}

private bool IsUserSelfOrg(string org)
{
return AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext) == org;
}

private async Task<bool> HasPermissionToCreateOrgRepo(string org)
{
List<Team> teams = await _giteaApi.GetTeams();
return IsUserSelfOrg(org) || teams.Any(team => CheckPermissionToCreateOrgRepo(team, org));
}

private static bool CheckPermissionToCreateOrgRepo(Team team, string org)
{
return team.can_create_org_repo && team.Organization.Username == org;
}
}
9 changes: 9 additions & 0 deletions backend/src/Designer/Services/Interfaces/IUserService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.Threading.Tasks;
using Altinn.Studio.Designer.Models.Dto;

namespace Altinn.Studio.Designer.Services.Interfaces;

public interface IUserService
{
public Task<UserOrgPermission> GetUserOrgPermission(string org);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Altinn.Studio.Designer.Models.Dto;
using Altinn.Studio.Designer.RepositoryClient.Model;
using Designer.Tests.Fixtures;
using Designer.Tests.Utils;
Expand All @@ -14,8 +15,9 @@ namespace Designer.Tests.GiteaIntegrationTests
{
public class UserControllerGiteaIntegrationTests : GiteaIntegrationTestsBase<UserControllerGiteaIntegrationTests>
{

public UserControllerGiteaIntegrationTests(GiteaWebAppApplicationFactoryFixture<Program> factory, GiteaFixture giteaFixture, SharedDesignerHttpClientProvider sharedDesignerHttpClientProvider) : base(factory, giteaFixture, sharedDesignerHttpClientProvider)
public UserControllerGiteaIntegrationTests(GiteaWebAppApplicationFactoryFixture<Program> factory,
GiteaFixture giteaFixture, SharedDesignerHttpClientProvider sharedDesignerHttpClientProvider) : base(
factory, giteaFixture, sharedDesignerHttpClientProvider)
{
}

Expand All @@ -31,10 +33,8 @@ public async Task GetCurrentUser_ShouldReturnOk(string expectedUserName, string
response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Headers.First(h => h.Key == "Set-Cookie").Value.Should().Contain(e => e.Contains("XSRF-TOKEN"));
string content = await response.Content.ReadAsStringAsync();
var user = JsonSerializer.Deserialize<User>(content, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
var user = JsonSerializer.Deserialize<User>(content,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

user.Login.Should().Be(expectedUserName);
user.Email.Should().Be(expectedEmail);
Expand Down Expand Up @@ -62,16 +62,37 @@ public async Task StarredEndpoints_ShouldBehaveAsExpected(string org)
string targetRepo = TestDataHelper.GenerateTestRepoName();
await CreateAppUsingDesigner(org, targetRepo);

using var putStarredResponse = await HttpClient.PutAsync($"designer/api/user/starred/{org}/{targetRepo}", null);
using var putStarredResponse =
await HttpClient.PutAsync($"designer/api/user/starred/{org}/{targetRepo}", null);
putStarredResponse.StatusCode.Should().Be(HttpStatusCode.NoContent);
await GetAndVerifyStarredRepos(targetRepo);

using var deleteStarredResponse = await HttpClient.DeleteAsync($"designer/api/user/starred/{org}/{targetRepo}");
using var deleteStarredResponse =
await HttpClient.DeleteAsync($"designer/api/user/starred/{org}/{targetRepo}");
deleteStarredResponse.StatusCode.Should().Be(HttpStatusCode.NoContent);

await GetAndVerifyStarredRepos();
}

[Theory]
[InlineData(GiteaConstants.TestOrgUsername, true)]
[InlineData("OtherOrg", false)]
public async Task HasAccessToCreateRepository_ShouldReturnCorrectPermissions(string org, bool expectedCanCreate)
{
string requestUrl = $"designer/api/user/org-permissions/{org}";

using var response = await HttpClient.GetAsync(requestUrl);

response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();

var userOrgPermission = JsonSerializer.Deserialize<UserOrgPermission>(content,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

userOrgPermission.Should().NotBeNull();
userOrgPermission.CanCreateOrgRepo.Should().Be(expectedCanCreate);
}

private async Task GetAndVerifyStarredRepos(params string[] expectedStarredRepos)
{
using var response = await HttpClient.GetAsync("designer/api/user/starred");
Expand All @@ -83,6 +104,5 @@ private async Task GetAndVerifyStarredRepos(params string[] expectedStarredRepos
content.Should().Contain(r => r.Name == expectedStarredRepo);
}
}

}
}
49 changes: 49 additions & 0 deletions backend/tests/Designer.Tests/Services/UserServiceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Altinn.Studio.Designer.RepositoryClient.Model;
using Altinn.Studio.Designer.Services.Implementation;
using Altinn.Studio.Designer.Services.Interfaces;
using Microsoft.AspNetCore.Http;
using Moq;
using Xunit;

namespace Designer.Tests.Services
{
public class UserServiceTests
{
private readonly Mock<IHttpContextAccessor> _httpContextAccessor;
private readonly Mock<IGitea> _giteaApi;

public UserServiceTests()
{
_httpContextAccessor = new Mock<IHttpContextAccessor>();
_giteaApi = new Mock<IGitea>();
var context = new DefaultHttpContext();
_httpContextAccessor.Setup(req => req.HttpContext).Returns(context);
}

[Theory]
[InlineData("org1", false)]
[InlineData("org2", true)]
public async Task GetUserOrgPermission_ReturnsCorrectPermission(string org, bool expectedCanCreate)
{
var teams = new List<Team>
{
new Team
{
Organization = new Organization { Username = org },
can_create_org_repo = expectedCanCreate
}
};

_giteaApi.Setup(api => api.GetTeams()).ReturnsAsync(teams);

var userService = new UserService(_httpContextAccessor.Object, _giteaApi.Object);

var result = await userService.GetUserOrgPermission(org);

Assert.NotNull(result);
Assert.Equal(expectedCanCreate, result.CanCreateOrgRepo);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { screen } from '@testing-library/react';
import {
NewApplicationForm,
type NewApplicationFormProps,
Expand All @@ -8,7 +8,11 @@ import {
import { type User } from 'app-shared/types/Repository';
import { type Organization } from 'app-shared/types/Organization';
import userEvent from '@testing-library/user-event';
import { textMock } from '../../../testing/mocks/i18nMock';
import { textMock } from '@studio/testing/mocks/i18nMock';
import type { ServicesContextProps } from 'app-shared/contexts/ServicesContext';
import { renderWithProviders } from '../../testing/mocks';
import { createQueryClientMock } from 'app-shared/mocks/queryClientMock';
import { useUserOrgPermissionQuery } from '../../hooks/queries/useUserOrgPermissionsQuery';

const mockOnSubmit = jest.fn();

Expand Down Expand Up @@ -51,12 +55,18 @@ const defaultProps: NewApplicationFormProps = {
actionableElement: mockCancelComponentButton,
};

jest.mock('../../hooks/queries/useUserOrgPermissionsQuery');

(useUserOrgPermissionQuery as jest.Mock).mockReturnValue({
data: { canCreateOrgRepo: true },
});

describe('NewApplicationForm', () => {
afterEach(jest.clearAllMocks);

it('calls onSubmit when form is submitted with valid data', async () => {
const user = userEvent.setup();
render(<NewApplicationForm {...defaultProps} />);
renderNewApplicationForm();

const select = screen.getByLabelText(textMock('general.service_owner'));
await user.click(select);
Expand All @@ -81,7 +91,7 @@ describe('NewApplicationForm', () => {

it('does not call onSubmit when form is submitted with invalid data', async () => {
const user = userEvent.setup();
render(<NewApplicationForm {...defaultProps} />);
renderNewApplicationForm();

const select = screen.getByLabelText(textMock('general.service_owner'));
await user.click(select);
Expand All @@ -96,4 +106,47 @@ describe('NewApplicationForm', () => {

expect(mockOnSubmit).toHaveBeenCalledTimes(0);
});

it('should notify the user if they lack permission to create a new application for the organization and disable the "Create" button', async () => {
const user = userEvent.setup();
(useUserOrgPermissionQuery as jest.Mock).mockReturnValue({
data: { canCreateOrgRepo: false },
});
renderNewApplicationForm(defaultProps);

const serviceOwnerSelect = screen.getByLabelText(textMock('general.service_owner'));
await user.selectOptions(serviceOwnerSelect, mockOrg.username);
expect(
await screen.findByText(textMock('dashboard.missing_service_owner_rights_error_message')),
).toBeInTheDocument();
expect(screen.getByRole('button', { name: mockSubmitbuttonText })).toBeDisabled();
});

it('should enable the "Create" button and not display an error if the user has permission to create an organization', async () => {
const user = userEvent.setup();
(useUserOrgPermissionQuery as jest.Mock).mockReturnValue({
data: { canCreateOrgRepo: true },
});
renderNewApplicationForm(defaultProps);

const serviceOwnerSelect = screen.getByLabelText(textMock('general.service_owner'));
await user.selectOptions(serviceOwnerSelect, mockOrg.username);
expect(
screen.queryByText(textMock('dashboard.missing_service_owner_rights_error_message')),
).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: mockSubmitbuttonText })).toBeEnabled();
});
});

function renderNewApplicationForm(
newApplicationFormProps?: Partial<NewApplicationFormProps>,
services?: Partial<ServicesContextProps>,
) {
return renderWithProviders(
<NewApplicationForm {...defaultProps} {...newApplicationFormProps} />,
{
queries: services,
queryClient: createQueryClientMock(),
},
);
}
Loading
Loading