Fix the IPv4 check for untrusted log input

Review the AI's codeEasy10 min

Your task

A log pipeline filtered untrusted input with a regex an AI described as an IPv4 validator. It only checked for four groups of one to three digits, so it let through 999.999.999.999. The replacement checks each part of the address for real.

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

Input and output:

  • candidate: the string to check.
  • Return true when it is a canonical IPv4 address, else false.

Rules the tests check:

  • Split the string on .. There must be exactly 4 parts.
  • Each part must be 1 to 3 characters, all ASCII digits.
  • A part longer than one character must not start with 0, so 0 is fine and 010 is not. Some parsers read 010 as octal 8.
  • Each part's value must be at most 255.
  • Nothing is trimmed: any space, tab or other character outside the address makes it invalid.

Examples

is_canonical_ipv4(candidate: str) -> bool
Example 1
Inputis_canonical_ipv4("1.2.3.4")
OutputTrue
Example 2
Inputis_canonical_ipv4("999.999.999.999")
OutputFalse
Example 3
Inputis_canonical_ipv4("010.0.0.1")
OutputFalse