stub out proxyauth addon

Stub out basic workings, add and test configure event.
This commit is contained in:
Aldo Cortesi 2016-11-13 12:32:20 +13:00
parent fe01b1435a
commit e644d2167c
2 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,68 @@
import binascii
import passlib.apache
from mitmproxy import exceptions
def parse_http_basic_auth(s):
words = s.split()
if len(words) != 2:
return None
scheme = words[0]
try:
user = binascii.a2b_base64(words[1]).decode("utf8", "replace")
except binascii.Error:
return None
parts = user.split(':')
if len(parts) != 2:
return None
return scheme, parts[0], parts[1]
def assemble_http_basic_auth(scheme, username, password):
v = binascii.b2a_base64(
(username + ":" + password).encode("utf8")
).decode("ascii")
return scheme + " " + v
class ProxyAuth:
def __init__(self):
self.nonanonymous = False
self.htpasswd = None
self.singleuser = None
def configure(self, options, updated):
if "auth_nonanonymous" in updated:
self.nonanonymous = options.auth_nonanonymous
if "auth_singleuser" in updated:
if options.auth_singleuser:
parts = options.auth_singleuser.split(':')
if len(parts) != 2:
raise exceptions.OptionsError(
"Invalid single-user auth specification."
)
self.singleuser = parts
else:
self.singleuser = None
if "auth_htpasswd" in updated:
if options.auth_htpasswd:
try:
self.htpasswd = passlib.apache.HtpasswdFile(
options.auth_htpasswd
)
except (ValueError, OSError) as v:
raise exceptions.OptionsError(
"Could not open htpasswd file: %s" % v
)
else:
self.auth_htpasswd = None
def http_connect(self, f):
# mode = regular
pass
def http_request(self, f):
# mode = regular, no via
pass

View File

@ -0,0 +1,53 @@
import binascii
from mitmproxy import exceptions
from mitmproxy.test import taddons
from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.addons import proxyauth
def test_parse_http_basic_auth():
vals = ("basic", "foo", "bar")
assert proxyauth.parse_http_basic_auth(
proxyauth.assemble_http_basic_auth(*vals)
) == vals
assert not proxyauth.parse_http_basic_auth("")
assert not proxyauth.parse_http_basic_auth("foo bar")
v = "basic " + binascii.b2a_base64(b"foo").decode("ascii")
assert not proxyauth.parse_http_basic_auth(v)
def test_configure():
up = proxyauth.ProxyAuth()
with taddons.context() as ctx:
tutils.raises(
exceptions.OptionsError,
ctx.configure, up, auth_singleuser="foo"
)
ctx.configure(up, auth_singleuser="foo:bar")
assert up.singleuser == ["foo", "bar"]
ctx.configure(up, auth_singleuser=None)
assert up.singleuser is None
ctx.configure(up, auth_nonanonymous=True)
assert up.nonanonymous
ctx.configure(up, auth_nonanonymous=False)
assert not up.nonanonymous
tutils.raises(
exceptions.OptionsError,
ctx.configure,
up,
auth_htpasswd = tutils.test_data.path(
"mitmproxy/net/data/server.crt"
)
)
tutils.raises(
exceptions.OptionsError,
ctx.configure,
up,
auth_htpasswd = "nonexistent"
)