Fix the host check in a ping handler
Your task
Your internal ops tool pings a host the user types, to check it is reachable. The first version ran sh -c "ping -c 1 " + host, so a host like 8.8.8.8; cat /etc/passwd ran a second command. The new version runs ping directly with a list of arguments (argv) and no shell.
An assistant wrote build_ping_argv(host), which decides what that argument list is. It is in the editor. It has a bug. Find it and fix it.
Input and output:
host: the text the user typed.- Return
["ping", "-c", "1", host]when the host is valid, withhostunchanged. Return[]when it is not, and nothing runs.
Rules the tests check. A host is valid only when all of these hold:
- It is 1 to 253 characters long, dots included.
- Split on
., every part (a label) is 1 to 63 characters long. So no empty labels:a..band a leading or trailing.are invalid. - Every character of a label is an ASCII letter, a digit from 0 to 9 or
-. - No label starts or ends with
-. This also stops-f, whichpingwould read as an option, not a host. - If every label is made only of digits, the host must be an IPv4 address. That means exactly 4 labels, each from 0 to 255, with no leading zero.
0is fine,010is not, because some resolvers read010as octal 8.
Examples:
build_ping_argv("8.8.8.8")returns["ping", "-c", "1", "8.8.8.8"].build_ping_argv("8.8.8.8; cat /etc/passwd")returns[].build_ping_argv("internal-db.corp.example.com")returns["ping", "-c", "1", "internal-db.corp.example.com"].
Then, in a sentence or two: how would you catch this kind of bug in review?
Examples
build_ping_argv(host: str) -> list[str]Example 1
Input
build_ping_argv("8.8.8.8")Output
["ping", "-c", "1", "8.8.8.8"]Example 2
Input
build_ping_argv("8.8.8.8; cat /etc/passwd")Output
[]Example 3
Input
build_ping_argv("internal-db.corp.example.com")Output
["ping", "-c", "1", "internal-db.corp.example.com"]