import { describe, expect, test } from "bun:test"; import buildHostIptablesScripts from "./build-host-iptables-scripts"; const base = { host_id: 0, interface_name: "wgui0", target_interface: "eth0", }; describe("buildHostIptablesScripts", () => { test("deny by default with no clients", () => { const res = buildHostIptablesScripts({ ...base, clients: [], }); expect(res.success).toBe(true); expect(res.post_up).toContain("iptables -N WGUI0FWD"); expect(res.post_up).toContain("iptables -A WGUI0FWD -j DROP"); expect(res.post_up).toContain("iptables -A WGUI0IN -j DROP"); expect(res.post_up).not.toContain("WGUI0FWD -s"); expect(res.post_down).toContain("iptables -X WGUI0FWD"); expect(res.post_down).toContain("iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE"); }); test("all access accepts the client on forward and input", () => { const res = buildHostIptablesScripts({ ...base, clients: [ { id: 1, wg_ip_address: "10.0.0.2", rules: [{ rule_type: "all" }], }, ], }); expect(res.success).toBe(true); expect(res.post_up).toContain( "iptables -A WGUI0FWD -s 10.0.0.2/32 -j ACCEPT", ); expect(res.post_up).toContain( "iptables -A WGUI0IN -s 10.0.0.2/32 -j ACCEPT", ); }); test("destination IP and ports", () => { const res = buildHostIptablesScripts({ ...base, clients: [ { id: 2, wg_ip_address: "10.0.0.3", rules: [ { rule_type: "destination", destination: "192.168.1.10", ports: "80,443", protocol: "tcp", }, ], }, ], }); expect(res.success).toBe(true); expect(res.post_up).toContain( "iptables -A WGUI0FWD -s 10.0.0.3/32 -d 192.168.1.10/32 -p tcp -m multiport --dports 80,443 -j ACCEPT", ); expect(res.post_up).toContain( "iptables -A WGUI0IN -s 10.0.0.3/32 -d 192.168.1.10/32 -p tcp -m multiport --dports 80,443 -j ACCEPT", ); }); test("protocol any with ports emits tcp and udp", () => { const res = buildHostIptablesScripts({ ...base, clients: [ { id: 3, wg_ip_address: "10.0.0.4", rules: [ { rule_type: "destination", ports: "53", protocol: "any", }, ], }, ], }); expect(res.success).toBe(true); expect(res.post_up).toContain( "iptables -A WGUI0FWD -s 10.0.0.4/32 -p tcp --dport 53 -j ACCEPT", ); expect(res.post_up).toContain( "iptables -A WGUI0FWD -s 10.0.0.4/32 -p udp --dport 53 -j ACCEPT", ); }); test("rejects invalid destination", () => { const res = buildHostIptablesScripts({ ...base, clients: [ { id: 4, wg_ip_address: "10.0.0.5", rules: [ { rule_type: "destination", destination: "not-an-ip", }, ], }, ], }); expect(res.success).toBe(false); }); test("cleans up legacy allow-all rules", () => { const res = buildHostIptablesScripts({ ...base, }); expect(res.post_up).toContain( "iptables -D FORWARD -i wgui0 -j ACCEPT 2>/dev/null || true", ); expect(res.post_down).toContain( "iptables -D FORWARD -i wgui0 -j ACCEPT 2>/dev/null || true", ); }); });