improve make_error_response

This commit is contained in:
Maximilian Hils 2017-02-15 15:55:08 +01:00
parent 4bac850bb1
commit 2955e3d566
2 changed files with 25 additions and 14 deletions

View File

@ -10,6 +10,7 @@ import mitmproxy.net.http
from mitmproxy import connections # noqa
from mitmproxy import exceptions
from mitmproxy import http
from mitmproxy.net.http import status_codes
REALM = "mitmproxy"
@ -68,15 +69,13 @@ class ProxyAuth:
def auth_required_response(self) -> http.HTTPResponse:
if self.is_proxy_auth():
return http.make_error_response(
407,
"Proxy Authentication Required",
mitmproxy.net.http.Headers(Proxy_Authenticate='Basic realm="{}"'.format(REALM)),
status_codes.PROXY_AUTH_REQUIRED,
headers=mitmproxy.net.http.Headers(Proxy_Authenticate='Basic realm="{}"'.format(REALM)),
)
else:
return http.make_error_response(
401,
"Authentication Required",
mitmproxy.net.http.Headers(WWW_Authenticate='Basic realm="{}"'.format(REALM)),
status_codes.UNAUTHORIZED,
headers=mitmproxy.net.http.Headers(WWW_Authenticate='Basic realm="{}"'.format(REALM)),
)
def check(self, f: http.HTTPFlow) -> Optional[Tuple[str, str]]:
@ -95,7 +94,7 @@ class ProxyAuth:
if self.nonanonymous:
return username, password
elif self.singleuser:
if [username, password] == self.singleuser:
if self.singleuser == [username, password]:
return username, password
elif self.htpasswd:
if self.htpasswd.check_password(username, password):

View File

@ -1,4 +1,5 @@
import cgi
import html
from typing import Optional
from mitmproxy import flow
@ -203,16 +204,27 @@ class HTTPFlow(flow.Flow):
return c
def make_error_response(status_code, message, headers=None):
response = http.status_codes.RESPONSES.get(status_code, "Unknown")
def make_error_response(
status_code: int,
message: str="",
headers: Optional[http.Headers]=None,
) -> HTTPResponse:
reason = http.status_codes.RESPONSES.get(status_code, "Unknown")
body = """
<html>
<head>
<title>%d %s</title>
<title>{status_code} {reason}</title>
</head>
<body>%s</body>
<body>
<h1>{status_code} {reason}</h1>
<p>{message}</p>
</body>
</html>
""".strip() % (status_code, response, cgi.escape(message))
""".strip().format(
status_code=status_code,
reason=reason,
message=html.escape(message),
)
body = body.encode("utf8", "replace")
if not headers:
@ -226,7 +238,7 @@ def make_error_response(status_code, message, headers=None):
return HTTPResponse(
b"HTTP/1.1",
status_code,
response,
reason,
headers,
body,
)