diff --git a/mitmproxy/addons/proxyauth.py b/mitmproxy/addons/proxyauth.py index e9505d91b..18a858667 100644 --- a/mitmproxy/addons/proxyauth.py +++ b/mitmproxy/addons/proxyauth.py @@ -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): diff --git a/mitmproxy/http.py b/mitmproxy/http.py index 9c59984ab..f0cabcf8e 100644 --- a/mitmproxy/http.py +++ b/mitmproxy/http.py @@ -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 = """ - %d %s + {status_code} {reason} - %s + +

{status_code} {reason}

+

{message}

+ - """.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, )