|
1 | 1 | """Api middleware.""" |
2 | 2 |
|
| 3 | +import contextlib |
3 | 4 | import re |
4 | 5 | import typing |
5 | 6 | from http.client import HTTP_PORT, HTTPS_PORT |
@@ -44,6 +45,10 @@ def __init__( |
44 | 45 | ) |
45 | 46 |
|
46 | 47 |
|
| 48 | +_PROTO_HEADER_REGEX = re.compile(r"proto=(?P<proto>http(s)?)") |
| 49 | +_HOST_HEADER_REGEX = re.compile(r"host=(?P<host>[\w.-]+)(:(?P<port>\d{1,5}))?") |
| 50 | + |
| 51 | + |
47 | 52 | class ProxyHeaderMiddleware: |
48 | 53 | """Account for forwarding headers when deriving base URL. |
49 | 54 |
|
@@ -92,25 +97,20 @@ def _get_forwarded_url_parts(self, scope: Scope) -> Tuple[str]: |
92 | 97 |
|
93 | 98 | if forwarded := self._get_header_value_by_name(scope, "forwarded"): |
94 | 99 | for proxy in forwarded.split(","): |
95 | | - if (proto_expr := re.search(r"proto=(?P<proto>http(s)?)", proxy)) and ( |
96 | | - host_expr := re.search( |
97 | | - r"host=(?P<host>[\w.-]+)(:(?P<port>\d{1,5}))?", proxy |
98 | | - ) |
| 100 | + if (proto_expr := _PROTO_HEADER_REGEX.search(proxy)) and ( |
| 101 | + host_expr := _HOST_HEADER_REGEX.search(proxy) |
99 | 102 | ): |
100 | | - proto = proto_expr.groupdict()["proto"] |
101 | | - domain = host_expr.groupdict()["host"] |
102 | | - port_str = host_expr.groupdict().get("port", None) |
| 103 | + proto = proto_expr.group("proto") |
| 104 | + domain = host_expr.group("host") |
| 105 | + port_str = host_expr.group("port") # None if not present in the match |
103 | 106 |
|
104 | 107 | else: |
105 | 108 | domain = self._get_header_value_by_name(scope, "x-forwarded-host", domain) |
106 | 109 | proto = self._get_header_value_by_name(scope, "x-forwarded-proto", proto) |
107 | 110 | port_str = self._get_header_value_by_name(scope, "x-forwarded-port", port) |
108 | 111 |
|
109 | | - try: |
| 112 | + with contextlib.suppress(ValueError): # ignore ports that are not valid integers |
110 | 113 | port = int(port_str) if port_str is not None else port |
111 | | - except ValueError: |
112 | | - # ignore ports that are not valid integers |
113 | | - pass |
114 | 114 |
|
115 | 115 | return (proto, domain, port) |
116 | 116 |
|
|
0 commit comments