Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions src/shared/access-control/access-control.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { Role } from 'src/core/auth/auth.constants';
import { AccessControlService } from './access-control.service';
import { RoleAccessProvider } from './role-access.interface';

describe('AccessControlService', () => {
let service: AccessControlService;

beforeEach(() => {
service = new AccessControlService();
});

it('skips engagement approver filters when payment admin role is also present', async () => {
const paymentAdminApplyFilter = jest
.fn()
.mockImplementation((_userId, req: Record<string, unknown>) =>
Promise.resolve({
...req,
admin: true,
}),
);
const engagementApproverApplyFilter = jest
.fn()
.mockImplementation((_userId, req: Record<string, unknown>) =>
Promise.resolve({
...req,
category: 'ENGAGEMENT_PAYMENT',
}),
);
const paymentAdminProvider: RoleAccessProvider<Record<string, unknown>> = {
roleName: Role.PaymentAdmin,
applyFilter: paymentAdminApplyFilter,
};
const engagementApproverProvider: RoleAccessProvider<
Record<string, unknown>
> = {
roleName: Role.EngagementPaymentApprover,
applyFilter: engagementApproverApplyFilter,
};

service.register(paymentAdminProvider);
service.register(engagementApproverProvider);

const result = await service.applyFilters<Record<string, unknown>>(
'88770025',
[Role.PaymentAdmin, Role.EngagementPaymentApprover],
{ type: 'PAYMENT' },
);

expect(result).toEqual({
admin: true,
type: 'PAYMENT',
});
expect(paymentAdminApplyFilter).toHaveBeenCalledTimes(1);
expect(engagementApproverApplyFilter).not.toHaveBeenCalled();
});

it('applies engagement approver filters when payment admin role is absent', async () => {
const engagementApproverApplyFilter = jest
.fn()
.mockImplementation((_userId, req: Record<string, unknown>) =>
Promise.resolve({
...req,
category: 'ENGAGEMENT_PAYMENT',
}),
);
const engagementApproverProvider: RoleAccessProvider<
Record<string, unknown>
> = {
roleName: Role.EngagementPaymentApprover,
applyFilter: engagementApproverApplyFilter,
};

service.register(engagementApproverProvider);

const result = await service.applyFilters<Record<string, unknown>>(
'88770025',
[Role.EngagementPaymentApprover],
{ type: 'PAYMENT' },
);

expect(result).toEqual({
category: 'ENGAGEMENT_PAYMENT',
type: 'PAYMENT',
});
expect(engagementApproverApplyFilter).toHaveBeenCalledTimes(1);
});

it('skips engagement approver resource checks when payment admin role is also present', async () => {
const paymentAdminVerifyAccess = jest.fn().mockResolvedValue(undefined);
const engagementApproverVerifyAccess = jest
.fn()
.mockRejectedValue(new Error('should not be called'));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[💡 readability]
Using mockRejectedValue with an error message like 'should not be called' is a bit misleading. Consider using a more descriptive message or a different approach to ensure clarity in test failures.

const paymentAdminProvider: RoleAccessProvider = {
roleName: Role.PaymentAdmin,
verifyAccessToResource: paymentAdminVerifyAccess,
};
const engagementApproverProvider: RoleAccessProvider = {
roleName: Role.EngagementPaymentApprover,
verifyAccessToResource: engagementApproverVerifyAccess,
};

service.register(paymentAdminProvider);
service.register(engagementApproverProvider);

await expect(
service.verifyAccess('winning-id', '88770025', [
Role.PaymentAdmin,
Role.EngagementPaymentApprover,
]),
).resolves.toBeUndefined();

expect(paymentAdminVerifyAccess).toHaveBeenCalledTimes(1);
expect(engagementApproverVerifyAccess).not.toHaveBeenCalled();
});
});
39 changes: 37 additions & 2 deletions src/shared/access-control/access-control.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { Role } from 'src/core/auth/auth.constants';
import { RoleAccessProvider } from './role-access.interface';

@Injectable()
Expand All @@ -9,14 +10,39 @@ export class AccessControlService {
this.providers.set(provider.roleName.trim().toLowerCase(), provider);
}

private normalizeRoles(roles: string[] = []): Set<string> {
return new Set(
(roles || []).map((role) => role?.trim().toLowerCase()).filter(Boolean),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[⚠️ maintainability]
The use of role?.trim().toLowerCase() is repeated in multiple places. Consider extracting this logic into a helper function to improve maintainability and reduce duplication.

);
}

private shouldSkipProvider(
providerRole: string,
normalizedRoles: Set<string>,
): boolean {
return (
providerRole === Role.EngagementPaymentApprover.trim().toLowerCase() &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[❗❗ correctness]
Ensure that Role.EngagementPaymentApprover and Role.PaymentAdmin are always defined and not null or undefined to avoid potential runtime errors.

normalizedRoles.has(Role.PaymentAdmin.trim().toLowerCase())
);
}

async applyFilters<T>(
userId: string,
roles: string[] = [],
req: any,
): Promise<T> {
let out = { ...req };
const normalizedRoles = this.normalizeRoles(roles);
for (const r of roles || []) {
const p = this.providers.get(r?.trim().toLowerCase());
const normalizedRole = r?.trim().toLowerCase();
if (
!normalizedRole ||
this.shouldSkipProvider(normalizedRole, normalizedRoles)
) {
continue;
}

const p = this.providers.get(normalizedRole);
if (p?.applyFilter) {
out = await p.applyFilter(userId, out);
}
Expand All @@ -25,8 +51,17 @@ export class AccessControlService {
}

async verifyAccess(resourceId: string, userId: string, roles: string[] = []) {
const normalizedRoles = this.normalizeRoles(roles);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[⚠️ correctness]
The normalizeRoles function is called but its implementation is not shown in the diff. Ensure that it correctly normalizes roles to prevent potential mismatches or errors in access verification.

for (const r of roles || []) {
const p = this.providers.get(r?.trim().toLowerCase());
const normalizedRole = r?.trim().toLowerCase();
if (
!normalizedRole ||
this.shouldSkipProvider(normalizedRole, normalizedRoles)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[❗❗ correctness]
The shouldSkipProvider function is used to determine if a provider should be skipped. Ensure that this function is well-tested to avoid inadvertently skipping necessary providers, which could lead to incorrect access control.

) {
continue;
}

const p = this.providers.get(normalizedRole);
if (p?.verifyAccessToResource) {
await p.verifyAccessToResource(resourceId, userId);
}
Expand Down
Loading