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

Merged
merged 20 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ import { createQueryClientMock } from 'app-shared/mocks/queryClientMock';
import { QueryKey } from 'app-shared/types/QueryKey';
import { PackagesRouter } from 'app-shared/navigation/PackagesRouter';
import { app, org } from '@studio/testing/testids';
import { useUserOrgPermissionQuery } from '../../hooks/queries/useUserOrgPermissionsQuery';

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

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

const mockServiceFullName: string = `${org}/${app}`;
const mockUser: User = {
Expand Down
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(),
},
);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { type FormEvent, type ChangeEvent } from 'react';
import React, { type FormEvent, type ChangeEvent, useState } from 'react';
import classes from './NewApplicationForm.module.css';
import { StudioButton, StudioSpinner } from '@studio/components';
import { useTranslation } from 'react-i18next';
Expand All @@ -11,6 +11,7 @@ import { SelectedContextType } from 'dashboard/context/HeaderContext';
import { type NewAppForm } from '../../types/NewAppForm';
import { useCreateAppFormValidation } from './hooks/useCreateAppFormValidation';
import { Link } from 'react-router-dom';
import { useUserOrgPermissionQuery } from '../../hooks/queries/useUserOrgPermissionsQuery';

type CancelButton = {
onClick: () => void;
Expand Down Expand Up @@ -47,11 +48,14 @@ export const NewApplicationForm = ({
const { t } = useTranslation();
const selectedContext = useSelectedContext();
const { validateRepoOwnerName, validateRepoName } = useCreateAppFormValidation();

const defaultSelectedOrgOrUser: string =
selectedContext === SelectedContextType.Self || selectedContext === SelectedContextType.All
? user.login
: selectedContext;
const [currentSelectedOrg, setCurrentSelectedOrg] = useState<string>(defaultSelectedOrgOrUser);
const { data: userOrgPermission, isFetching } = useUserOrgPermissionQuery(currentSelectedOrg, {
enabled: Boolean(currentSelectedOrg),
});

const validateTextValue = (event: ChangeEvent<HTMLInputElement>) => {
const { errorMessage: repoNameErrorMessage, isValid: isRepoNameValid } = validateRepoName(
Expand Down Expand Up @@ -96,14 +100,22 @@ export const NewApplicationForm = ({
return isOrgValid && isRepoNameValid;
};

const createRepoAccessError: string =
!userOrgPermission?.canCreateOrgRepo && !isFetching
? t('dashboard.missing_service_owner_rights_error_message')
: '';

const hasCreateRepoAccessError: boolean = Boolean(createRepoAccessError);

return (
<form onSubmit={handleSubmit} className={classes.form}>
<ServiceOwnerSelector
name='org'
user={user}
organizations={organizations}
errorMessage={formError.org}
errorMessage={formError.org || createRepoAccessError}
selectedOrgOrUser={defaultSelectedOrgOrUser}
onChange={setCurrentSelectedOrg}
/>
<RepoNameInput
name='repoName'
Expand All @@ -115,7 +127,7 @@ export const NewApplicationForm = ({
<StudioSpinner showSpinnerTitle spinnerTitle={t('dashboard.creating_your_service')} />
) : (
<>
<StudioButton type='submit' variant='primary'>
<StudioButton type='submit' variant='primary' disabled={hasCreateRepoAccessError}>
{submitButtonText}
</StudioButton>
<CancelComponent actionableElement={actionableElement} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { textMock } from '../../../testing/mocks/i18nMock';
import { user as mockUser } from 'app-shared/mocks/mocks';
import userEvent from '@testing-library/user-event';

const defaultProps = {
const defaultProps: ServiceOwnerSelectorProps = {
selectedOrgOrUser: 'userLogin',
user: {
...mockUser,
Expand All @@ -21,6 +21,7 @@ const defaultProps = {
],
errorMessage: '',
name: '',
onChange: () => {},
};

const renderServiceOwnerSelector = (props: Partial<ServiceOwnerSelectorProps> = {}) => {
Expand Down Expand Up @@ -77,4 +78,16 @@ describe('ServiceOwnerSelector', () => {
const select = screen.getByLabelText(textMock('general.service_owner'));
expect(select).toHaveValue(defaultProps.user.login);
});

it('should execute the onChange callback when service owner is changed', async () => {
const user = userEvent.setup();
const selectedOrgOrUser = 'all';
const onChangeMock = jest.fn();
renderServiceOwnerSelector({ selectedOrgOrUser, onChange: onChangeMock });

const select = screen.getByLabelText(textMock('general.service_owner'));
await user.selectOptions(select, 'organizationUsername');
expect(onChangeMock).toHaveBeenCalledWith('organizationUsername');
expect(onChangeMock).toHaveBeenCalledTimes(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export type ServiceOwnerSelectorProps = {
organizations: Organization[];
errorMessage?: string;
name?: string;
onChange?: (org: string) => void;
};

export const ServiceOwnerSelector = ({
Expand All @@ -18,6 +19,7 @@ export const ServiceOwnerSelector = ({
organizations,
errorMessage,
name,
onChange,
}: ServiceOwnerSelectorProps) => {
const { t } = useTranslation();
const serviceOwnerId: string = useId();
Expand All @@ -38,6 +40,7 @@ export const ServiceOwnerSelector = ({
name={name}
id={serviceOwnerId}
defaultValue={defaultValue}
onChange={(event) => onChange(event.target.value)}
>
{selectableOptions.map(({ value, label }) => (
<option key={value} value={value}>
Expand Down
20 changes: 20 additions & 0 deletions frontend/dashboard/hooks/queries/useUserOrgPermissionsQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { useServicesContext } from 'app-shared/contexts/ServicesContext';
import type { UseQueryResult } from '@tanstack/react-query';
import { useQuery } from '@tanstack/react-query';
import { QueryKey } from 'app-shared/types/QueryKey';

type UserOrgPermission = {
canCreateOrgRepo: boolean;
};

export const useUserOrgPermissionQuery = (
org: string,
options?: { enabled: boolean },
): UseQueryResult<UserOrgPermission> => {
const { getUserOrgPermissions } = useServicesContext();
return useQuery({
queryKey: [QueryKey.UserOrgPermissions, org],
queryFn: () => getUserOrgPermissions(org),
...options,
});
};
1 change: 1 addition & 0 deletions frontend/language/src/nb.json
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@
"dashboard.loading": "Laster inn dashboardet",
"dashboard.loading_resource_list": "Laster inn ressursliste",
"dashboard.make_copy": "Lag kopi",
"dashboard.missing_service_owner_rights_error_message": "Du mangler tilgang til å opprette en ny applikasjon i valgt organisasjon.",
"dashboard.my_apps": "Mine apper",
"dashboard.my_data_models": "Mine datamodeller",
"dashboard.my_resources": "Mine ressurser",
Expand Down
3 changes: 3 additions & 0 deletions frontend/packages/shared/src/api/paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ export const appMetadataAttachmentPath = (org, app) => `${basePath}/${org}/${app
// App version
export const appVersionPath = (org, app) => `${basePath}/${org}/${app}/app-development/app-version`; // Get

// UserOrgPermissions
export const userOrgPermissionsPath = (org) => `${basePath}/user/org-permissions/${org}`;

// Config
export const serviceConfigPath = (org, app) => `${basePath}/${org}/${app}/config`; // Get, Post

Expand Down
2 changes: 2 additions & 0 deletions frontend/packages/shared/src/api/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import {
resourceAccessPackageServicesPath,
optionListPath,
optionListReferencesPath,
userOrgPermissionsPath,
dataTypePath,
} from './paths';

Expand Down Expand Up @@ -140,6 +141,7 @@ export const getTextLanguages = (owner: string, app: string): Promise<string[]>
export const getTextResources = (owner: string, app: string, lang: string) => get<ITextResourcesWithLanguage>(textResourcesPath(owner, app, lang));
export const getUser = () => get<User>(userCurrentPath());
export const getWidgetSettings = (owner: string, app: string) => get<WidgetSettingsResponse | null>(widgetSettingsPath(owner, app));
export const getUserOrgPermissions = (org: string) => get(userOrgPermissionsPath(org));
export const searchRepos = (filter: SearchRepoFilterParams) => get<SearchRepositoryResponse>(`${repoSearchPath()}${buildQueryParams(filter)}`);
export const validateImageFromExternalUrl = (owner: string, app: string, url: string) => get<ExternalImageUrlValidationResponse>(validateImageFromExternalUrlPath(owner, app, url));

Expand Down
5 changes: 5 additions & 0 deletions frontend/packages/shared/src/mocks/queriesMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,11 @@ export const queriesMock: ServicesContextProps = {
validateImageFromExternalUrl: jest
.fn()
.mockImplementation(() => Promise.resolve<ExternalImageUrlValidationResponse>('Ok')),
getUserOrgPermissions: jest.fn().mockImplementation(() =>
Promise.resolve({
canCreateOrgRepo: true,
}),
),

// Queries - Settings modal
getAppConfig: jest.fn().mockImplementation(() => Promise.resolve<AppConfig>(appConfig)),
Expand Down
1 change: 1 addition & 0 deletions frontend/packages/shared/src/types/QueryKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export enum QueryKey {
IsLoggedInWithAnsattporten = 'IsLoggedInWithAnsattporten',
AppScopes = 'AppScopes',
SelectedAppScopes = 'SelectedAppScopes',
UserOrgPermissions = 'UserOrgPermissions',
DataType = 'DataType',

// Resourceadm
Expand Down
Loading