Skip to content

Commit

Permalink
Add type hint to util/ssl_match_hostname.py
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani committed Apr 20, 2021
1 parent 123c627 commit f432f38
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
1 change: 1 addition & 0 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"src/urllib3/util/connection.py",
"src/urllib3/util/queue.py",
"src/urllib3/util/response.py",
"src/urllib3/util/ssl_match_hostname.py",
"src/urllib3/util/url.py",
}
SOURCE_FILES = [
Expand Down
16 changes: 9 additions & 7 deletions src/urllib3/util/ssl_match_hostname.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import ipaddress
import re
from typing import Dict, Tuple, Union
from typing import Any, Dict, Match, Optional, Tuple, Union

# https://github.com/python/typeshed/blob/master/stdlib/2and3/ssl.pyi
_PCTRTT = Tuple[Tuple[str, str], ...]
Expand All @@ -20,7 +20,9 @@ class CertificateError(ValueError):
pass


def _dnsname_match(dn, hostname, max_wildcards=1):
def _dnsname_match(
dn: Any, hostname: str, max_wildcards: int = 1
) -> Union[Optional[Match[str]], bool]:
"""Matching according to RFC 6125, section 6.4.3
http://tools.ietf.org/html/rfc6125#section-6.4.3
Expand All @@ -47,7 +49,7 @@ def _dnsname_match(dn, hostname, max_wildcards=1):

# speed up common case w/o wildcards
if not wildcards:
return dn.lower() == hostname.lower()
return bool(dn.lower() == hostname.lower())

# RFC 6125, section 6.4.3, subitem 1.
# The client SHOULD NOT attempt to match a presented identifier in which
Expand All @@ -74,7 +76,7 @@ def _dnsname_match(dn, hostname, max_wildcards=1):
return pat.match(hostname)


def _ipaddress_match(ipname, host_ip):
def _ipaddress_match(ipname: Any, host_ip: str) -> bool:
"""Exact matching of IP addresses.
RFC 6125 explicitly doesn't define an algorithm for this
Expand All @@ -83,7 +85,7 @@ def _ipaddress_match(ipname, host_ip):
# OpenSSL may add a trailing newline to a subjectAltName's IP address
# Divergence from upstream: ipaddress can't handle byte str
ip = ipaddress.ip_address(ipname.rstrip())
return ip == host_ip
return bool(ip == host_ip)


def match_hostname(cert: _PeerCertRetType, hostname: str) -> None:
Expand All @@ -107,8 +109,8 @@ def match_hostname(cert: _PeerCertRetType, hostname: str) -> None:
# Not an IP address (common case)
host_ip = None
dnsnames = []
san = cert.get("subjectAltName", ())
for key, value in san:
san = cert.get("subjectAltName", ()) # type: ignore
for key, value in san: # type: ignore
if key == "DNS":
if host_ip is None and _dnsname_match(value, hostname):
return
Expand Down

0 comments on commit f432f38

Please sign in to comment.