From 11444356cd79130f8c041e70de7aede713a967de Mon Sep 17 00:00:00 2001 From: Moul <moul@moul.re> Date: Mon, 14 Jun 2021 18:10:12 +0200 Subject: [PATCH] [fix] #170: endpoint: Fix ipv4/host attributes mix up In case only an IPv4 is present, the latter ends up in server/host attribute Since HOST_REGEX is using dots, the IPv4 is matched as a host Only happening to BMA(S) and GVA since the other endpoints' regex are using one among (host|ipv6|ipv4) Use ipaddress as a trick after regex matching to switch ipv4 and server/host attributes --- duniterpy/api/endpoint.py | 22 ++++++++++++++++++++++ tests/api/test_endpoints.py | 12 ++++++++++++ 2 files changed, 34 insertions(+) diff --git a/duniterpy/api/endpoint.py b/duniterpy/api/endpoint.py index 3ef14708..41e51d5b 100644 --- a/duniterpy/api/endpoint.py +++ b/duniterpy/api/endpoint.py @@ -14,6 +14,7 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. import re +from ipaddress import ip_address from typing import Any, Dict, Optional, Type, TypeVar from duniterpy import constants as const @@ -175,6 +176,13 @@ class BMAEndpoint(Endpoint): ipv4 = m["ipv4"] ipv6 = m["ipv6"] port = int(m["port"]) + + try: + if ip_address(server).version == 4: + ipv4 = server + server = "" + except ValueError: + pass return cls(server, ipv4, ipv6, port) def inline(self) -> str: @@ -270,6 +278,13 @@ class SecuredBMAEndpoint(BMAEndpoint): ipv6 = m["ipv6"] port = int(m["port"]) path = m["path"] + + try: + if ip_address(server).version == 4: + ipv4 = server + server = "" + except ValueError: + pass if not path: path = "" return cls(server, ipv4, ipv6, port, path) @@ -624,6 +639,13 @@ class GVAEndpoint(Endpoint): ipv6 = m["ipv6"] port = int(m["port"]) path = m["path"] + + try: + if ip_address(server).version == 4: + ipv4 = server + server = "" + except ValueError: + pass if not flags: flags = "" if not path: diff --git a/tests/api/test_endpoints.py b/tests/api/test_endpoints.py index 75dc7a61..7198759e 100644 --- a/tests/api/test_endpoints.py +++ b/tests/api/test_endpoints.py @@ -87,3 +87,15 @@ class TestEndpoint(unittest.TestCase): self.assertEqual(gvasub_endpoint.path, "gva") assert gvasub_endpoint.inline(), endpoint_str + + def test_gva_host_ipv4_mix_up(self): + endpoint_str = "GVA S 127.0.0.1 443 gva" + gva_endpoint = endpoint.GVAEndpoint.from_inline(endpoint_str) + self.assertEqual(gva_endpoint.server, "") + self.assertEqual(gva_endpoint.ipv4, "127.0.0.1") + + def test_bmas_host_ipv4_mix_up(self): + endpoint_str = "BMAS 127.0.0.1 443 bma" + bmas_endpoint = endpoint.SecuredBMAEndpoint.from_inline(endpoint_str) + self.assertEqual(bmas_endpoint.server, "") + self.assertEqual(bmas_endpoint.ipv4, "127.0.0.1") -- GitLab