-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #17 from techsavvyash/feat/geoip
feat: add geoip based request blocking
- Loading branch information
Showing
5 changed files
with
881 additions
and
16 deletions.
There are no files selected for viewing
This file contains 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 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,66 @@ | ||
import { GeoIPInterceptor } from './geoip.interceptor'; | ||
import { ExecutionContext, HttpException } from '@nestjs/common'; | ||
import { Observable, of } from 'rxjs'; | ||
|
||
describe('GeoIpInterceptor', () => { | ||
let interceptor: GeoIPInterceptor; | ||
|
||
beforeEach(() => { | ||
interceptor = new GeoIPInterceptor(); | ||
}); | ||
|
||
it('should allow a request from India', async () => { | ||
const executionContext = createMockExecutionContext('115.240.90.163'); // Mock IP from India | ||
const callHandler = { | ||
handle: jest.fn().mockReturnValue(of({})), | ||
}; | ||
|
||
await expect(interceptor.intercept(executionContext, callHandler)).resolves.toBeInstanceOf(Observable); | ||
}); | ||
|
||
it('should allow a request from India with IPv6', async () => { | ||
const executionContext = createMockExecutionContext('2401:4900:1c70:140b:fd0c:65a1:64e2:81bb'); // Mock IP from India | ||
const callHandler = { | ||
handle: jest.fn().mockReturnValue(of({})), | ||
}; | ||
|
||
await expect(interceptor.intercept(executionContext, callHandler)).resolves.toBeInstanceOf(Observable); | ||
}); | ||
|
||
it('should block a request from outside India', async () => { | ||
const executionContext = createMockExecutionContext('128.101.101.101'); // Mock IP from outside India | ||
const callHandler = { | ||
handle: jest.fn().mockReturnValue(of({})), | ||
}; | ||
|
||
await expect(interceptor.intercept(executionContext, callHandler)).rejects.toThrow(HttpException); | ||
}); | ||
|
||
it('should block a request from machine local IP', async () => { | ||
const executionContext = createMockExecutionContext('127.0.0.1'); // Mock IP from outside India | ||
const callHandler = { | ||
handle: jest.fn().mockReturnValue(of({})), | ||
}; | ||
|
||
await expect(interceptor.intercept(executionContext, callHandler)).rejects.toThrow(HttpException); | ||
}); | ||
|
||
it('should block a request from a fake spoofed IP', async () => { | ||
const executionContext = createMockExecutionContext('1607:e054:4d04:8f9c:6efa:761f:b964:57b6'); // Mock IP from outside India | ||
const callHandler = { | ||
handle: jest.fn().mockReturnValue(of({})), | ||
}; | ||
|
||
await expect(interceptor.intercept(executionContext, callHandler)).rejects.toThrow(HttpException); | ||
}); | ||
// Helper function to create a mock ExecutionContext | ||
function createMockExecutionContext(ip: string): ExecutionContext { | ||
return { | ||
switchToHttp: () => ({ | ||
getRequest: () => ({ | ||
headers: { 'x-forwarded-for': ip }, | ||
}), | ||
}), | ||
} as ExecutionContext; | ||
} | ||
}); |
This file contains 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,41 @@ | ||
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger, HttpStatus, InternalServerErrorException, HttpException } from '@nestjs/common'; | ||
import { Observable } from 'rxjs'; | ||
import { HttpService } from '@nestjs/axios'; | ||
import { CustomLogger } from "../common/logger"; | ||
|
||
@Injectable() | ||
export class GeoIPInterceptor implements NestInterceptor { | ||
private logger: CustomLogger; | ||
private readonly httpService: HttpService; | ||
|
||
constructor() { | ||
this.logger = new CustomLogger('GeoIPInterceptor'); | ||
this.httpService = new HttpService(); | ||
} | ||
|
||
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> { | ||
const request = context.switchToHttp().getRequest(); | ||
const clientIp = request.headers['x-forwarded-for'] || request.ip; // Get client IP address | ||
|
||
// Call the geolocation service to get the country from the IP | ||
const { country, regionName } = await this.getLocation(clientIp); | ||
|
||
if (country !== 'India') { | ||
this.logger.verbose('Denying request from ip: ' + clientIp + ' country: ' + country) | ||
throw new HttpException('Access Denied', HttpStatus.FORBIDDEN); | ||
} | ||
|
||
this.logger.verbose('Allowed request from ip: ' + clientIp + ' region: ' + regionName) | ||
return next.handle(); | ||
} | ||
|
||
private async getLocation(ip: any): Promise<any> { | ||
try { | ||
const resp = await this.httpService.axiosRef.get(`https://geoip.samagra.io/city/${ip}`) | ||
return { country: resp.data.country, regionName: resp.data.regionName }; | ||
} catch (err) { | ||
this.logger.error('Error occured while reading the geoip database', err); | ||
throw new InternalServerErrorException('Error occured while reading the geoip database'); | ||
} | ||
} | ||
} |
This file contains 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.