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

Defining endpoint security through JDL #23740

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
157 changes: 157 additions & 0 deletions generators/base-application/support/prepare-entity.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { formatDateForChangelog } from '../../base/support/index.js';
import { prepareEntityPrimaryKeyForTemplates, entityDefaultConfig } from './prepare-entity.js';
import BaseGenerator from '../../base/index.js';
import { getConfigWithDefaults } from '../../../jdl/jhipster/index.js';
import { JDLSecurityType, PrivilegeActionType, RoleActionType } from '../../../jdl/models/jdl-security-type.js';
import { prepareEntity } from './index.js';

describe('generator - base-application - support - prepareEntity', () => {
const defaultGenerator = { jhipsterConfig: getConfigWithDefaults() };
Expand Down Expand Up @@ -301,4 +303,159 @@ describe('generator - base-application - support - prepareEntity', () => {
});
});
});

describe('prepare entity security', () => {
describe('with no security', () => {
it('prepareEntity should not add security', () => {
const entity = {
...entityDefaultConfig,
name: 'Entity',
changelogDate: formatDateForChangelog(new Date()),
fields: [{ fieldName: 'id', fieldType: 'CustomType', path: ['id'], relationshipsPath: [] }],
};
const result = prepareEntity(entity, defaultGenerator, 'testApp');
expect(result.security).to.be.undefined;
expect(result.hasSecurity).to.equal(false);
expect(result.hasRolesSecurity).to.equal(false);
});

it('prepareEntity should add role based security', () => {
const entity = {
...entityDefaultConfig,
name: 'Entity',
changelogDate: formatDateForChangelog(new Date()),
fields: [{ fieldName: 'id', fieldType: 'CustomType', path: ['id'], relationshipsPath: [] }],
secure: {
securityType: JDLSecurityType.Roles,
roles: [
{ role: 'ROLE_ALLOWED', actionList: [RoleActionType.Post, RoleActionType.Put, RoleActionType.Get] },
{ role: 'ROLE_FORBIDDEN', actionList: [RoleActionType.Get] },
],
},
};
const result = prepareEntity(entity, defaultGenerator, 'testApp');
expect(result.security).to.exist;
expect(result.hasSecurity).to.equal(true);
expect(result.hasRolesSecurity).to.equal(true);
expect(result.security.securityType).to.equal(JDLSecurityType.Roles);
expect(result.security.roles).to.deep.equal({
get: '"ROLE_ALLOWED", "ROLE_FORBIDDEN"',
put: '"ROLE_ALLOWED"',
post: '"ROLE_ALLOWED"',
delete: '"DUMMY_ROLE_NO_ACCESS"',
});
expect(result.security.allowedRoles).to.exist;
expect(result.security.allowedRoles).to.deep.equal({
delete: [],
get: ['ROLE_ALLOWED', 'ROLE_FORBIDDEN'],
post: ['ROLE_ALLOWED'],
put: ['ROLE_ALLOWED'],
});
expect(result.security.forbiddenRoles).to.exist;
expect(result.security.forbiddenRoles).to.deep.equal({
delete: ['ROLE_ALLOWED', 'ROLE_FORBIDDEN'],
get: [],
post: ['ROLE_FORBIDDEN'],
put: ['ROLE_FORBIDDEN'],
});
});

it('prepareEntity should add privilege based security', () => {
const entity = {
...entityDefaultConfig,
name: 'Entity',
changelogDate: formatDateForChangelog(new Date()),
fields: [{ fieldName: 'id', fieldType: 'CustomType', path: ['id'], relationshipsPath: [] }],
secure: {
securityType: JDLSecurityType.Privileges,
privileges: [{ action: PrivilegeActionType.Read, privList: ['Admin'] }],
},
};
const result = prepareEntity(entity, defaultGenerator, 'testApp');
expect(result.security).to.exist;
expect(result.hasSecurity).to.equal(true);
expect(result.hasPrivilegeSecurity).to.equal(true);
expect(result.security.securityType).to.equal(JDLSecurityType.Privileges);
expect(result.security.privileges).to.deep.equal({ read: '"ADMIN"' });
});

it('prepareEntity should add organizational security', () => {
const entity = {
...entityDefaultConfig,
name: 'Entity',
changelogDate: formatDateForChangelog(new Date()),
fields: [{ fieldName: 'id', fieldType: 'CustomType', path: ['id'], relationshipsPath: [] }],
secure: {
securityType: JDLSecurityType.OrganizationalSecurity,
organizationalSecurity: { resource: 'TestResource' },
},
};
const result = prepareEntity(entity, defaultGenerator, 'testApp');
expect(result.security).to.exist;
expect(result.hasSecurity).to.equal(true);
expect(result.hasOrganizationalSecurity).to.equal(true);
expect(result.security.securityType).to.equal(JDLSecurityType.OrganizationalSecurity);
expect(result.security.organizationalSecurity).to.deep.equal({ resource: 'TestResource' });
});

it('prepareEntity should add parent based security', () => {
const entity = {
...entityDefaultConfig,
name: 'Entity',
changelogDate: formatDateForChangelog(new Date()),
fields: [{ fieldName: 'id', fieldType: 'CustomType', path: ['id'], relationshipsPath: [] }],
secure: {
securityType: JDLSecurityType.ParentPrivileges,
parentPrivileges: { parent: 'TestParent', field: 'TestField' },
},
};
const result = prepareEntity(entity, defaultGenerator, 'testApp');
expect(result.security).to.exist;
expect(result.hasSecurity).to.equal(true);
expect(result.hasParentSecurity).to.equal(true);
expect(result.security.securityType).to.equal(JDLSecurityType.ParentPrivileges);
expect(result.security.parentPrivileges).to.deep.equal({
field: 'TestField',
parent: 'TestParent',
parentEntityApiUrl: 'test-parents',
parentEntityClass: 'TestParent',
parentEntityInstance: 'testParent',
parentEntityName: 'TestParent',
parentFieldName: 'TestField',
parentFieldNameUpper: 'TestField',
parentInstanceName: 'testParent',
});
});

it('prepareEntity should add relational based security', () => {
const entity = {
...entityDefaultConfig,
name: 'Entity',
changelogDate: formatDateForChangelog(new Date()),
fields: [{ fieldName: 'id', fieldType: 'CustomType', path: ['id'], relationshipsPath: [] }],
secure: {
securityType: JDLSecurityType.RelPrivileges,
relPrivileges: {
fromEntity: 'FromEntity',
fromField: 'FromField',
toEntity: 'ToEntity',
toField: 'toField',
},
comment: 'comment',
},
};
const result = prepareEntity(entity, defaultGenerator, 'testApp');
expect(result.security).to.exist;
expect(result.hasSecurity).to.equal(true);
expect(result.hasRelationSecurity).to.equal(true);
expect(result.security.securityType).to.equal(JDLSecurityType.RelPrivileges);
expect(result.security.relPrivileges).to.deep.equal({
fromEntity: 'FromEntity',
fromField: 'FromField',
toEntity: 'ToEntity',
toField: 'toField',
});
});
});
});
});
190 changes: 190 additions & 0 deletions generators/base-application/support/prepare-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import { fieldIsEnum } from './field-utils.js';

import { Entity } from '../types/index.js';
import type CoreGenerator from '../../base-core/generator.js';
import { JDLSecurityType } from '../../../jdl/models/jdl-security-type.js';

const { sortedUniq, intersection } = _;

Expand Down Expand Up @@ -268,10 +269,199 @@ export default function prepareEntity(entityWithConfig, generator, application)
return Object.fromEntries(fieldEntries);
};
_derivedProperties(entityWithConfig);
defineEntitySecurity(entityWithConfig);

return entityWithConfig;
}

/**
* Defines role based security for an entity.
*
* @param {any} entityWithConfig - The entity with security configuration.
*/
function defineRoleBasedSecurity(entityWithConfig: any) {
entityWithConfig.hasSecurity = true;
entityWithConfig.hasRolesSecurity = true;
const allRoles: any[] = [];
const allowedRolesAsString: any = { get: [], put: [], post: [], delete: [] };
const allowedRoles: any = { get: [], put: [], post: [], delete: [] };
for (let i = 0; i < entityWithConfig.secure.roles.length; i++) {
const role = `"${entityWithConfig.secure.roles[i].role}"`;
allRoles.push(entityWithConfig.secure.roles[i].role);
for (let j = 0; j < entityWithConfig.secure.roles[i].actionList.length; j++) {
const action = _.lowerCase(entityWithConfig.secure.roles[i].actionList[j]);
if (!allowedRolesAsString[action].includes(role)) {
allowedRolesAsString[action].push(role);
allowedRoles[action].push(entityWithConfig.secure.roles[i].role);
}
}
}
const forbiddenRoles: any = {};
forbiddenRoles.get = allRoles.filter(item => allowedRoles.get.indexOf(item) < 0);
forbiddenRoles.put = allRoles.filter(item => allowedRoles.put.indexOf(item) < 0);
forbiddenRoles.post = allRoles.filter(item => allowedRoles.post.indexOf(item) < 0);
forbiddenRoles.delete = allRoles.filter(item => allowedRoles.delete.indexOf(item) < 0);
entityWithConfig.security.roles = {
get: allowedRolesAsString.get.length > 0 ? allowedRolesAsString.get.join(', ') : '"DUMMY_ROLE_NO_ACCESS"',
put: allowedRolesAsString.put.length > 0 ? allowedRolesAsString.put.join(', ') : '"DUMMY_ROLE_NO_ACCESS"',
post: allowedRolesAsString.post.length > 0 ? allowedRolesAsString.post.join(', ') : '"DUMMY_ROLE_NO_ACCESS"',
delete: allowedRolesAsString.delete.length > 0 ? allowedRolesAsString.delete.join(', ') : '"DUMMY_ROLE_NO_ACCESS"',
};
entityWithConfig.security.allowedRoles = {
get: [...allowedRoles.get],
put: [...allowedRoles.put],
post: [...allowedRoles.post],
delete: [...allowedRoles.delete],
};
entityWithConfig.security.forbiddenRoles = {
get: [...forbiddenRoles.get],
put: [...forbiddenRoles.put],
post: [...forbiddenRoles.post],
delete: [...forbiddenRoles.delete],
};
}

/**
* Defines privilege-based security for an entity with configuration.
*
* @param {Object} entityWithConfig - The entity with configuration.
* @return {void}
*/
function definePrivilegeBasedSecurity(entityWithConfig: any) {
entityWithConfig.hasSecurity = true;
entityWithConfig.hasPrivilegeSecurity = true;
const privileges = {};
for (let i = 0; i < entityWithConfig.secure.privileges.length; i++) {
const action = _.lowerCase(entityWithConfig.secure.privileges[i].action);
if (entityWithConfig.secure.privileges[i].privList.length > 0) {
privileges[action] = entityWithConfig.secure.privileges[i].privList
.map(x => `"${x}"`)
.join(', ')
.toUpperCase();
}
}
entityWithConfig.security.privileges = privileges;
}

/**
* Sets the organizational security for the given entity with configuration.
*
* @param {any} entityWithConfig - The entity object with configuration.
* @return {void}
*/
function defineOrganizationalSecurity(entityWithConfig: any) {
entityWithConfig.hasSecurity = true;
entityWithConfig.hasOrganizationalSecurity = true;
entityWithConfig.security.organizationalSecurity = entityWithConfig.secure.organizationalSecurity;
}

/**
* Defines parent based security for the given entity.
*
* @param {any} entityWithConfig - The entity object with configuration.
*/
function defineParentBasedSecurity(entityWithConfig: any) {
entityWithConfig.hasSecurity = true;
entityWithConfig.hasParentSecurity = true;
const parentPrivileges = entityWithConfig.secure.parentPrivileges;
entityWithConfig.security.parentPrivileges = parentPrivileges;
entityWithConfig.security.roles = {
get: 'ROLE_ADMIN',
put: 'ROLE_ADMIN',
post: 'ROLE_ADMIN',
delete: 'ROLE_ADMIN',
};
entityWithConfig.security.parentPrivileges.parentEntityClass = _.upperFirst(parentPrivileges.parent);
entityWithConfig.security.parentPrivileges.parentEntityName = parentPrivileges.parent;
entityWithConfig.security.parentPrivileges.parentEntityApiUrl = _.kebabCase(_.lowerFirst(pluralize(parentPrivileges.parent)));
entityWithConfig.security.parentPrivileges.parentEntityInstance = _.lowerFirst(parentPrivileges.parent);
entityWithConfig.security.parentPrivileges.parentInstanceName = _.lowerFirst(parentPrivileges.parent);
entityWithConfig.security.parentPrivileges.parentFieldNameUpper = _.upperFirst(parentPrivileges.field);
entityWithConfig.security.parentPrivileges.parentFieldName = parentPrivileges.field;
}

/**
* Sets up relational security for the given entity with configuration.
*
* @param {any} entityWithConfig - The entity with its security configuration.
* @return {void}
*/
function defineRelationalSecurity(entityWithConfig: any) {
entityWithConfig.hasSecurity = true;
entityWithConfig.hasRelationSecurity = true;
entityWithConfig.security.relPrivileges = entityWithConfig.secure.relPrivileges;
}

/**
* Retrieves the security type associated with the given entity configuration.
* @param {any} entityWithConfig - The entity with its configuration.
* @return {JDLSecurityType} - The security type of the entity. Returns JDLSecurityType.None if no security type is defined.
*/
function getSecurityType(entityWithConfig: any): JDLSecurityType {
return entityWithConfig.secure?.securityType || JDLSecurityType.None;
}

/**
* Checks if the given security type is of "None" type.
*
* @param {JDLSecurityType} securityType - The security type to be checked.
* @return {boolean} - True if the security type is "None", false otherwise.
*/
function isNoneSecurityType(securityType: JDLSecurityType): boolean {
return securityType === JDLSecurityType.None;
}

/**
* Assigns a security type to an entity object and initialize security object on the entity.
*
* @param {any} entityWithConfig - The entity object with configuration.
* @param {JDLSecurityType} securityType - The security type to assign.
* @return {void}
*/
function assignEntitySecurity(entityWithConfig: any, securityType: JDLSecurityType): void {
entityWithConfig.security = {
securityType,
};
}

/**
* Defines the security for the given entity. Security is defined through 'secure' property in the entity configuration.
*
* @param {Object} entityWithConfig - The entity with its configuration.
* @throws {Error} If the entity has an unknown security type.
*/
function defineEntitySecurity(entityWithConfig: any): void {
const securityType = getSecurityType(entityWithConfig);

if (isNoneSecurityType(securityType)) {
entityWithConfig.hasSecurity = false;
entityWithConfig.hasRolesSecurity = false;
return;
}

assignEntitySecurity(entityWithConfig, securityType);

switch (securityType) {
case JDLSecurityType.Roles:
defineRoleBasedSecurity(entityWithConfig);
break;
case JDLSecurityType.Privileges:
definePrivilegeBasedSecurity(entityWithConfig);
break;
case JDLSecurityType.OrganizationalSecurity:
defineOrganizationalSecurity(entityWithConfig);
break;
case JDLSecurityType.ParentPrivileges:
defineParentBasedSecurity(entityWithConfig);
break;
case JDLSecurityType.RelPrivileges:
defineRelationalSecurity(entityWithConfig);
break;
default:
throw new Error(`Entity ${entityWithConfig.name()} has defined unknown security type: ${securityType}`);
}
}

export function derivedPrimaryKeyProperties(primaryKey) {
_.defaults(primaryKey, {
hasUUID: primaryKey.fields && primaryKey.fields.some(field => field.fieldType === UUID),
Expand Down