-
Notifications
You must be signed in to change notification settings - Fork 1
Added data filter for box data isolation for testing session environment #608
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
Merged
MikhailDeriabin
merged 8 commits into
dev
from
feature/add-datafilter-to-testing-sessions-587
Jul 26, 2025
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
da8de40
Add box filter interceptor
PlayJeri b5d4e30
Add decorator to bypass the box id filter
PlayJeri ce5222b
Extend all DTOs with box_id if it's testing session to make data filt…
PlayJeri afaafac
Apply interceptor globally if its testing session
PlayJeri 05c0c96
apply no box filter decorator to dev only and "login" endpoints
PlayJeri f8af141
add `@NoBoxIdFilter()` for /box GET endpoint
MikhailDeriabin c87e5df
JSDocs added
PlayJeri 051306e
Add tests for BoxIdFilterInterceptor
PlayJeri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| import { BoxIdFilterInterceptor } from '../../../../src/box/auth/BoxIdFilter.interceptor'; | ||
| import { CallHandler } from '@nestjs/common'; | ||
| import { lastValueFrom, of } from 'rxjs'; | ||
| import RequestBuilder from '../../test_utils/data/RequestBuilder'; | ||
| import ExecutionContextBuilder from '../../test_utils/data/ExecutionContextBuilder'; | ||
|
|
||
| const mockJwtService = { | ||
| verifyAsync: jest.fn(), | ||
| }; | ||
| const mockReflector = { | ||
| getAllAndOverride: jest.fn(), | ||
| }; | ||
|
|
||
| describe('BoxIdFilterInterceptor class test suite', () => { | ||
| let interceptor: BoxIdFilterInterceptor; | ||
| let callHandler: CallHandler; | ||
|
|
||
| beforeEach(() => { | ||
| interceptor = new BoxIdFilterInterceptor( | ||
| mockReflector as any, | ||
| mockJwtService as any, | ||
| ); | ||
| callHandler = { handle: jest.fn() } as any; | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('should filter array data by box_id', async () => { | ||
| const boxId = 'box123'; | ||
| const data = [ | ||
| { box_id: 'box123', value: 1 }, | ||
| { box_id: 'box999', value: 2 }, | ||
| ]; | ||
| const request = new RequestBuilder().build(); | ||
| (request as any).user = { box_id: boxId }; | ||
| const context = new ExecutionContextBuilder() | ||
| .setHttpRequest(request) | ||
| .build(); | ||
| (callHandler.handle as jest.Mock).mockReturnValue(of(data)); | ||
|
|
||
| const results$ = await interceptor.intercept(context, callHandler); | ||
| const result = await lastValueFrom(results$); | ||
| expect(result).toEqual([{ box_id: 'box123', value: 1 }]); | ||
| }); | ||
|
|
||
| it('should filter nested data and update metaData', async () => { | ||
| const boxId = 'box123'; | ||
| const data = { | ||
| data: { | ||
| Clan: [ | ||
| { box_id: 'box123', name: 'A' }, | ||
| { box_id: 'box999', name: 'B' }, | ||
| ], | ||
| }, | ||
| metaData: { dataKey: 'Clan', dataCount: 2 }, | ||
| paginationData: { itemCount: 2 }, | ||
| }; | ||
| const request = new RequestBuilder().build(); | ||
| (request as any).user = { box_id: boxId }; | ||
| const context = new ExecutionContextBuilder() | ||
| .setHttpRequest(request) | ||
| .build(); | ||
| (callHandler.handle as jest.Mock).mockReturnValue(of(data)); | ||
|
|
||
| const results$ = await interceptor.intercept(context, callHandler); | ||
| const result = await lastValueFrom(results$); | ||
| expect(result.data.Clan).toEqual([{ box_id: 'box123', name: 'A' }]); | ||
| expect(result.metaData.dataCount).toBe(1); | ||
| expect(result.paginationData.itemCount).toBe(1); | ||
| }); | ||
|
|
||
| it('should skip filtering if NO_BOX_ID_FILTER is set', async () => { | ||
| mockReflector.getAllAndOverride.mockReturnValueOnce(true); | ||
| const data = [ | ||
| { box_id: 'box123', value: 1 }, | ||
| { box_id: 'box999', value: 2 }, | ||
| ]; | ||
| const request = new RequestBuilder().build(); | ||
| (request as any).user = { box_id: 'box123' }; | ||
| const context = new ExecutionContextBuilder() | ||
| .setHttpRequest(request) | ||
| .build(); | ||
| (callHandler.handle as jest.Mock).mockReturnValue(of(data)); | ||
|
|
||
| const results$ = await interceptor.intercept(context, callHandler); | ||
| const result = await lastValueFrom(results$); | ||
| expect(result).toEqual(data); | ||
| }); | ||
|
|
||
| it('should extract box_id from JWT if user is missing', async () => { | ||
| const boxId = 'jwtBoxId'; | ||
| mockJwtService.verifyAsync.mockResolvedValueOnce({ box_id: boxId }); | ||
| const data = [ | ||
| { box_id: 'jwtBoxId', value: 1 }, | ||
| { box_id: 'other', value: 2 }, | ||
| ]; | ||
| const request = new RequestBuilder() | ||
| .setHeaders({ authorization: 'Bearer token' }) | ||
| .build(); | ||
| const context = new ExecutionContextBuilder() | ||
| .setHttpRequest(request) | ||
| .build(); | ||
| (callHandler.handle as jest.Mock).mockReturnValue(of(data)); | ||
|
|
||
| const results$ = await interceptor.intercept(context, callHandler); | ||
| const result = await lastValueFrom(results$); | ||
| expect(result).toEqual([{ box_id: 'jwtBoxId', value: 1 }]); | ||
| expect(mockJwtService.verifyAsync).toHaveBeenCalledWith( | ||
| 'token', | ||
| expect.any(Object), | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw APIError if JWT is invalid', async () => { | ||
| mockJwtService.verifyAsync.mockRejectedValueOnce(new Error('bad token')); | ||
| const request = new RequestBuilder() | ||
| .setHeaders({ authorization: 'Bearer valid-test-token' }) | ||
| .build(); | ||
| const context = new ExecutionContextBuilder() | ||
| .setHttpRequest(request) | ||
| .build(); | ||
| (callHandler.handle as jest.Mock).mockReturnValue(of([])); | ||
|
|
||
| await expect( | ||
| interceptor.intercept(context, callHandler).then(lastValueFrom), | ||
| ).rejects.toThrow(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| import { | ||
| Injectable, | ||
| NestInterceptor, | ||
| ExecutionContext, | ||
| CallHandler, | ||
| } from '@nestjs/common'; | ||
| import { Observable, mergeMap } from 'rxjs'; | ||
| import { BoxUser } from './BoxUser'; | ||
| import { Reflector } from '@nestjs/core'; | ||
| import { JwtService } from '@nestjs/jwt'; | ||
| import { envVars } from '../../common/service/envHandler/envVars'; | ||
| import { APIError } from '../../common/controller/APIError'; | ||
| import { APIErrorReason } from '../../common/controller/APIErrorReason'; | ||
| import { NO_BOX_ID_FILTER } from './decorator/NoBoxIdFilter.decorator'; | ||
|
|
||
| /** | ||
| * Interceptor used for testing sessions to prevent data leaks. | ||
| * Interceptor get's the users box_id from the request and then filters | ||
| * all outgoing data based on that box_id. So users are not able to get | ||
| * any data from other boxes. | ||
| */ | ||
| @Injectable() | ||
| export class BoxIdFilterInterceptor implements NestInterceptor { | ||
| constructor( | ||
| private readonly reflector: Reflector, | ||
| private readonly jwtService: JwtService, | ||
| ) {} | ||
| async intercept( | ||
PlayJeri marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| context: ExecutionContext, | ||
| next: CallHandler, | ||
| ): Promise<Observable<any>> { | ||
| const noFilter = this.reflector.getAllAndOverride<boolean>( | ||
| NO_BOX_ID_FILTER, | ||
| [context.getHandler(), context.getClass()], | ||
| ); | ||
| if (noFilter) return next.handle(); | ||
|
|
||
| const request = context.switchToHttp().getRequest(); | ||
| const boxUser: BoxUser = request.user; | ||
| let boxId: string; | ||
| if (!boxUser) { | ||
| boxId = await this.getBoxIdFromRequest(request); | ||
| } else { | ||
| boxId = boxUser.box_id; | ||
| } | ||
|
|
||
| return next | ||
| .handle() | ||
| .pipe(mergeMap(async (data) => this.filterByBoxId(await data, boxId))); | ||
| } | ||
|
|
||
| /** | ||
| * Used to extract the box_id from the request. | ||
| * @param request incoming http request. | ||
| * @returns The box ID | ||
| */ | ||
| private async getBoxIdFromRequest(request: any): Promise<string | undefined> { | ||
| if (request.user && request.user.box_id) return request.user.box_id; | ||
|
|
||
| const [type, token] = request.headers.authorization?.split(' ') ?? []; | ||
| if (type === 'Bearer' && token) { | ||
| try { | ||
| const payload: BoxUser = await this.jwtService.verifyAsync(token, { | ||
| secret: envVars.JWT_SECRET, | ||
| }); | ||
| return payload.box_id; | ||
| } catch { | ||
| throw new APIError({ | ||
| reason: APIErrorReason.NOT_AUTHENTICATED, | ||
| message: | ||
| 'All endpoints need to be provided an auth token in testing sessions.', | ||
| }); | ||
| } | ||
| } | ||
| return undefined; | ||
| } | ||
|
|
||
| /** | ||
| * | ||
| * | ||
| * @param data Data to be filtered. | ||
| * @param boxId The box ID used for filtering | ||
| * @returns Data where box_id matches the boxId. | ||
| */ | ||
| private filterByBoxId(data: any, boxId: string): any { | ||
| if ( | ||
| data && | ||
| typeof data === 'object' && | ||
| data.data && | ||
| typeof data.data === 'object' | ||
| ) { | ||
| for (const key of Object.keys(data.data)) { | ||
| const value = data.data[key]; | ||
| if (Array.isArray(value)) { | ||
| const filtered = value.filter((item) => item?.box_id === boxId); | ||
| data.data[key] = filtered; | ||
| // Update metaData.dataCount if key matches metaData.dataKey | ||
| if ( | ||
| data.metaData && | ||
| data.metaData.dataKey === key && | ||
| typeof data.metaData.dataCount === 'number' | ||
| ) { | ||
| data.metaData.dataCount = filtered.length; | ||
| } | ||
| if ( | ||
| data.paginationData && | ||
| typeof data.paginationData.itemCount === 'number' | ||
| ) { | ||
| data.paginationData.itemCount = filtered.length; | ||
| } | ||
| } | ||
| } | ||
| return data; | ||
| } | ||
|
|
||
| // If data is just an array, filter it | ||
| if (Array.isArray(data)) { | ||
| return data.filter((item) => item?.box_id === boxId); | ||
| } | ||
|
|
||
| // If data is an object with box_id, filter recursively | ||
| if (data && typeof data === 'object') { | ||
| if ('box_id' in data && data.box_id !== boxId) return undefined; | ||
| for (const key of Object.keys(data)) { | ||
| data[key] = this.filterByBoxId(data[key], boxId); | ||
| } | ||
| } | ||
| return data; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import { SetMetadata } from '@nestjs/common'; | ||
|
|
||
| export const NO_BOX_ID_FILTER = 'NO_BOX_ID_FILTER'; | ||
|
|
||
| /** | ||
| * Used for skipping the BoxIdFilter interceptor. | ||
| * Used in testing session related endpoints that need to be able to return | ||
| * entities from DB that don't match the requesting users box_id | ||
| * of for endpoints before the user is authenticated. | ||
| */ | ||
| export const NoBoxIdFilter = () => SetMetadata(NO_BOX_ID_FILTER, true); | ||
PlayJeri marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.