pytest-socket icon indicating copy to clipboard operation
pytest-socket copied to clipboard

--allow-hosts does not account for dynamic DNS resolution at runtime

Open s-ankur opened this issue 8 months ago • 0 comments

When using --allow-hosts to permit network connections to specific hostnames, pytest-socket resolves these hostnames to IP addresses at the start of the test session. However, libraries like boto3 (which utilizes urllib3) perform DNS resolution at runtime, potentially obtaining different IP addresses.

As a result, even if a hostname is specified in --allow-hosts, connections made to IP addresses resolved during test execution are blocked, leading to unexpected SocketConnectBlockedError exceptions.

Steps to Reproduce:

  1. Install boto3, pytest, and pytest-socket.

  2. Write a test that uses boto3 to interact with an AWS service (e.g., listing S3 buckets).

  3. Run pytest with the following options:

    pytest --disable-socket --allow-hosts=amazonaws.com
    
  4. Observe that the test fails with a SocketConnectBlockedError, despite amazonaws.com being allowed.

Expected Behavior:

Allowing a hostname via --allow-hosts should permit all connections to that hostname, regardless of when DNS resolution occurs.

Actual Behavior:

Connections to IP addresses resolved at runtime are blocked, even if their corresponding hostnames are specified in --allow-hosts.

Additional Context:

This issue arises because pytest-socket resolves allowed hostnames to IP addresses only once at the beginning of the test session. If a library performs DNS resolution during test execution and obtains different IP addresses, these are not recognized as allowed, leading to blocked connections.

A potential solution could involve resolving hostnames at the time of each connection attempt

s-ankur avatar Apr 29 '25 01:04 s-ankur