Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions libs/i18n/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -1517,6 +1517,7 @@
"Password is required when password authentication is enabled.": "Password is required when password authentication is enabled.",
"Name is required for quadlet applications.": "Name is required for quadlet applications.",
"Name is required for compose applications.": "Name is required for compose applications.",
"The following host ports are used in more than one application: {{ports}}": "The following host ports are used in more than one application: {{ports}}",
"Name is required, another application uses the same image.": "Name is required, another application uses the same image.",
"Cannot be decimal": "Cannot be decimal",
"Percentage must be between 1 and 100.": "Percentage must be between 1 and 100.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,18 @@ import { FormGroup, Grid } from '@patternfly/react-core';
import { FormGroupWithHelperText } from '../../../common/WithHelperText';
import TextField from '../../../form/TextField';
import ApplicationPortMappingField from '../../../form/ApplicationPortMappingField';
import ErrorHelperText from '../../../form/FieldHelperText';
import { useTranslation } from '../../../../hooks/useTranslation';
import { type PortMapping, type SingleContainerAppForm } from '../../../../types/deviceSpec';
import ApplicationImageForm from './ApplicationImageForm';

const ApplicationContainerForm = ({ index, isReadOnly }: { index: number; isReadOnly?: boolean }) => {
const { t } = useTranslation();
const appFieldName = `applications[${index}].app`;
const [{ value: app }] = useField<SingleContainerAppForm>(`${appFieldName}`);
const [{ value: app }, appMeta] = useField<SingleContainerAppForm>(`${appFieldName}`);
const portsErrorId = `application-${index}-ports-error`;
const portsErrorMessage = (appMeta.error as { ports?: string } | undefined)?.ports;
const hasPortsError = !!portsErrorMessage;
const { setFieldValue, setFieldTouched } = useFormikContext();
const ports = React.useMemo(() => app.ports || [], [app.ports]);

Expand All @@ -33,13 +37,15 @@ const ApplicationContainerForm = ({ index, isReadOnly }: { index: number; isRead
<ApplicationImageForm applicationName={appFieldName} isReadOnly={isReadOnly} />

<ApplicationPortMappingField
errorId={hasPortsError ? portsErrorId : undefined}
ports={ports}
onChange={updatePorts}
isReadOnly={isReadOnly}
description={t('Provide a list of ports to map to the container')}
targetPortAriaLabel={t('Container port')}
targetPortPlaceholder={t('Enter container port')}
/>
{hasPortsError && <ErrorHelperText id={portsErrorId} error={portsErrorMessage} touchRequired={false} />}

<FormGroup label={t('Resources')}>
<Grid hasGutter>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type ApplicationPortMappingFieldProps = {
targetPortAriaLabel: string;
targetPortPlaceholder: string;
withProtocol?: boolean;
errorId?: string;
};

const normalizeProtocol = (protocol?: string) => (protocol || 'tcp').toLowerCase();
Expand Down Expand Up @@ -67,6 +68,7 @@ const ApplicationPortMappingField = ({
targetPortAriaLabel,
targetPortPlaceholder,
withProtocol,
errorId,
}: ApplicationPortMappingFieldProps) => {
const { t } = useTranslation();

Expand Down Expand Up @@ -287,6 +289,8 @@ const ApplicationPortMappingField = ({
<SplitItem isFilled>
<TextInput
aria-label={t('Host port')}
aria-invalid={errorId ? true : undefined}
aria-describedby={errorId}
value={hostPort}
placeholder={t('Enter host port')}
onChange={(_, value) => {
Expand Down
5 changes: 3 additions & 2 deletions libs/ui-components/src/components/form/FieldHelperText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ExclamationCircleIcon } from '@patternfly/react-icons/dist/js/icons/exc
import { useTranslation } from '../../hooks/useTranslation';

type ErrorHelperTextProps = {
id?: string;
meta?: FieldMetaProps<unknown>;
touchRequired?: boolean;
error?: React.ReactNode;
Expand All @@ -32,7 +33,7 @@ export const DefaultHelperText = ({ helperText }: DefaultHelperTextProps) => {
) : null;
};

const ErrorHelperText = ({ meta, error, touchRequired = true }: ErrorHelperTextProps) => {
const ErrorHelperText = ({ id, meta, error, touchRequired = true }: ErrorHelperTextProps) => {
const { t } = useTranslation();
let content: React.ReactNode;
if (meta) {
Expand All @@ -42,7 +43,7 @@ const ErrorHelperText = ({ meta, error, touchRequired = true }: ErrorHelperTextP
}
return content ? (
<FlightCtlHelperText isLiveRegion>
<HelperTextItem variant="error" icon={<ExclamationCircleIcon />} screenReaderText={t('Validation error')}>
<HelperTextItem id={id} variant="error" icon={<ExclamationCircleIcon />} screenReaderText={t('Validation error')}>
{content}
</HelperTextItem>
</FlightCtlHelperText>
Expand Down
149 changes: 149 additions & 0 deletions libs/ui-components/src/components/form/validations.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import { beforeAll, describe, expect, it } from 'vitest';
import i18next from 'i18next';
import * as Yup from 'yup';
import { getIn, yupToFormErrors } from 'formik';

import { AppType } from '@flightctl/types';
import { AppSpecType, type ApplicationEntry, type PortMapping } from '../../types/deviceSpec';
import { isDuplicatePortMapping, validApplicationsSchema } from './validations';

const app = (name: string, ports: PortMapping[]): ApplicationEntry => ({
type: 'manual',
app: {
appType: AppType.AppTypeContainer,
specType: AppSpecType.OCI_IMAGE,
name,
image: 'docker.io/library/nginx:stable-alpine',
ports,
cpuLimit: '',
memoryLimit: '',
variables: [],
volumes: [],
},
});

const translations = i18next.createInstance();
const schema = Yup.object({ applications: validApplicationsSchema(translations.t) });

beforeAll(async () => {
await translations.init({ lng: 'en', resources: { en: { translation: {} } } });
});

describe('container host port validation', () => {
it.each(['hostPort', 'targetPort'] as const)(
'preserves duplicate and invalid port errors when a mapping has an invalid %s',
async (invalidField) => {
const mappings = [{ hostPort: '8080', targetPort: '80' }];
if (invalidField === 'targetPort') {
mappings[0].targetPort = '70000';
} else {
mappings.push({ hostPort: '70000', targetPort: '80' });
}
const error = await schema
.validate(
{
applications: [app('port-test-a', mappings), app('port-test-b', [{ hostPort: '8080', targetPort: '81' }])],
},
{ abortEarly: false },
)
.catch((e: unknown) => e);
expect(error).toBeInstanceOf(Yup.ValidationError);
const errors = yupToFormErrors(error as Yup.ValidationError);
expect(getIn(errors, 'applications[0].app.ports')).toBe(
'Port must be between 1 and 65535 The following host ports are used in more than one application: 8080',
);
},
);

it('reports invalid mappings at the combined field without a duplicate', async () => {
const error = await schema
.validate({ applications: [app('port-test-a', [{ hostPort: '', targetPort: '70000' }])] }, { abortEarly: false })
.catch((e: unknown) => e);
expect(error).toBeInstanceOf(Yup.ValidationError);
expect(getIn(yupToFormErrors(error as Yup.ValidationError), 'applications[0].app.ports')).toBe(
'Host port is required Port must be between 1 and 65535',
);
});

it.each(['80', '81'])('rejects host port reuse across applications with target port %s', async (targetPort) => {
const applications = [
app('port-test-a', [{ hostPort: '8080', targetPort: '80' }]),
app('port-test-b', [{ hostPort: '8080', targetPort }]),
];

const error = await schema.validate({ applications }, { abortEarly: false }).catch((e: unknown) => e);
expect(error).toBeInstanceOf(Yup.ValidationError);
expect((error as Yup.ValidationError).inner.map(({ path }) => path)).toEqual([
'applications[0].app.ports',
'applications[1].app.ports',
]);
expect((error as Yup.ValidationError).errors).toContain(
'The following host ports are used in more than one application: 8080',
);
});

it('lists every conflicting host port once at the combined ports field', async () => {
const error = await schema
.validate(
{
applications: [
app('port-test-a', [
{ hostPort: '8080', targetPort: '80' },
{ hostPort: '9090', targetPort: '90' },
{ hostPort: '8080', targetPort: '81' },
{ hostPort: '7070', targetPort: '70' },
]),
app('port-test-b', [{ hostPort: '9090', targetPort: '91' }]),
],
},
{ abortEarly: false },
)
.catch((e: unknown) => e);
expect(error).toBeInstanceOf(Yup.ValidationError);
expect((error as Yup.ValidationError).inner).toEqual([
expect.objectContaining({
path: 'applications[0].app.ports',
message: 'The following host ports are used in more than one application: 8080, 9090',
}),
expect.objectContaining({
path: 'applications[1].app.ports',
message: 'The following host ports are used in more than one application: 9090',
}),
]);
});

it('rejects host port reuse within an application', async () => {
await expect(
schema.validate({
applications: [
app('port-test-a', [
{ hostPort: '8080', targetPort: '80' },
{ hostPort: '8080', targetPort: '81' },
]),
],
}),
).rejects.toBeInstanceOf(Yup.ValidationError);
});

it('allows applications to use the same container port on different host ports', async () => {
const value = {
applications: [
app('port-test-a', [{ hostPort: '8080', targetPort: '80' }]),
app('port-test-b', [{ hostPort: '8081', targetPort: '80' }]),
],
};
await expect(schema.validate(value)).resolves.toEqual(value);
});

it('allows removing a conflicting mapping', async () => {
await expect(
schema.isValid({
applications: [app('port-test-a', [{ hostPort: '8080', targetPort: '80' }]), app('port-test-b', [])],
}),
).resolves.toBe(true);
});

it('detects an occupied host port in the port editor regardless of target port', () => {
expect(isDuplicatePortMapping('8080', '81', [{ hostPort: '8080', targetPort: '80' }])).toBe(true);
});
});
45 changes: 43 additions & 2 deletions libs/ui-components/src/components/form/validations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,7 @@ export const isDuplicatePortMapping = (
if (!hostPort || !targetPort) {
return false;
}
return existingPorts.some((port) => port.hostPort === hostPort && port.targetPort === targetPort);
return existingPorts.some((port) => port.hostPort === hostPort);
};

export const isValidPortMapping = (
Expand Down Expand Up @@ -913,7 +913,6 @@ const manualContainerAppSchema = (t: TFunction) =>
appType: Yup.string().oneOf([AppType.AppTypeContainer]).required(t('Application type is required')),
name: validApplicationAndVolumeName(t),
image: ociImageSchema(t).required(t('Image is required.')),
ports: containerAppPortMappingSchema(t),
cpuLimit: Yup.string().test(
'valid-cpu-format',
t('CPU limit is invalid. Use a positive number of cores (e.g. 0.5 or 2).'),
Expand Down Expand Up @@ -1149,6 +1148,48 @@ export const validApplicationsSchema = (t: TFunction) => {
});
}),
)
.test('valid-container-ports', (appsValue, testContext) => {
const entries = (appsValue || []) as ApplicationEntry[];
const hostPorts = entries.flatMap((entry) =>
entry.type === 'manual' && entry.app.appType === AppType.AppTypeContainer && 'ports' in entry.app
? (entry.app.ports || []).map((port) => port.hostPort).filter(isValidPortNumber)
: [],
);
const counts = countBy(hostPorts);
const errors = entries.flatMap((entry, appIndex) => {
if (entry.type !== 'manual' || entry.app.appType !== AppType.AppTypeContainer || !('ports' in entry.app)) {
return [];
}
const ports = entry.app.ports || [];
// Keep mapping and duplicate errors at one path so Formik preserves both in the combined field.
const messages: string[] = [];
try {
containerAppPortMappingSchema(t).validateSync(ports, { abortEarly: false });
} catch (error) {
if (!(error instanceof Yup.ValidationError)) {
throw error;
}
messages.push(...error.errors);
}
const duplicatePorts = [...new Set(ports.map((port) => port.hostPort).filter((port) => counts[port] > 1))];
if (duplicatePorts.length > 0) {
messages.push(
t('The following host ports are used in more than one application: {{ports}}', {
ports: duplicatePorts.join(', '),
}),
);
}
return messages.length > 0
? [
testContext.createError({
message: [...new Set(messages)].join(' '),
path: `${testContext.path}[${appIndex}].app.ports`,
}),
]
: [];
});
return errors.length ? new Yup.ValidationError(errors) : true;
})
.test('unique-app-ids', (appsValue, testContext) => {
if (!appsValue?.length) {
return true;
Expand Down
Loading