Fix the check for ports open to the internet

Review the AI's codeMedium20 minAmazon style

Your task

You asked an assistant to let the app servers reach a Postgres database, and it opened port 5432 to 0.0.0.0/0, the whole internet. It worked in staging because a rule that broad includes the app servers too. The team now audits every security group's ingress rules, the rules for incoming traffic.

An assistant wrote internet_exposed_ports(rules). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • rules: one string per ingress rule, meant to be "<port>|<cidr>", such as "5432|10.0.1.0/24". The list can be empty.
  • Return the ports reachable from outside private address space, as a list of integers with no repeats, in ascending order.

Rules the tests check:

  • Skip a rule unless it splits on | into exactly 2 parts.
  • The port must be digits only and from 0 to 65535. Otherwise skip the rule.
  • The CIDR is an address, a /, then a prefix length. Split at the first / and skip the rule if there is none. The prefix length must be digits only and from 0 to 32. The address must split on . into exactly 4 parts, each digits only and from 0 to 255. Skip anything else.
  • A CIDR with prefix length n covers every address whose first n bits match the address written. So 10.5.7.9/8 covers 10.0.0.0 to 10.255.255.255, and /0 covers every address.
  • Private space is three ranges: 10.0.0.0 to 10.255.255.255, 172.16.0.0 to 172.31.255.255, and 192.168.0.0 to 192.168.255.255.
  • A rule exposes its port when the range its CIDR covers does not fit entirely inside one of those three ranges.

Examples

internet_exposed_ports(rules: list[str]) -> list[int]
Example 1
Inputinternet_exposed_ports(["5432|0.0.0.0/0"])
Output[5432]
Example 2
Inputinternet_exposed_ports(["5432|10.0.1.0/24", "5432|10.0.2.0/24"])
Output[]
Example 3
Inputinternet_exposed_ports(["5432|172.16.0.0/12", "5432|172.32.0.0/12"])
Output[5432]