Refactor: update examples to utilize new address paradigm with wildcard support

- Introduced `get_wildcard_address` function for explicit wildcard binding.
- Updated examples to use `get_available_interfaces` and `get_optimal_binding_address` for address selection.
- Ensured consistent usage of the new address paradigm across all example files.
- Added tests to verify the implementation of the new address paradigm and wildcard feature.
This commit is contained in:
yashksaini-coder
2025-09-09 12:10:28 +05:30
parent 80e22f7c4a
commit 7d364da950
15 changed files with 280 additions and 181 deletions

View File

@ -1,12 +1,12 @@
"""
Tests to verify that all examples use 127.0.0.1 instead of 0.0.0.0
Tests to verify that all examples use the new address paradigm consistently
"""
from pathlib import Path
class TestExamplesBindAddress:
"""Test suite to verify all examples use secure bind addresses"""
class TestExamplesAddressParadigm:
"""Test suite to verify all examples use the new address paradigm consistently"""
def get_example_files(self):
"""Get all Python files in the examples directory"""
@ -32,49 +32,26 @@ class TestExamplesBindAddress:
return found_wildcards
def test_no_wildcard_binding_in_examples(self):
"""Test that no example files use 0.0.0.0 for binding"""
def test_examples_use_address_paradigm(self):
"""Test that examples use the new address paradigm functions"""
example_files = self.get_example_files()
# Skip certain files that might legitimately discuss wildcards
skip_files = [
"network_discover.py", # This demonstrates wildcard expansion
]
files_with_wildcards = {}
for filepath in example_files:
if any(skip in str(filepath) for skip in skip_files):
continue
wildcards = self.check_file_for_wildcard_binding(filepath)
if wildcards:
files_with_wildcards[str(filepath)] = wildcards
# Assert no wildcards found
if files_with_wildcards:
error_msg = "Found wildcard bindings in example files:\n"
for filepath, occurrences in files_with_wildcards.items():
error_msg += f"\n{filepath}:\n"
for line_num, line in occurrences:
error_msg += f" Line {line_num}: {line}\n"
assert False, error_msg
def test_examples_use_loopback_address(self):
"""Test that examples use 127.0.0.1 for local binding"""
example_files = self.get_example_files()
# Files that should contain listen addresses
files_with_networking = [
"ping/ping.py",
# Files that should use the new paradigm
networking_examples = [
"echo/echo.py",
"chat/chat.py",
"ping/ping.py",
"bootstrap/bootstrap.py",
"pubsub/pubsub.py",
"identify/identify.py",
]
for filename in files_with_networking:
paradigm_functions = [
"get_available_interfaces",
"get_optimal_binding_address",
]
for filename in networking_examples:
filepath = None
for example_file in example_files:
if filename in str(example_file):
@ -87,24 +64,54 @@ class TestExamplesBindAddress:
with open(filepath, encoding="utf-8") as f:
content = f.read()
# Check for proper loopback usage
has_loopback = "127.0.0.1" in content or "localhost" in content
has_multiaddr_loopback = "/ip4/127.0.0.1/" in content
# Check that the file uses the new paradigm functions
for func in paradigm_functions:
assert func in content, (
f"{filepath} should use {func} from the new address paradigm"
)
assert has_loopback or has_multiaddr_loopback, (
f"{filepath} should use loopback address (127.0.0.1)"
def test_wildcard_available_as_feature(self):
"""Test that wildcard is available as a feature when needed"""
example_files = self.get_example_files()
# Check that network_discover.py demonstrates wildcard usage
network_discover_file = None
for example_file in example_files:
if "network_discover.py" in str(example_file):
network_discover_file = example_file
break
if network_discover_file:
with open(network_discover_file, encoding="utf-8") as f:
content = f.read()
# Should demonstrate wildcard expansion
assert "0.0.0.0" in content, (
f"{network_discover_file} should demonstrate wildcard usage"
)
assert "expand_wildcard_address" in content, (
f"{network_discover_file} should use expand_wildcard_address"
)
def test_doc_examples_use_loopback(self):
"""Test that documentation examples use secure addresses"""
def test_doc_examples_use_paradigm(self):
"""Test that documentation examples use the new address paradigm"""
doc_examples_dir = Path("examples/doc-examples")
if not doc_examples_dir.exists():
return
doc_example_files = list(doc_examples_dir.glob("*.py"))
paradigm_functions = [
"get_available_interfaces",
"get_optimal_binding_address",
]
for filepath in doc_example_files:
wildcards = self.check_file_for_wildcard_binding(filepath)
assert not wildcards, (
f"Documentation example {filepath} contains wildcard binding"
)
with open(filepath, encoding="utf-8") as f:
content = f.read()
# Check that doc examples use the new paradigm
for func in paradigm_functions:
assert func in content, (
f"Documentation example {filepath} should use {func}"
)

View File

@ -1,5 +1,5 @@
"""
Tests for default bind address changes from 0.0.0.0 to 127.0.0.1
Tests for the new address paradigm with wildcard support as a feature
"""
import pytest
@ -9,28 +9,43 @@ from libp2p import new_host
from libp2p.utils.address_validation import (
get_available_interfaces,
get_optimal_binding_address,
get_wildcard_address,
)
class TestDefaultBindAddress:
class TestAddressParadigm:
"""
Test suite for verifying default bind addresses use
secure addresses (not 0.0.0.0)
Test suite for verifying the new address paradigm:
- get_available_interfaces() returns all available interfaces
- get_optimal_binding_address() returns optimal address for examples
- get_wildcard_address() provides wildcard as a feature when needed
"""
def test_default_bind_address_is_not_wildcard(self):
"""Test that default bind address is NOT 0.0.0.0 (wildcard)"""
def test_wildcard_address_function(self):
"""Test that get_wildcard_address() provides wildcard as a feature"""
port = 8000
addr = get_wildcard_address(port)
# Should return wildcard address when explicitly requested
assert "0.0.0.0" in str(addr)
addr_str = str(addr)
assert "/ip4/" in addr_str
assert f"/tcp/{port}" in addr_str
def test_optimal_binding_address_selection(self):
"""Test that optimal binding address uses good heuristics"""
port = 8000
addr = get_optimal_binding_address(port)
# Should NOT return wildcard address
assert "0.0.0.0" not in str(addr)
# Should return a valid IP address (could be loopback or local network)
addr_str = str(addr)
assert "/ip4/" in addr_str
assert f"/tcp/{port}" in addr_str
# Should be from available interfaces
available_interfaces = get_available_interfaces(port)
assert addr in available_interfaces
def test_available_interfaces_includes_loopback(self):
"""Test that available interfaces always includes loopback address"""
port = 8000
@ -43,9 +58,12 @@ class TestDefaultBindAddress:
loopback_found = any("127.0.0.1" in str(addr) for addr in interfaces)
assert loopback_found, "Loopback address not found in available interfaces"
# Should not have wildcard as the only option
if len(interfaces) == 1:
assert "0.0.0.0" not in str(interfaces[0])
# Available interfaces should not include wildcard by default
# (wildcard is available as a feature through get_wildcard_address())
wildcard_found = any("0.0.0.0" in str(addr) for addr in interfaces)
assert not wildcard_found, (
"Wildcard should not be in default available interfaces"
)
def test_host_default_listen_address(self):
"""Test that new hosts use secure default addresses"""
@ -59,55 +77,66 @@ class TestDefaultBindAddress:
# Note: We can't test actual binding without running the host,
# but we've verified the address format is correct
def test_no_wildcard_in_fallback(self):
"""Test that fallback addresses don't use wildcard binding"""
# When no interfaces are discovered, fallback should be loopback
def test_paradigm_consistency(self):
"""Test that the address paradigm is consistent"""
port = 8000
# Even if we can't discover interfaces, we should get loopback
addr = get_optimal_binding_address(port)
# Should NOT be wildcard
assert "0.0.0.0" not in str(addr)
# get_optimal_binding_address should return a valid address
optimal_addr = get_optimal_binding_address(port)
assert "/ip4/" in str(optimal_addr)
assert f"/tcp/{port}" in str(optimal_addr)
# Should be a valid IP address
addr_str = str(addr)
assert "/ip4/" in addr_str
assert f"/tcp/{port}" in addr_str
# get_wildcard_address should return wildcard when explicitly needed
wildcard_addr = get_wildcard_address(port)
assert "0.0.0.0" in str(wildcard_addr)
assert f"/tcp/{port}" in str(wildcard_addr)
# Both should be valid Multiaddr objects
assert isinstance(optimal_addr, Multiaddr)
assert isinstance(wildcard_addr, Multiaddr)
@pytest.mark.parametrize("protocol", ["tcp", "udp"])
def test_different_protocols_use_secure_addresses(self, protocol):
"""Test that different protocols still use secure addresses by default"""
def test_different_protocols_support(self, protocol):
"""Test that different protocols are supported by the paradigm"""
port = 8000
addr = get_optimal_binding_address(port, protocol=protocol)
# Should NOT be wildcard
assert "0.0.0.0" not in str(addr)
assert protocol in str(addr)
# Test optimal address with different protocols
optimal_addr = get_optimal_binding_address(port, protocol=protocol)
assert protocol in str(optimal_addr)
assert f"/{protocol}/{port}" in str(optimal_addr)
# Should be a valid IP address
addr_str = str(addr)
assert "/ip4/" in addr_str
assert f"/{protocol}/{port}" in addr_str
# Test wildcard address with different protocols
wildcard_addr = get_wildcard_address(port, protocol=protocol)
assert "0.0.0.0" in str(wildcard_addr)
assert protocol in str(wildcard_addr)
assert f"/{protocol}/{port}" in str(wildcard_addr)
def test_security_no_public_binding_by_default(self):
"""Test that no public interface binding occurs by default"""
# Test available interfaces with different protocols
interfaces = get_available_interfaces(port, protocol=protocol)
assert len(interfaces) > 0
for addr in interfaces:
assert protocol in str(addr)
def test_wildcard_available_as_feature(self):
"""Test that wildcard binding is available as a feature when needed"""
port = 8000
# Wildcard should be available through get_wildcard_address()
wildcard_addr = get_wildcard_address(port)
assert "0.0.0.0" in str(wildcard_addr)
# But should not be in default available interfaces
interfaces = get_available_interfaces(port)
# Check that we don't expose on all interfaces by default
wildcard_addrs = [addr for addr in interfaces if "0.0.0.0" in str(addr)]
assert len(wildcard_addrs) == 0, (
"Found wildcard addresses in default interfaces"
wildcard_in_interfaces = any("0.0.0.0" in str(addr) for addr in interfaces)
assert not wildcard_in_interfaces, (
"Wildcard should not be in default interfaces"
)
# Verify optimal address selection doesn't choose wildcard
# Optimal address should not be wildcard by default
optimal = get_optimal_binding_address(port)
assert "0.0.0.0" not in str(optimal), "Optimal address should not be wildcard"
# Should be a valid IP address (could be loopback or local network)
addr_str = str(optimal)
assert "/ip4/" in addr_str
assert f"/tcp/{port}" in addr_str
assert "0.0.0.0" not in str(optimal), (
"Optimal address should not be wildcard by default"
)
def test_loopback_is_always_available(self):
"""Test that loopback address is always available as an option"""
@ -132,9 +161,6 @@ class TestDefaultBindAddress:
interfaces = get_available_interfaces(port)
optimal = get_optimal_binding_address(port)
# Should never return wildcard
assert "0.0.0.0" not in str(optimal)
# Should return one of the available interfaces
optimal_str = str(optimal)
interface_strs = [str(addr) for addr in interfaces]
@ -142,7 +168,7 @@ class TestDefaultBindAddress:
f"Optimal address {optimal_str} should be in available interfaces"
)
# If non-loopback interfaces are available, should prefer them
# Should prefer non-loopback when available, fallback to loopback
non_loopback_interfaces = [
addr for addr in interfaces if "127.0.0.1" not in str(addr)
]
@ -157,23 +183,21 @@ class TestDefaultBindAddress:
"Should use loopback when no other interfaces available"
)
def test_address_validation_utilities_behavior(self):
"""Test that address validation utilities behave as expected"""
def test_address_paradigm_completeness(self):
"""Test that the address paradigm provides all necessary functionality"""
port = 8000
# Test that we get multiple interface options
# Test that we get interface options
interfaces = get_available_interfaces(port)
assert len(interfaces) >= 2, (
"Should have at least loopback + one network interface"
)
assert len(interfaces) >= 1, "Should have at least one interface"
# Test that loopback is always included
has_loopback = any("127.0.0.1" in str(addr) for addr in interfaces)
assert has_loopback, "Loopback should always be available"
# Test that no wildcards are included
has_wildcard = any("0.0.0.0" in str(addr) for addr in interfaces)
assert not has_wildcard, "Wildcard addresses should never be included"
# Test that wildcard is available as a feature
wildcard_addr = get_wildcard_address(port)
assert "0.0.0.0" in str(wildcard_addr)
# Test optimal selection
optimal = get_optimal_binding_address(port)