KatInterview

Firewall Rule Resolver with Longest-Prefix Priority

Math & Bit ManipulationAuto-graded · 21 test cases
MediumAuto-gradedMath & Bit Manipulationbit-manipulationcidripv4

Last updated

Resolve an IPv4 address against CIDR allow/deny rules using longest-prefix precedence, later-rule tie-breaking, and a default of deny, via bitmask matching.

Firewall Rule Resolver

A firewall holds an ordered list of rules. Each rule is a pair [action, cidr]:

  • action is either "allow" or "deny".
  • cidr is an IPv4 block written as a.b.c.d/p, where p is the prefix length (0 to 32).

You are also given a single IPv4 address, target_ip, written in dotted-decimal form such as 192.168.1.25.

Decide whether traffic from target_ip is permitted, and return either "allow" or "deny".

How a decision is made

  1. A rule applies to the address if the address lies inside the rule's CIDR block, meaning the first p bits of the address equal the first p bits of the block's base address. Only those p leading bits of the base address matter; any remaining bits of the base address are ignored (so 10.1.2.3/8 covers the same addresses as 10.0.0.0/8). A /0 block covers every address.
  2. Among all applying rules, the one with the largest prefix length decides the outcome.
  3. If several applying rules share that largest prefix length, the one that appears latest in the list decides.
  4. If no rule applies, the answer is "deny".

Function

Implement a function that receives the list of rules and the target address and returns the string "allow" or "deny".

Constraints

  • Every address and CIDR block is valid; each octet is in [0, 255] and each prefix length is in [0, 32].
  • The rule list may be empty.
  • Actions are exactly "allow" or "deny" (lowercase).
  • The return value must be exactly "allow" or "deny".

Examples

Example 1

Input: resolve_firewall_rules([['allow', '192.168.0.0/16'], ['deny', '192.168.1.0/24']], '192.168.1.25')

Output: 'deny'

Example 2

Input: resolve_firewall_rules([['deny', '10.0.0.0/8'], ['allow', '10.1.0.0/16'], ['deny', '10.1.2.0/24']], '10.1.2.55')

Output: 'deny'

Example 3

Input: resolve_firewall_rules([['allow', '172.16.0.0/12'], ['deny', '172.16.5.0/24'], ['allow', '172.16.5.128/25']], '172.16.5.200')

Output: 'allow'

Hints

Hint 1

Convert each dotted address into a single 32-bit integer by shifting the running value left 8 bits and OR-ing in the next octet.

Hint 2

For prefix length p, a mask with p leading ones is (0xffffffff << (32 - p)) & 0xffffffff, with p = 0 handled separately as mask 0. An address is in the block when (address & mask) == (base & mask).

Hint 3

You do not need to sort. Scan the rules once while remembering the best prefix length seen so far (start at -1) and its action; replace them whenever an applying rule has prefix >= the best, so later rules win ties.