refactor: use ipaddress library for ip validation

This commit is contained in:
Inex Code 2024-03-01 14:58:28 +03:00 committed by dettlaff
parent 9399a3bdf3
commit 467796b2ad
3 changed files with 10 additions and 8 deletions

View file

@ -44,7 +44,7 @@ class MailServer(Service):
return None return None
@staticmethod @staticmethod
def get_subdomain() -> str | None: def get_subdomain() -> Optional[str]:
return None return None
@staticmethod @staticmethod

View file

@ -2,6 +2,7 @@
"""Network utils""" """Network utils"""
import subprocess import subprocess
import re import re
import ipaddress
from typing import Optional from typing import Optional
@ -23,9 +24,9 @@ def get_ip6() -> Optional[str]:
ip6 = subprocess.check_output(["ip", "addr", "show", "dev", "eth0"]).decode( ip6 = subprocess.check_output(["ip", "addr", "show", "dev", "eth0"]).decode(
"utf-8" "utf-8"
) )
# We ignore link-local addresses ip6 = re.findall(r"inet6 (\S+)\/\d+", ip6)
ip6 = re.search(r"inet6 (?!fe80:\S+)(\S+)\/\d+", ip6) for address in ip6:
if ipaddress.IPv6Address(address).is_global:
return address
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
ip6 = None return None
return ip6.group(1) if ip6 else None

View file

@ -168,13 +168,14 @@ def test_enabling_disabling_writes_json(
# more detailed testing of this is in test_graphql/test_system.py # more detailed testing of this is in test_graphql/test_system.py
# Using the same random global IPs as the test_network_utils
def test_mailserver_with_dkim_returns_some_dns(dkim_file): def test_mailserver_with_dkim_returns_some_dns(dkim_file):
records = MailServer().get_dns_records("203.0.113.3", "2001:db8::1") records = MailServer().get_dns_records("157.90.247.192", "2a01:4f8:c17:7e3d::2")
assert len(records) > 0 assert len(records) > 0
def test_mailserver_with_no_dkim_returns_no_dns(no_dkim_file): def test_mailserver_with_no_dkim_returns_no_dns(no_dkim_file):
assert MailServer().get_dns_records("203.0.113.3", "2001:db8::1") == [] assert MailServer().get_dns_records("157.90.247.192", "2a01:4f8:c17:7e3d::2") == []
def test_services_enabled_by_default(generic_userdata): def test_services_enabled_by_default(generic_userdata):