aboutsummaryrefslogtreecommitdiffstats
path: root/mitmproxy/addons/upstream_proxy_auth.py
blob: 2ee51fcbd5f54375f1eef68da9ac2a3b8c44c9ae (plain)
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
import re
import base64

from mitmproxy import exceptions
from mitmproxy.utils import strutils


def parse_upstream_auth(auth):
    pattern = re.compile(".+:")
    if pattern.search(auth) is None:
        raise exceptions.OptionsError(
            "Invalid upstream auth specification: %s" % auth
        )
    return b"Basic" + b" " + base64.b64encode(strutils.always_bytes(auth))


class UpstreamProxyAuth():
    def __init__(self):
        self.auth = None

    def configure(self, options, updated):
        if "upstream_auth" in updated:
            if options.upstream_auth is None:
                self.auth = None
            else:
                self.auth = parse_upstream_auth(options.upstream_auth)

    def requestheaders(self, f):
        if self.auth and f.mode == "upstream":
            f.request.headers["Proxy-Authorization"] = self.auth