Skip to content

Commit

Permalink
chore: unit tests for buildFirewall rules
Browse files Browse the repository at this point in the history
  • Loading branch information
JuroUhlar committed Dec 21, 2023
1 parent 78371e8 commit a34efb3
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
66 changes: 66 additions & 0 deletions src/server/botd-firewall/updateFirewallRule.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { buildFirewallRules } from './updateFirewallRule';
import { describe, expect, it } from 'vitest';

describe('buildFirewallRules', () => {
it('should build a single firewall rule correctly', async () => {
const blockedIps = ['192.168.0.1', '10.0.0.1', '172.16.0.1'];
const expectedRules = [
{
action: 'block',
description: 'Block Bot IP addresses #1',
expression: 'http.x_forwarded_for in {"192.168.0.1" "10.0.0.1" "172.16.0.1"}',
},
];
const rules = await buildFirewallRules(blockedIps);

expect(rules).toEqual(expectedRules);
});

// Add more test cases here...
it('should build multiple firewall rules correctly', async () => {
const blockedIps = [
'68.237.223.37',
'53.40.210.202',
'140.184.133.152',
'253.221.155.217',
'195.43.16.78',
'2.2.2.2',
'2.2.2.2',
'2.2.2.2',
'2.2.2.2',
'2.2.2.2',
'3.3.3.3',
'3.3.3.3',
'3.3.3.3',
'3.3.3.3',
'3.3.3.3',
'4.4.4.4',
'4.4.4.4',
];
const expectedRules = [
{
action: 'block',
description: 'Block Bot IP addresses #1',
expression:
'http.x_forwarded_for in {"68.237.223.37" "53.40.210.202" "140.184.133.152" "253.221.155.217" "195.43.16.78"}',
},
{
action: 'block',
description: 'Block Bot IP addresses #2',
expression: 'http.x_forwarded_for in {"2.2.2.2" "2.2.2.2" "2.2.2.2" "2.2.2.2" "2.2.2.2"}',
},
{
action: 'block',
description: 'Block Bot IP addresses #3',
expression: 'http.x_forwarded_for in {"3.3.3.3" "3.3.3.3" "3.3.3.3" "3.3.3.3" "3.3.3.3"}',
},
{
action: 'block',
description: 'Block Bot IP addresses #4',
expression: 'http.x_forwarded_for in {"4.4.4.4" "4.4.4.4"}',
},
];
const rules = await buildFirewallRules(blockedIps, 5);
expect(rules).toEqual(expectedRules);
});
});
7 changes: 5 additions & 2 deletions src/server/botd-firewall/updateFirewallRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@ export const getBlockedIps = async (): Promise<string[]> => {
return blockedIps.map((ip) => ip.ip);
};

export const buildFirewallRules = async (blockedIps: string[]): Promise<CloudflareRule[]> => {
export const buildFirewallRules = async (
blockedIps: string[],
maxIpsPerRule = MAX_IPS_PER_RULE,
): Promise<CloudflareRule[]> => {
// Split the list of blocked IPs into chunks of MAX_IPS_PER_RULE length
const chunks = chunk(blockedIps, MAX_IPS_PER_RULE);
const chunks = chunk(blockedIps, maxIpsPerRule);

// Build the rule expression for each chunk
const ruleExpressions = chunks.map((chunk) => {
Expand Down

0 comments on commit a34efb3

Please sign in to comment.