diff --git a/libs/i18n/locales/en/translation.json b/libs/i18n/locales/en/translation.json index ffad0f80d..b39fe9a7e 100644 --- a/libs/i18n/locales/en/translation.json +++ b/libs/i18n/locales/en/translation.json @@ -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.", diff --git a/libs/ui-components/src/components/Device/EditDeviceWizard/steps/ApplicationContainerForm.tsx b/libs/ui-components/src/components/Device/EditDeviceWizard/steps/ApplicationContainerForm.tsx index 6c5bfd044..76bdbf371 100644 --- a/libs/ui-components/src/components/Device/EditDeviceWizard/steps/ApplicationContainerForm.tsx +++ b/libs/ui-components/src/components/Device/EditDeviceWizard/steps/ApplicationContainerForm.tsx @@ -5,6 +5,7 @@ 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'; @@ -12,7 +13,10 @@ import ApplicationImageForm from './ApplicationImageForm'; const ApplicationContainerForm = ({ index, isReadOnly }: { index: number; isReadOnly?: boolean }) => { const { t } = useTranslation(); const appFieldName = `applications[${index}].app`; - const [{ value: app }] = useField(`${appFieldName}`); + const [{ value: app }, appMeta] = useField(`${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]); @@ -33,6 +37,7 @@ const ApplicationContainerForm = ({ index, isReadOnly }: { index: number; isRead + {hasPortsError && } diff --git a/libs/ui-components/src/components/form/ApplicationPortMappingField.tsx b/libs/ui-components/src/components/form/ApplicationPortMappingField.tsx index 8f2ac0387..c09d7d800 100644 --- a/libs/ui-components/src/components/form/ApplicationPortMappingField.tsx +++ b/libs/ui-components/src/components/form/ApplicationPortMappingField.tsx @@ -33,6 +33,7 @@ type ApplicationPortMappingFieldProps = { targetPortAriaLabel: string; targetPortPlaceholder: string; withProtocol?: boolean; + errorId?: string; }; const normalizeProtocol = (protocol?: string) => (protocol || 'tcp').toLowerCase(); @@ -67,6 +68,7 @@ const ApplicationPortMappingField = ({ targetPortAriaLabel, targetPortPlaceholder, withProtocol, + errorId, }: ApplicationPortMappingFieldProps) => { const { t } = useTranslation(); @@ -287,6 +289,8 @@ const ApplicationPortMappingField = ({ { diff --git a/libs/ui-components/src/components/form/FieldHelperText.tsx b/libs/ui-components/src/components/form/FieldHelperText.tsx index 2b4ed2ff7..3e1ae7883 100644 --- a/libs/ui-components/src/components/form/FieldHelperText.tsx +++ b/libs/ui-components/src/components/form/FieldHelperText.tsx @@ -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; touchRequired?: boolean; error?: React.ReactNode; @@ -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) { @@ -42,7 +43,7 @@ const ErrorHelperText = ({ meta, error, touchRequired = true }: ErrorHelperTextP } return content ? ( - } screenReaderText={t('Validation error')}> + } screenReaderText={t('Validation error')}> {content} diff --git a/libs/ui-components/src/components/form/validations.test.ts b/libs/ui-components/src/components/form/validations.test.ts new file mode 100644 index 000000000..50804530f --- /dev/null +++ b/libs/ui-components/src/components/form/validations.test.ts @@ -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); + }); +}); diff --git a/libs/ui-components/src/components/form/validations.ts b/libs/ui-components/src/components/form/validations.ts index 797b0e4b6..7e068ebd6 100644 --- a/libs/ui-components/src/components/form/validations.ts +++ b/libs/ui-components/src/components/form/validations.ts @@ -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 = ( @@ -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).'), @@ -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;