|
| 1 | +/** |
| 2 | + * Tests for GeoBlockGuard. |
| 3 | + * |
| 4 | + * Verifies: |
| 5 | + * - Requests from a blocked country are rejected with 451. |
| 6 | + * - Requests from an allowed country pass. |
| 7 | + * - A missing geo header defaults to allow (no false positives). |
| 8 | + */ |
| 9 | + |
| 10 | +import { ExecutionContext, HttpException } from '@nestjs/common'; |
| 11 | +import { ConfigService } from '@nestjs/config'; |
| 12 | +import { GeoBlockGuard } from '../geo-block.guard'; |
| 13 | + |
| 14 | +function makeContext(headers: Record<string, string>): ExecutionContext { |
| 15 | + const request = { headers }; |
| 16 | + return { |
| 17 | + switchToHttp: () => ({ |
| 18 | + getRequest: () => request, |
| 19 | + }), |
| 20 | + } as unknown as ExecutionContext; |
| 21 | +} |
| 22 | + |
| 23 | +function makeConfigService(blockedCountries: string): ConfigService { |
| 24 | + return { get: () => blockedCountries } as unknown as ConfigService; |
| 25 | +} |
| 26 | + |
| 27 | +describe('GeoBlockGuard', () => { |
| 28 | + it('rejects requests from a blocked country with 451', () => { |
| 29 | + const guard = new GeoBlockGuard(makeConfigService('KP,IR,CU')); |
| 30 | + const ctx = makeContext({ 'cf-ipcountry': 'IR' }); |
| 31 | + |
| 32 | + expect(() => guard.canActivate(ctx)).toThrow(HttpException); |
| 33 | + try { |
| 34 | + guard.canActivate(ctx); |
| 35 | + } catch (err) { |
| 36 | + expect((err as HttpException).getStatus()).toBe(451); |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + it('allows requests from a non-blocked country', () => { |
| 41 | + const guard = new GeoBlockGuard(makeConfigService('KP,IR,CU')); |
| 42 | + const ctx = makeContext({ 'cf-ipcountry': 'US' }); |
| 43 | + |
| 44 | + expect(guard.canActivate(ctx)).toBe(true); |
| 45 | + }); |
| 46 | + |
| 47 | + it('allows requests with no geo header (no false positives)', () => { |
| 48 | + const guard = new GeoBlockGuard(makeConfigService('KP,IR,CU')); |
| 49 | + const ctx = makeContext({}); |
| 50 | + |
| 51 | + expect(guard.canActivate(ctx)).toBe(true); |
| 52 | + }); |
| 53 | + |
| 54 | + it('falls back to X-Country-Code when CF-IPCountry is absent', () => { |
| 55 | + const guard = new GeoBlockGuard(makeConfigService('KP,IR,CU')); |
| 56 | + const ctx = makeContext({ 'x-country-code': 'kp' }); |
| 57 | + |
| 58 | + expect(() => guard.canActivate(ctx)).toThrow(HttpException); |
| 59 | + }); |
| 60 | + |
| 61 | + it('allows all requests when BLOCKED_COUNTRIES is empty', () => { |
| 62 | + const guard = new GeoBlockGuard(makeConfigService('')); |
| 63 | + const ctx = makeContext({ 'cf-ipcountry': 'IR' }); |
| 64 | + |
| 65 | + expect(guard.canActivate(ctx)).toBe(true); |
| 66 | + }); |
| 67 | +}); |
0 commit comments