Dynamic Login for upstream proxy

Hello everyone,

I have made a script that sends each request to a specific upstream proxy based on the host, thanks to change_upstream_proxy. I am now trying to figure out how to handle upstream proxy that require login.

I see that the --upstream-auth option exists and works perfectly, however I am trying to have different credentials based on different upstream proxy, basically I wish to change the Proxy-Authorization value of the header in the script I launch with mitmdump.

I tried to change it that way

    from mitmproxy.utils import strutils
    import json
    import base64
    import psycopg2

    def request(flow):

        flow.request.headers["Proxy-Authorization"] = b"Basic" + b" " + base64.b64encode(strutils.always_bytes("charles:charles"))
        print(flow.request.headers)

        conn = psycopg2.connect("dbname= cdhdtdb1 user=postgres password=***** host=192.168.0.126 port=5432")
        cursor = conn.cursor()
        cursor.execute(
            "prepare myplan as "
            "select * from config where host = $1")

        host = flow.request.host
        if flow.request.method == "CONNECT":
            return
        cursor.execute("""execute myplan (%(host)s)""", {"host": host})
        once = True
        for request in cursor:
            if flow.live and once:
                flow.live.change_upstream_proxy_server((request[2], int(request[3])))
                once = False

However it does not work, I have a wireshark running on the proxy and the value of Proxy-Authorization is still the one defined at the command line, I am not able to change it with the script. I am wondering if it is possible or the way the layer are made makes it impossible ?

Best regards,
Charles