-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheader_utils.py
More file actions
165 lines (139 loc) · 4.45 KB
/
Copy pathheader_utils.py
File metadata and controls
165 lines (139 loc) · 4.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""Validation and safe merging for proxy CONNECT headers.
CONNECT requests are raw HTTP and must not interpolate CR, LF, or NUL.
CONNECT response headers are not origin HTTPS headers: hop-by-hop and
security-sensitive names are not copied onto the origin response, and
existing origin headers are never overwritten.
"""
from __future__ import annotations
from typing import Any, Dict, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union
RawHeaders = Union[Mapping[Any, Any], Sequence[Tuple[Any, Any]], None]
# Never copy these from a CONNECT response onto the origin response.
BLOCKED_PROXY_RESPONSE_HEADERS = frozenset({
"age",
"authorization",
"cache-control",
"clear-site-data",
"connection",
"content-disposition",
"content-encoding",
"content-language",
"content-length",
"content-location",
"content-range",
"content-security-policy",
"content-security-policy-report-only",
"content-type",
"cookie",
"date",
"etag",
"expires",
"host",
"keep-alive",
"last-modified",
"link",
"location",
"pragma",
"proxy-agent",
"proxy-authenticate",
"proxy-authorization",
"proxy-connection",
"refresh",
"server",
"set-cookie",
"set-cookie2",
"strict-transport-security",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"vary",
"via",
"warning",
"www-authenticate",
"x-content-type-options",
"x-frame-options",
"x-xss-protection",
})
def _as_str(value: Any) -> str:
if isinstance(value, bytes):
return value.decode("latin-1")
return str(value)
def validate_header_name(name: Any) -> str:
"""Return a header name, or raise ValueError if it is not a single token."""
name_s = _as_str(name)
if not name_s:
raise ValueError("Header name must not be empty")
for char in name_s:
code = ord(char)
if char in "()<>@,;:\\\"/[]?={} \t:" or code <= 32 or code == 127:
raise ValueError(f"Invalid header name {name_s!r}")
return name_s
def validate_header_value(value: Any) -> str:
"""Return a header value, or raise ValueError if it contains CR, LF, or NUL."""
value_s = _as_str(value)
if any(char in value_s for char in "\r\n\x00"):
raise ValueError(f"Invalid header value {value_s!r}")
return value_s
def validate_headers(headers: Optional[Mapping[Any, Any]]) -> Dict[str, str]:
"""Validate a mapping of CONNECT request headers.
Raises:
ValueError: If any name or value contains CR, LF, NUL, or other
characters illegal in a single CONNECT header line.
"""
if not headers:
return {}
validated: Dict[str, str] = {}
for name, value in headers.items():
validated[validate_header_name(name)] = validate_header_value(value)
return validated
def _header_items(headers: RawHeaders) -> List[Tuple[Any, Any]]:
if not headers:
return []
if isinstance(headers, (list, tuple)):
return list(headers)
if hasattr(headers, "items"):
return list(headers.items())
return []
def origin_has_header(origin_headers: RawHeaders, name: str) -> bool:
"""Return True if origin_headers already contains ``name`` (case-insensitive)."""
lowered = _as_str(name).lower()
for key, _value in _header_items(origin_headers):
if _as_str(key).lower() == lowered:
return True
return False
def is_mergeable_proxy_header(name: Any) -> bool:
"""Return True if a CONNECT response header may be copied onto origin headers."""
lowered = _as_str(name).lower()
if lowered in BLOCKED_PROXY_RESPONSE_HEADERS:
return False
if lowered.startswith("access-control-"):
return False
return True
def snapshot_headers(headers: RawHeaders) -> Dict[str, str]:
"""Copy headers into a plain dict of strings."""
snapshot: Dict[str, str] = {}
for name, value in _header_items(headers):
snapshot[_as_str(name)] = _as_str(value)
return snapshot
def merge_proxy_response_headers(
origin_headers: MutableMapping[Any, Any],
proxy_headers: RawHeaders,
) -> None:
"""Copy safe CONNECT headers onto origin headers without overwriting."""
for name, value in _header_items(proxy_headers):
name_s = _as_str(name)
if not is_mergeable_proxy_header(name_s):
continue
if origin_has_header(origin_headers, name_s):
continue
origin_headers[name_s] = _as_str(value)
def filter_connect_headers(
origin_headers: RawHeaders,
connect_headers: RawHeaders,
) -> List[Tuple[Any, Any]]:
"""Return CONNECT header pairs that are safe to merge into origin headers."""
extra: List[Tuple[Any, Any]] = []
for name, value in _header_items(connect_headers):
if is_mergeable_proxy_header(name) and not origin_has_header(origin_headers, name):
extra.append((name, value))
return extra