From 3d04bbdd47086ac7de4e67d8ef0664aa11b2f677 Mon Sep 17 00:00:00 2001 From: checktheroads Date: Mon, 20 Jan 2020 00:34:45 -0700 Subject: [PATCH] improve validation of listen_address --- hyperglass/configuration/models/general.py | 29 +++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/hyperglass/configuration/models/general.py b/hyperglass/configuration/models/general.py index 0087184..8dc223c 100644 --- a/hyperglass/configuration/models/general.py +++ b/hyperglass/configuration/models/general.py @@ -2,6 +2,7 @@ # Standard Library Imports from datetime import datetime +from ipaddress import ip_address from pathlib import Path from typing import List from typing import Optional @@ -50,10 +51,36 @@ class General(HyperglassModel): redis_port: StrictInt = 6379 requires_ipv6_cidr: List[StrictStr] = ["cisco_ios", "cisco_nxos"] request_timeout: StrictInt = 30 - listen_address: Union[IPvAnyAddress, StrictStr] = "localhost" + listen_address: Optional[Union[IPvAnyAddress, StrictStr]] listen_port: StrictInt = 8001 log_file: Optional[FilePath] + @validator("listen_address", pre=True, always=True) + def validate_listen_address(cls, value, values): + """Set default listen_address based on debug mode. + + Arguments: + value {str|IPvAnyAddress|None} -- listen_address + values {dict} -- already-validated entries before listen_address + + Returns: + {str} -- Validated listen_address + """ + if value is None and not values["debug"]: + listen_address = "localhost" + elif value is None and values["debug"]: + listen_address = ip_address("0.0.0.0") # noqa: S104 + elif isinstance(value, str) and value != "localhost": + try: + listen_address = ip_address(value) + except ValueError: + raise ValueError(str(value)) + elif isinstance(value, str) and value == "localhost": + listen_address = value + else: + raise ValueError(str(value)) + return listen_address + @validator("site_description") def validate_site_description(cls, value, values): """Format the site descripion with the org_name field.