From 5a874df91512a903103c27772250df6adebdb9d2 Mon Sep 17 00:00:00 2001 From: Thomas Heartman Date: Thu, 26 Sep 2024 13:52:51 +0200 Subject: [PATCH] fix: trim role names before validation (#8277) This trims role names before validation and subsequent validation. This fixes a bug where you could have names that were empty or that were duplicates of other names, but with leading or trailing spaces. (They display the same in the UI). This does not modify how we handle descriptions in the API. While the UI form requires you to enter a description, the API does not. As such, we can't make that required now without it being a breaking change. --- src/lib/schema/role-schema.ts | 2 +- src/lib/services/access-service.test.ts | 27 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/lib/schema/role-schema.ts b/src/lib/schema/role-schema.ts index 4946efc90631..572e6cac93b5 100644 --- a/src/lib/schema/role-schema.ts +++ b/src/lib/schema/role-schema.ts @@ -13,7 +13,7 @@ export const permissionRoleSchema = joi export const roleSchema = joi .object() .keys({ - name: joi.string().required(), + name: joi.string().trim().required(), description: joi.string().optional().allow('').allow(null).default(''), permissions: joi .array() diff --git a/src/lib/services/access-service.test.ts b/src/lib/services/access-service.test.ts index ac170a008695..5bfa3f229d3b 100644 --- a/src/lib/services/access-service.test.ts +++ b/src/lib/services/access-service.test.ts @@ -97,6 +97,33 @@ test('should accept empty permissions', async () => { }); }); +test('should not accept empty names', async () => { + const { accessService } = getSetup(); + const withWhitespaceName: IRoleValidation = { + name: ' ', + description: 'description', + permissions: [], + }; + + await expect( + accessService.validateRole(withWhitespaceName), + ).rejects.toThrow('"name" is not allowed to be empty'); +}); + +test('should trim leading and trailing whitespace from names', async () => { + const { accessService } = getSetup(); + const withUntrimmedName: IRoleValidation = { + name: ' untrimmed ', + description: 'description', + permissions: [], + }; + expect(await accessService.validateRole(withUntrimmedName)).toEqual({ + name: 'untrimmed', + description: 'description', + permissions: [], + }); +}); + test('should complete environment field of permissions when not present', async () => { const { accessService } = getSetup(); const withoutEnvironmentInPermissions: IRoleValidation = {