diff --git a/src/routes/devices/deviceValidator.test.ts b/src/routes/devices/deviceValidator.test.ts new file mode 100644 index 000000000..f7361b908 --- /dev/null +++ b/src/routes/devices/deviceValidator.test.ts @@ -0,0 +1,60 @@ +/********************************************************************* + * Copyright (c) Intel Corporation 2026 + * SPDX-License-Identifier: Apache-2.0 + **********************************************************************/ + +import { validationResult } from 'express-validator' +import { describe, expect, it } from '@jest/globals' +import { validator } from './deviceValidator.js' + +async function getValidationErrors(body: any): Promise { + const req: any = { body, query: {}, params: {} } + const chains = validator() + + for (const chain of chains) { + await chain.run(req) + } + + return validationResult(req).array() +} + +describe('device validator dnsSuffix checks', () => { + it('accepts a valid dnsSuffix', async () => { + const errors = await getValidationErrors({ + guid: '123e4567-e89b-12d3-a456-426614174000', + dnsSuffix: 'os.suffix.com' + }) + + expect(errors).toHaveLength(0) + }) + + it('accepts null dnsSuffix', async () => { + const errors = await getValidationErrors({ + guid: '123e4567-e89b-12d3-a456-426614174000', + dnsSuffix: null + }) + + expect(errors).toHaveLength(0) + }) + + it("accepts empty string dnsSuffix", async () => { + const errors = await getValidationErrors({ + guid: '123e4567-e89b-12d3-a456-426614174000', + dnsSuffix: '' + }) + + expect(errors).toHaveLength(0) + }) + + it('rejects dnsSuffix containing query string characters', async () => { + const errors = await getValidationErrors({ + guid: '123e4567-e89b-12d3-a456-426614174000', + dnsSuffix: 'None?injected_query_string=123' + }) + + expect(errors.some((error) => error.path === 'dnsSuffix')).toBeTruthy() + const dnsSuffixError = errors.find((error) => error.path === 'dnsSuffix') + expect(dnsSuffixError).toBeDefined() + expect(dnsSuffixError?.msg).toContain('dnsSuffix') + }) +}) diff --git a/src/routes/devices/deviceValidator.ts b/src/routes/devices/deviceValidator.ts index 8050442ff..34facb795 100644 --- a/src/routes/devices/deviceValidator.ts +++ b/src/routes/devices/deviceValidator.ts @@ -13,6 +13,16 @@ export const validator = (): any => [ .isString() .isLength({ max: 255 }) .withMessage('Hostname must be less than 256 characters'), + check('dnsSuffix') + .optional({ nullable: true }) + .isString() + .bail() + .isLength({ max: 255 }) + .withMessage('dnsSuffix must be less than 256 characters') + .bail() + .if((value) => value !== '') + .isFQDN({ require_tld: false, allow_trailing_dot: true }) + .withMessage('dnsSuffix must be a valid DNS suffix'), check('mpsusername').optional({ nullable: true }).isString(), check('connect').optional({ nullable: true }).isISO8601().toDate(), check('disconnect').optional({ nullable: true }).isISO8601().toDate(),