| 5 | |
| 6 | |
| 7 | class TestIPRule: |
| 8 | host1 = '127.0.0.1' |
| 9 | host2 = '127.0.1.0' |
| 10 | host3 = '128.0.0.1' |
| 11 | host4 = '127.0.0.0/23' |
| 12 | host5 = '127.0.0.0/25' |
| 13 | subnet1 = '127.0.0.0/24' |
| 14 | fact1 = Fact(trait='host.ip.address', value=host1) |
| 15 | fact2 = Fact(trait='host.ip.address', value=host2) |
| 16 | fact3 = Fact(trait='host.ip.address', value=host3) |
| 17 | fact4 = Fact(trait='host.ip.address', value=host4) |
| 18 | fact5 = Fact(trait='host.ip.address', value=host5) |
| 19 | fact6 = Fact(trait='host.ip.address', value=subnet1) |
| 20 | rule = Rule(trait='host.ip.address', action=RuleAction.DENY, match=subnet1) |
| 21 | rs = RuleSet(rules=[rule]) |
| 22 | |
| 23 | def test_rule_serialize(self): |
| 24 | rule_display = self.rule.display |
| 25 | assert rule_display['trait'] == 'host.ip.address' |
| 26 | assert rule_display['action'] == 'DENY' |
| 27 | assert rule_display['match'] == self.subnet1 |
| 28 | |
| 29 | def test_rule_deserialize(self): |
| 30 | rule_serialized = { |
| 31 | "trait": "host.ip.address", |
| 32 | "action": "DENY", |
| 33 | "match": self.subnet1, |
| 34 | } |
| 35 | test_rule = Rule.load(rule_serialized) |
| 36 | assert test_rule.trait == 'host.ip.address' |
| 37 | assert test_rule.action == RuleAction.DENY |
| 38 | assert test_rule.match == self.subnet1 |
| 39 | |
| 40 | async def test_is_ip_rule_match(self): |
| 41 | assert await self.rs._is_ip_rule_match(self.rule, self.fact1) |
| 42 | assert (not await self.rs._is_ip_rule_match(self.rule, self.fact2)) |
| 43 | assert (not await self.rs._is_ip_rule_match(self.rule, self.fact3)) |
| 44 | |
| 45 | async def test_is_fact_allowed(self): |
| 46 | assert (not await self.rs.is_fact_allowed(self.fact1)) |
| 47 | assert await self.rs.is_fact_allowed(self.fact2) |
| 48 | assert await self.rs.is_fact_allowed(self.fact3) |
| 49 | |
| 50 | async def test_smaller_subnet(self): |
| 51 | assert (not await self.rs._is_ip_rule_match(self.rule, self.fact4)) |
| 52 | assert await self.rs.is_fact_allowed(self.fact4) |
| 53 | |
| 54 | async def test_larger_subnet(self): |
| 55 | assert (not await self.rs._is_ip_rule_match(self.rule, self.fact5)) |
| 56 | assert await self.rs.is_fact_allowed(self.fact5) |
| 57 | |
| 58 | async def test_same_subnet(self): |
| 59 | assert await self.rs._is_ip_rule_match(self.rule, self.fact6) |
| 60 | assert (not await self.rs.is_fact_allowed(self.fact6)) |