Skip to content

Commit

Permalink
fix(dhcpcd): Make lease parsing more robust
Browse files Browse the repository at this point in the history
  • Loading branch information
holmanb committed Apr 1, 2024
1 parent fb0dd29 commit 915bcda
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 6 deletions.
3 changes: 2 additions & 1 deletion cloudinit/net/dhcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -787,8 +787,9 @@ def parse_dhcpcd_lease(lease_dump: str, interface: str) -> Dict:
try:
lease = dict(
[
a.split("=")
a.split("=", maxsplit=1)
for a in lease_dump.strip().replace("'", "").split("\n")
if "=" in a
]
)
except ValueError as error:
Expand Down
60 changes: 55 additions & 5 deletions tests/unittests/net/test_dhcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1199,12 +1199,62 @@ def test_parse_lease_dump(self):
assert "255.255.240.0" == parsed_lease["subnet-mask"]
assert "192.168.0.1" == parsed_lease["routers"]

@pytest.mark.parametrize(
"lease, parsed",
(
pytest.param(
"""
fail
""",
{},
id="lease_has_no_keys",
),
pytest.param(
"""
domain_name='us-east-2.compute.internal'
domain_name_servers='192.168.0.2'
""",
{
"domain_name": "us-east-2.compute.internal",
"domain_name_servers": "192.168.0.2",
},
id="lease_has_empty_lines",
),
pytest.param(
"""
domain_name='us-east-2.compute.internal'
not-a-kv-pair
domain_name_servers='192.168.0.2'
""",
{
"domain_name": "us-east-2.compute.internal",
"domain_name_servers": "192.168.0.2",
},
id="lease_has_values_that_arent_key_value_pairs",
),
pytest.param(
"""
domain_name='us-east=2.compute.internal'
""",
{
"domain_name": "us-east=2.compute.internal",
},
id="lease_has_kv_pair_including_equals_sign_in_value",
),
),
)
def test_parse_lease_dump_resilience(self, lease, parsed):
with mock.patch("cloudinit.net.dhcp.util.load_binary_file"):
Dhcpcd.parse_dhcpcd_lease(dedent(lease), "eth0")

def test_parse_lease_dump_fails(self):
lease = dedent(
"""
fail
"""
)
def _raise():
raise ValueError()
lease = mock.Mock()
lease.strip = _raise

with pytest.raises(InvalidDHCPLeaseFileError):
with mock.patch("cloudinit.net.dhcp.util.load_binary_file"):
Expand Down

0 comments on commit 915bcda

Please sign in to comment.