3
3
import functools
4
4
import ipaddress
5
5
import socket
6
+ from collections .abc import Sequence
6
7
from typing import TYPE_CHECKING
7
8
from urllib .parse import urlparse
8
9
9
10
from django .conf import settings
10
11
from django .utils .encoding import force_str
11
12
from urllib3 .exceptions import LocationParseError
12
13
from urllib3 .util .connection import _set_socket_options , allowed_gai_family
14
+ from urllib3 .util .timeout import _DEFAULT_TIMEOUT , _TYPE_DEFAULT
13
15
14
16
from sentry .exceptions import RestrictedIPAddress
15
17
@@ -104,12 +106,12 @@ def is_safe_hostname(hostname: str | None) -> bool:
104
106
105
107
# Modifed version of urllib3.util.connection.create_connection.
106
108
def safe_create_connection (
107
- address ,
108
- timeout = socket . _GLOBAL_DEFAULT_TIMEOUT ,
109
- source_address = None ,
110
- socket_options = None ,
109
+ address : tuple [ str , int ] ,
110
+ timeout : _TYPE_DEFAULT | float | None = _DEFAULT_TIMEOUT ,
111
+ source_address : str | None = None ,
112
+ socket_options : Sequence [ tuple [ int , int , int | bytes ]] | None = None ,
111
113
is_ipaddress_permitted : IsIpAddressPermitted = None ,
112
- ):
114
+ ) -> socket . socket :
113
115
if is_ipaddress_permitted is None :
114
116
is_ipaddress_permitted = is_ipaddress_allowed
115
117
@@ -137,6 +139,7 @@ def safe_create_connection(
137
139
138
140
# Begin custom code.
139
141
ip = sa [0 ]
142
+ assert isinstance (ip , str ), ip # we aren't running ipv6-disabled python
140
143
if not is_ipaddress_permitted (ip ):
141
144
# I am explicitly choosing to be overly aggressive here. This means
142
145
# the first IP that matches that hits our restricted set of IP networks,
@@ -155,7 +158,7 @@ def safe_create_connection(
155
158
# If provided, set socket level options before connecting.
156
159
_set_socket_options (sock , socket_options )
157
160
158
- if timeout is not socket . _GLOBAL_DEFAULT_TIMEOUT :
161
+ if timeout is not _DEFAULT_TIMEOUT :
159
162
sock .settimeout (timeout )
160
163
if source_address :
161
164
sock .bind (source_address )
0 commit comments