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

BE: Policy int - Rough draft #1656

Closed
wants to merge 10 commits into from
47 changes: 47 additions & 0 deletions vehicles/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion vehicles/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@
"swagger-ui-express": "^5.0.1",
"typeorm": "^0.3.20",
"uuid": "^9.0.1",
"winston": "^3.14.2"
"winston": "^3.14.2",
"onroute-policy-engine": "0.4.2"
},
"devDependencies": {
"@golevelup/ts-jest": "^0.5.4",
Expand Down
13 changes: 13 additions & 0 deletions vehicles/src/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { PaymentService } from './modules/permit-application-payment/payment/pay
import { LogAsyncMethodExecution } from './common/decorator/log-async-method-execution.decorator';
import { FeatureFlagsService } from './modules/feature-flags/feature-flags.service';
import { ApplicationService } from './modules/permit-application-payment/application/application.service';
import { HttpService } from '@nestjs/axios';
import { getActivePolicyDefinitions } from './common/helper/policy-engine.helper';

@Injectable()
export class AppService {
Expand All @@ -27,6 +29,7 @@ export class AppService {
private paymentService: PaymentService,
private featureFlagsService: FeatureFlagsService,
private applicationService: ApplicationService,
private readonly httpService: HttpService,
) {}

getHello(): string {
Expand Down Expand Up @@ -128,6 +131,16 @@ export class AppService {
createCacheMap(permitApprovalSource, 'id', 'code'),
);

const policyConfigs = await getActivePolicyDefinitions(
this.httpService,
this.cacheManager,
);
await addToCache(
this.cacheManager,
CacheKey.POLICY_CONFIGURATIONS,
createCacheMap(policyConfigs, '??', 'policyJson'),
);

const endDateTime = new Date();
const processingTime = endDateTime.getTime() - startDateTime.getTime();
this.logger.log(
Expand Down
2 changes: 2 additions & 0 deletions vehicles/src/common/enum/cache-key.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,6 @@ export enum CacheKey {
FEATURE_FLAG_TYPE = 'FEATURE_FLAG_TYPE',
PERMIT_APPLICATION_ORIGIN = 'PERMIT_APPLICATION_ORIGIN',
PERMIT_APPROVAL_SOURCE = 'PERMIT_APPROVAL_SOURCE',
POLICY_CONFIGURATIONS = 'POLICY_CONFIGURATIONS',
ORBC_SERVICE_ACCOUNT_ACCESS_TOKEN = 'ORBC_SERVICE_ACCOUNT_ACCESS_TOKEN',
}
1 change: 1 addition & 0 deletions vehicles/src/common/enum/gov-common-services.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export enum GovCommonServices {
COMMON_HOSTED_EMAIL_SERVICE = 'CHES',
COMMON_DOCUMENT_GENERATION_SERVICE = 'CDOGS',
CREDIT_ACCOUNT_SERVICE = 'CREDIT_ACCOUNT',
ORBC_SERVICE_ACCOUNT = 'SA',
}
7 changes: 6 additions & 1 deletion vehicles/src/common/helper/gov-common-services.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,12 @@ function getTokenCredentials(govCommonServices: GovCommonServices): {
username = process.env.CFS_CREDIT_ACCOUNT_CLIENT_ID;
password = process.env.CFS_CREDIT_ACCOUNT_CLIENT_SECRET;
break;

case GovCommonServices.ORBC_SERVICE_ACCOUNT:
tokenCacheKey = CacheKey.ORBC_SERVICE_ACCOUNT_ACCESS_TOKEN;
tokenUrl = process.env.ORBC_SERVICE_ACCOUNT_TOKEN_URL;
username = process.env.ORBC_SERVICE_ACCOUNT_CLIENT_ID;
password = process.env.ORBC_SERVICE_ACCOUNT_CLIENT_SECRET;
break;
default:
break;
}
Expand Down
45 changes: 45 additions & 0 deletions vehicles/src/common/helper/policy-engine.helper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { Permit } from 'src/modules/permit-application-payment/permit/entities/permit.entity';
import { PolicyApplication } from '../interface/policy-application.interface';
import { PermitData } from '../interface/permit.template.interface';
import { getAccessToken } from './gov-common-services.helper';
import { GovCommonServices } from '../enum/gov-common-services.enum';
import { HttpService } from '@nestjs/axios';
import { Cache } from 'cache-manager';
import { AxiosResponse } from 'axios';
import { ReadPolicyConfigDto } from '../../modules/policy/dto/response/read-policy-config.dto';
import { Policy, ValidationResults } from 'onroute-policy-engine';

export const convertToPolicyApplication = (
application: Permit,
Expand All @@ -10,3 +17,41 @@ export const convertToPolicyApplication = (
permitData: JSON.parse(application.permitData.permitData) as PermitData,
};
};

export const getActivePolicyDefinitions = async (
httpService: HttpService,
cacheManager: Cache,
) => {
const token = await getAccessToken(
GovCommonServices.ORBC_SERVICE_ACCOUNT,
httpService,
cacheManager,
);
const response = await httpService.axiosRef.get<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
AxiosResponse<Response, any>,
Request
>(process.env.ORBC_POLICY_URL + '/policy-configurations', {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
return (await response.data.json()) as ReadPolicyConfigDto[];
};

export const validateWithPolicyEngine = async (
permitApplication: unknown,
cacheManager: Cache,
): Promise<boolean> => {
const policyDefinitions: ReadPolicyConfigDto[] = await cacheManager.get(
'active-policy-definitions',
);
const policy = new Policy(policyDefinitions);
const validationResults: ValidationResults =
await policy.validate(permitApplication);

return validationResults.violations.length > 0;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { AutoMap } from '@automapper/classes';
import { ApiProperty } from '@nestjs/swagger';
import { PolicyDefinition } from 'onroute-policy-engine/dist/types';

export class ReadPolicyConfigDto {
/**
* Unique identifier for the policy configuration.
*/
@AutoMap()
@ApiProperty({
example: '1',
description: 'Unique identifier for the policy configuration.',
})
policyConfigId: number;

/**
* JSON data representing the policy configuration.
*/
@AutoMap()
@ApiProperty({
description: 'Policy configuration in JSON format.',
})
policy: PolicyDefinition;

/**
* Configuration effective date.
*/
@AutoMap()
@ApiProperty({
example: '2023-07-13T17:31:17.470Z',
description: 'Policy Configuration effective date.',
})
effectiveDate: string;

/**
* Indicates if the configuration is currently a draft version.
*/
@AutoMap()
@ApiProperty({
example: true,
description: 'Indicates if the configuration is currently a draft.',
})
isDraft: boolean;

/**
* Description of changes made in the configuration.
*/
@AutoMap()
@ApiProperty({
example: 'Initial release of policy configuration with updated rules',
description: 'Description of changes made in the configuration.',
})
changeDescription: string;
}
2 changes: 1 addition & 1 deletion vehicles/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"module": "commonjs",
"module": "CommonJS",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
Expand Down
Loading