comparison libervia/server/proxy.py @ 1435:396d5606477f

server (proxy): add "Forwarded" and "X-Forwarded-xxx" headers to reverse proxy
author Goffi <goffi@goffi.org>
date Mon, 14 Jun 2021 15:27:33 +0200
parents 822bd0139769
children fc91b78b71db
comparison
equal deleted inserted replaced
1434:2f6dac783c8e 1435:396d5606477f
15 15
16 # You should have received a copy of the GNU Affero General Public License 16 # You should have received a copy of the GNU Affero General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>. 17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 from twisted.web import proxy 18 from twisted.web import proxy
19 from twisted.python.compat import urlquote 19 from twisted.python.compat import urlquote
20 from twisted.internet import address
20 from sat.core.log import getLogger 21 from sat.core.log import getLogger
22 from libervia.server.constants import Const as C
21 23
22 log = getLogger(__name__) 24 log = getLogger(__name__)
23 25
24 26
25 27
46 return SatReverseProxyResource( 48 return SatReverseProxyResource(
47 self.host, self.port, 49 self.host, self.port,
48 self.path + b'/' + urlquote(path, safe=b"").encode('utf-8'), 50 self.path + b'/' + urlquote(path, safe=b"").encode('utf-8'),
49 self.reactor 51 self.reactor
50 ) 52 )
53
54 def render(self, request):
55 # Forwarded and X-Forwarded-xxx headers can be set if we have behin an other proxy
56 if ((not request.getHeader(C.H_FORWARDED)
57 and not request.getHeader(C.H_X_FORWARDED_HOST))):
58 forwarded_data = []
59 addr = request.getClientAddress()
60 if ((isinstance(addr, address.IPv4Address)
61 or isinstance(addr, address.IPv6Address))):
62 request.requestHeaders.setRawHeaders(C.H_X_FORWARDED_FOR, [addr.host])
63 forwarded_data.append(f"for={addr.host}")
64 host = request.getHeader("host")
65 if host is None:
66 port = request.getHost().port
67 hostname = request.getRequestHostname()
68 host = hostname if port in (80, 443) else f"{hostname}:{port}"
69 request.requestHeaders.setRawHeaders(C.H_X_FORWARDED_HOST, [host])
70 forwarded_data.append(f"host={host}")
71 proto = "https" if request.isSecure() else "http"
72 request.requestHeaders.setRawHeaders(C.H_X_FORWARDED_PROTO, [proto])
73 forwarded_data.append(f"proto={proto}")
74 request.requestHeaders.setRawHeaders(
75 C.H_FORWARDED, [";".join(forwarded_data)]
76 )
77
78 return super().render(request)