The following issues were found

test/mitmproxy/data/addonscripts/addon.py
15 issues
Unable to import 'mitmproxy'
Error

Line: 1 Column: 1

              from mitmproxy import ctx
event_log = []


class Addon:
    @property
    def event_log(self):
        return event_log


            

Reported by Pylint.

Unused argument 'opts'
Error

Line: 10 Column: 20

                  def event_log(self):
        return event_log

    def load(self, opts):
        ctx.log.info("addon running")
        event_log.append("addonload")

    def configure(self, updated):
        event_log.append("addonconfigure")

            

Reported by Pylint.

Unused argument 'updated'
Error

Line: 14 Column: 25

                      ctx.log.info("addon running")
        event_log.append("addonload")

    def configure(self, updated):
        event_log.append("addonconfigure")


def configure(updated):
    event_log.append("scriptconfigure")

            

Reported by Pylint.

Unused argument 'updated'
Error

Line: 18 Column: 15

                      event_log.append("addonconfigure")


def configure(updated):
    event_log.append("scriptconfigure")


def load(l):
    event_log.append("scriptload")

            

Reported by Pylint.

Unused argument 'l'
Error

Line: 22 Column: 10

                  event_log.append("scriptconfigure")


def load(l):
    event_log.append("scriptload")


addons = [Addon()]

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from mitmproxy import ctx
event_log = []


class Addon:
    @property
    def event_log(self):
        return event_log


            

Reported by Pylint.

Missing class docstring
Error

Line: 5 Column: 1

              event_log = []


class Addon:
    @property
    def event_log(self):
        return event_log

    def load(self, opts):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 7 Column: 5

              
class Addon:
    @property
    def event_log(self):
        return event_log

    def load(self, opts):
        ctx.log.info("addon running")
        event_log.append("addonload")

            

Reported by Pylint.

Method could be a function
Error

Line: 10 Column: 5

                  def event_log(self):
        return event_log

    def load(self, opts):
        ctx.log.info("addon running")
        event_log.append("addonload")

    def configure(self, updated):
        event_log.append("addonconfigure")

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 10 Column: 5

                  def event_log(self):
        return event_log

    def load(self, opts):
        ctx.log.info("addon running")
        event_log.append("addonload")

    def configure(self, updated):
        event_log.append("addonconfigure")

            

Reported by Pylint.

mitmproxy/utils/typecheck.py
15 issues
Missing module docstring
Error

Line: 1 Column: 1

              import typing

Type = typing.Union[
    typing.Any  # anything more elaborate really fails with mypy at the moment.
]


def sequence_type(typeinfo: typing.Type[typing.List]) -> Type:
    """Return the type of a sequence, e.g. typing.List"""

            

Reported by Pylint.

Too many branches (17/12)
Error

Line: 28 Column: 1

                  return typeinfo.__args__  # type: ignore


def check_option_type(name: str, value: typing.Any, typeinfo: Type) -> None:
    """
    Check if the provided value is an instance of typeinfo and raises a
    TypeError otherwise. This function supports only those types required for
    options.
    """

            

Reported by Pylint.

Variable name "e" doesn't conform to snake_case naming style
Error

Line: 34 Column: 5

                  TypeError otherwise. This function supports only those types required for
    options.
    """
    e = TypeError("Expected {} for {}, but got {}.".format(
        typeinfo,
        name,
        type(value)
    ))


            

Reported by Pylint.

Unnecessary "elif" after "raise"
Error

Line: 42 Column: 5

              
    typename = str(typeinfo)

    if typename.startswith("typing.Union") or typename.startswith("typing.Optional"):
        for T in union_types(typeinfo):
            try:
                check_option_type(name, value, T)
            except TypeError:
                pass

            

Reported by Pylint.

Variable name "T" doesn't conform to snake_case naming style
Error

Line: 43 Column: 13

                  typename = str(typeinfo)

    if typename.startswith("typing.Union") or typename.startswith("typing.Optional"):
        for T in union_types(typeinfo):
            try:
                check_option_type(name, value, T)
            except TypeError:
                pass
            else:

            

Reported by Pylint.

Variable name "T" doesn't conform to snake_case naming style
Error

Line: 57 Column: 20

                          raise e
        if len(types) != len(value):
            raise e
        for i, (x, T) in enumerate(zip(value, types)):
            check_option_type(f"{name}[{i}]", x, T)
        return
    elif typename.startswith("typing.Sequence"):
        T = sequence_type(typeinfo)
        if not isinstance(value, (tuple, list)):

            

Reported by Pylint.

Variable name "x" doesn't conform to snake_case naming style
Error

Line: 57 Column: 17

                          raise e
        if len(types) != len(value):
            raise e
        for i, (x, T) in enumerate(zip(value, types)):
            check_option_type(f"{name}[{i}]", x, T)
        return
    elif typename.startswith("typing.Sequence"):
        T = sequence_type(typeinfo)
        if not isinstance(value, (tuple, list)):

            

Reported by Pylint.

Variable name "T" doesn't conform to snake_case naming style
Error

Line: 61 Column: 9

                          check_option_type(f"{name}[{i}]", x, T)
        return
    elif typename.startswith("typing.Sequence"):
        T = sequence_type(typeinfo)
        if not isinstance(value, (tuple, list)):
            raise e
        for v in value:
            check_option_type(name, v, T)
    elif typename.startswith("typing.IO"):

            

Reported by Pylint.

Variable name "v" doesn't conform to snake_case naming style
Error

Line: 64 Column: 13

                      T = sequence_type(typeinfo)
        if not isinstance(value, (tuple, list)):
            raise e
        for v in value:
            check_option_type(name, v, T)
    elif typename.startswith("typing.IO"):
        if hasattr(value, "read"):
            return
        else:

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 67 Column: 9

                      for v in value:
            check_option_type(name, v, T)
    elif typename.startswith("typing.IO"):
        if hasattr(value, "read"):
            return
        else:
            raise e
    elif typename.startswith("typing.Any"):
        return

            

Reported by Pylint.

release/deploy.py
15 issues
Using an f-string that does not have any interpolated variables
Error

Line: 29 Column: 9

                  subprocess.check_call([
        "aws", "s3", "cp",
        "--acl", "public-read",
        f"./release/dist/",
        f"s3://snapshots.mitmproxy.org/{upload_dir}/",
        "--recursive",
    ])

    # Upload releases to PyPI

            

Reported by Pylint.

FIXME remove
Error

Line: 40 Column: 3

                      subprocess.check_call(["twine", "upload", whl])

    # Upload dev docs
    if branch == "main" or branch == "actions-hardening":  # FIXME remove
        subprocess.check_call([
            "aws", "configure",
            "set", "preview.cloudfront", "true"
        ])
        subprocess.check_call([

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3
import os
import re
import subprocess
from pathlib import Path
from typing import Optional
# Security: No third-party dependencies here!

if __name__ == "__main__":

            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

Line: 4
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess

              #!/usr/bin/env python3
import os
import re
import subprocess
from pathlib import Path
from typing import Optional
# Security: No third-party dependencies here!

if __name__ == "__main__":

            

Reported by Bandit.

subprocess call - check for execution of untrusted input.
Security injection

Line: 26
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html

                      upload_dir = re.sub(r"^v([\d.]+)$", r"\1", tag)
    else:
        upload_dir = f"branches/{branch}"
    subprocess.check_call([
        "aws", "s3", "cp",
        "--acl", "public-read",
        f"./release/dist/",
        f"s3://snapshots.mitmproxy.org/{upload_dir}/",
        "--recursive",

            

Reported by Bandit.

Starting a process with a partial executable path
Security injection

Line: 26
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b607_start_process_with_partial_path.html

                      upload_dir = re.sub(r"^v([\d.]+)$", r"\1", tag)
    else:
        upload_dir = f"branches/{branch}"
    subprocess.check_call([
        "aws", "s3", "cp",
        "--acl", "public-read",
        f"./release/dist/",
        f"s3://snapshots.mitmproxy.org/{upload_dir}/",
        "--recursive",

            

Reported by Bandit.

subprocess call - check for execution of untrusted input.
Security injection

Line: 37
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html

                  # Upload releases to PyPI
    if tag:
        whl, = Path("release/dist/").glob('mitmproxy-*-py3-none-any.whl')
        subprocess.check_call(["twine", "upload", whl])

    # Upload dev docs
    if branch == "main" or branch == "actions-hardening":  # FIXME remove
        subprocess.check_call([
            "aws", "configure",

            

Reported by Bandit.

Starting a process with a partial executable path
Security injection

Line: 37
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b607_start_process_with_partial_path.html

                  # Upload releases to PyPI
    if tag:
        whl, = Path("release/dist/").glob('mitmproxy-*-py3-none-any.whl')
        subprocess.check_call(["twine", "upload", whl])

    # Upload dev docs
    if branch == "main" or branch == "actions-hardening":  # FIXME remove
        subprocess.check_call([
            "aws", "configure",

            

Reported by Bandit.

Consider merging these comparisons with "in" to "branch in ('main', 'actions-hardening')"
Error

Line: 40 Column: 8

                      subprocess.check_call(["twine", "upload", whl])

    # Upload dev docs
    if branch == "main" or branch == "actions-hardening":  # FIXME remove
        subprocess.check_call([
            "aws", "configure",
            "set", "preview.cloudfront", "true"
        ])
        subprocess.check_call([

            

Reported by Pylint.

Starting a process with a partial executable path
Security injection

Line: 41
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b607_start_process_with_partial_path.html

              
    # Upload dev docs
    if branch == "main" or branch == "actions-hardening":  # FIXME remove
        subprocess.check_call([
            "aws", "configure",
            "set", "preview.cloudfront", "true"
        ])
        subprocess.check_call([
            "aws", "s3",

            

Reported by Bandit.

test/helper_tools/dumperview.py
15 issues
Unable to import 'mitmproxy.addons'
Error

Line: 4 Column: 1

              #!/usr/bin/env python3
import click

from mitmproxy.addons import dumper
from mitmproxy.test import tflow
from mitmproxy.test import taddons


def show(flow_detail, flows):

            

Reported by Pylint.

Unable to import 'mitmproxy.test'
Error

Line: 5 Column: 1

              import click

from mitmproxy.addons import dumper
from mitmproxy.test import tflow
from mitmproxy.test import taddons


def show(flow_detail, flows):
    d = dumper.Dumper()

            

Reported by Pylint.

Unable to import 'mitmproxy.test'
Error

Line: 6 Column: 1

              
from mitmproxy.addons import dumper
from mitmproxy.test import tflow
from mitmproxy.test import taddons


def show(flow_detail, flows):
    d = dumper.Dumper()
    with taddons.context() as ctx:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3
import click

from mitmproxy.addons import dumper
from mitmproxy.test import tflow
from mitmproxy.test import taddons


def show(flow_detail, flows):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 9 Column: 1

              from mitmproxy.test import taddons


def show(flow_detail, flows):
    d = dumper.Dumper()
    with taddons.context() as ctx:
        ctx.configure(d, flow_detail=flow_detail)
        for f in flows:
            ctx.cycle(d, f)

            

Reported by Pylint.

Variable name "d" doesn't conform to snake_case naming style
Error

Line: 10 Column: 5

              

def show(flow_detail, flows):
    d = dumper.Dumper()
    with taddons.context() as ctx:
        ctx.configure(d, flow_detail=flow_detail)
        for f in flows:
            ctx.cycle(d, f)


            

Reported by Pylint.

Variable name "f" doesn't conform to snake_case naming style
Error

Line: 13 Column: 13

                  d = dumper.Dumper()
    with taddons.context() as ctx:
        ctx.configure(d, flow_detail=flow_detail)
        for f in flows:
            ctx.cycle(d, f)


@click.group()
def cli():

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 18 Column: 1

              

@click.group()
def cli():
    pass


@cli.command()
@click.option('--level', default=1, help='Detail level')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 24 Column: 1

              
@cli.command()
@click.option('--level', default=1, help='Detail level')
def tcp(level):
    f1 = tflow.ttcpflow(client_conn=True, server_conn=True)
    show(level, [f1])


@cli.command()

            

Reported by Pylint.

Variable name "f1" doesn't conform to snake_case naming style
Error

Line: 25 Column: 5

              @cli.command()
@click.option('--level', default=1, help='Detail level')
def tcp(level):
    f1 = tflow.ttcpflow(client_conn=True, server_conn=True)
    show(level, [f1])


@cli.command()
@click.option('--level', default=1, help='Detail level')

            

Reported by Pylint.

test/mitmproxy/addons/test_disable_h2c.py
15 issues
Missing module docstring
Error

Line: 1 Column: 1

              from mitmproxy import flow
from mitmproxy.addons import disable_h2c
from mitmproxy.test import taddons, tutils
from mitmproxy.test import tflow


class TestDisableH2CleartextUpgrade:
    def test_upgrade(self):
        with taddons.context() as tctx:

            

Reported by Pylint.

Missing class docstring
Error

Line: 7 Column: 1

              from mitmproxy.test import tflow


class TestDisableH2CleartextUpgrade:
    def test_upgrade(self):
        with taddons.context() as tctx:
            a = disable_h2c.DisableH2C()
            tctx.configure(a)


            

Reported by Pylint.

Method could be a function
Error

Line: 8 Column: 5

              

class TestDisableH2CleartextUpgrade:
    def test_upgrade(self):
        with taddons.context() as tctx:
            a = disable_h2c.DisableH2C()
            tctx.configure(a)

            f = tflow.tflow()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 8 Column: 5

              

class TestDisableH2CleartextUpgrade:
    def test_upgrade(self):
        with taddons.context() as tctx:
            a = disable_h2c.DisableH2C()
            tctx.configure(a)

            f = tflow.tflow()

            

Reported by Pylint.

Variable name "a" doesn't conform to snake_case naming style
Error

Line: 10 Column: 13

              class TestDisableH2CleartextUpgrade:
    def test_upgrade(self):
        with taddons.context() as tctx:
            a = disable_h2c.DisableH2C()
            tctx.configure(a)

            f = tflow.tflow()
            f.request.headers['upgrade'] = 'h2c'
            f.request.headers['connection'] = 'foo'

            

Reported by Pylint.

Variable name "f" doesn't conform to snake_case naming style
Error

Line: 13 Column: 13

                          a = disable_h2c.DisableH2C()
            tctx.configure(a)

            f = tflow.tflow()
            f.request.headers['upgrade'] = 'h2c'
            f.request.headers['connection'] = 'foo'
            f.request.headers['http2-settings'] = 'bar'

            a.request(f)

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 19
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                          f.request.headers['http2-settings'] = 'bar'

            a.request(f)
            assert 'upgrade' not in f.request.headers
            assert 'connection' not in f.request.headers
            assert 'http2-settings' not in f.request.headers

    def test_prior_knowledge(self):
        with taddons.context() as tctx:

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 20
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
            a.request(f)
            assert 'upgrade' not in f.request.headers
            assert 'connection' not in f.request.headers
            assert 'http2-settings' not in f.request.headers

    def test_prior_knowledge(self):
        with taddons.context() as tctx:
            a = disable_h2c.DisableH2C()

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 21
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                          a.request(f)
            assert 'upgrade' not in f.request.headers
            assert 'connection' not in f.request.headers
            assert 'http2-settings' not in f.request.headers

    def test_prior_knowledge(self):
        with taddons.context() as tctx:
            a = disable_h2c.DisableH2C()
            tctx.configure(a)

            

Reported by Bandit.

Method could be a function
Error

Line: 23 Column: 5

                          assert 'connection' not in f.request.headers
            assert 'http2-settings' not in f.request.headers

    def test_prior_knowledge(self):
        with taddons.context() as tctx:
            a = disable_h2c.DisableH2C()
            tctx.configure(a)

            f = tflow.tflow()

            

Reported by Pylint.

test/mitmproxy/addons/test_keepserving.py
15 issues
Unable to import 'pytest'
Error

Line: 2 Column: 1

              import asyncio
import pytest

from mitmproxy.addons import keepserving
from mitmproxy.test import taddons
from mitmproxy import command


class Dummy:

            

Reported by Pylint.

Attribute 'is_shutdown' defined outside __init__
Error

Line: 35 Column: 9

                  _is_shutdown = False

    def shutdown(self):
        self.is_shutdown = True


@pytest.mark.asyncio
async def test_keepserving():
    ks = TKS()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import asyncio
import pytest

from mitmproxy.addons import keepserving
from mitmproxy.test import taddons
from mitmproxy import command


class Dummy:

            

Reported by Pylint.

Missing class docstring
Error

Line: 9 Column: 1

              from mitmproxy import command


class Dummy:
    def __init__(self, val: bool):
        self.val = val

    def load(self, loader):
        loader.add_option("client_replay", bool, self.val, "test")

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

                  def __init__(self, val: bool):
        self.val = val

    def load(self, loader):
        loader.add_option("client_replay", bool, self.val, "test")
        loader.add_option("server_replay", bool, self.val, "test")
        loader.add_option("rfile", bool, self.val, "test")

    @command.command("readfile.reading")

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 5

                      loader.add_option("rfile", bool, self.val, "test")

    @command.command("readfile.reading")
    def readfile(self) -> bool:
        return self.val

    @command.command("replay.client.count")
    def creplay(self) -> int:
        return 1 if self.val else 0

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 23 Column: 5

                      return self.val

    @command.command("replay.client.count")
    def creplay(self) -> int:
        return 1 if self.val else 0

    @command.command("replay.server.count")
    def sreplay(self) -> int:
        return 1 if self.val else 0

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 27 Column: 5

                      return 1 if self.val else 0

    @command.command("replay.server.count")
    def sreplay(self) -> int:
        return 1 if self.val else 0


class TKS(keepserving.KeepServing):
    _is_shutdown = False

            

Reported by Pylint.

Missing class docstring
Error

Line: 31 Column: 1

                      return 1 if self.val else 0


class TKS(keepserving.KeepServing):
    _is_shutdown = False

    def shutdown(self):
        self.is_shutdown = True


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 39 Column: 1

              

@pytest.mark.asyncio
async def test_keepserving():
    ks = TKS()
    d = Dummy(True)
    with taddons.context(ks) as tctx:
        tctx.master.addons.add(d)
        ks.running()

            

Reported by Pylint.

test/mitmproxy/contentviews/test_base.py
14 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest
from mitmproxy.contentviews import base


def test_format_dict():
    d = {"one": "two", "three": "four"}
    f_d = base.format_dict(d)
    assert next(f_d)


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest
from mitmproxy.contentviews import base


def test_format_dict():
    d = {"one": "two", "three": "four"}
    f_d = base.format_dict(d)
    assert next(f_d)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 5 Column: 1

              from mitmproxy.contentviews import base


def test_format_dict():
    d = {"one": "two", "three": "four"}
    f_d = base.format_dict(d)
    assert next(f_d)

    d = {"adsfa": ""}

            

Reported by Pylint.

Variable name "d" doesn't conform to snake_case naming style
Error

Line: 6 Column: 5

              

def test_format_dict():
    d = {"one": "two", "three": "four"}
    f_d = base.format_dict(d)
    assert next(f_d)

    d = {"adsfa": ""}
    f_d = base.format_dict(d)

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 8
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              def test_format_dict():
    d = {"one": "two", "three": "four"}
    f_d = base.format_dict(d)
    assert next(f_d)

    d = {"adsfa": ""}
    f_d = base.format_dict(d)
    assert next(f_d)


            

Reported by Bandit.

Variable name "d" doesn't conform to snake_case naming style
Error

Line: 10 Column: 5

                  f_d = base.format_dict(d)
    assert next(f_d)

    d = {"adsfa": ""}
    f_d = base.format_dict(d)
    assert next(f_d)

    d = {}
    f_d = base.format_dict(d)

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 12
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
    d = {"adsfa": ""}
    f_d = base.format_dict(d)
    assert next(f_d)

    d = {}
    f_d = base.format_dict(d)
    with pytest.raises(StopIteration):
        next(f_d)

            

Reported by Bandit.

Variable name "d" doesn't conform to snake_case naming style
Error

Line: 14 Column: 5

                  f_d = base.format_dict(d)
    assert next(f_d)

    d = {}
    f_d = base.format_dict(d)
    with pytest.raises(StopIteration):
        next(f_d)



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 20 Column: 1

                      next(f_d)


def test_format_pairs():
    d = [("a", "c"), ("b", "d")]
    f_d = base.format_pairs(d)
    assert next(f_d)

    d = [("abc", "")]

            

Reported by Pylint.

Variable name "d" doesn't conform to snake_case naming style
Error

Line: 21 Column: 5

              

def test_format_pairs():
    d = [("a", "c"), ("b", "d")]
    f_d = base.format_pairs(d)
    assert next(f_d)

    d = [("abc", "")]
    f_d = base.format_pairs(d)

            

Reported by Pylint.

mitmproxy/tools/console/eventlog.py
14 issues
Unable to import 'urwid'
Error

Line: 3 Column: 1

              import collections

import urwid
from mitmproxy.tools.console import layoutwidget
from mitmproxy import log


class LogBufferWalker(urwid.SimpleListWalker):
    pass

            

Reported by Pylint.

Unused argument 'event_store'
Error

Line: 46 Column: 25

                          self.set_focus(0)
        return super().keypress(size, key)

    def add_event(self, event_store, entry: log.LogEntry):
        if log.log_tier(self.master.options.console_eventlog_verbosity) < log.log_tier(entry.level):
            return
        txt = "{}: {}".format(entry.level, str(entry.msg))
        if entry.level in ("error", "warn", "alert"):
            e = urwid.Text((entry.level, txt))

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import collections

import urwid
from mitmproxy.tools.console import layoutwidget
from mitmproxy import log


class LogBufferWalker(urwid.SimpleListWalker):
    pass

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 8 Column: 1

              from mitmproxy import log


class LogBufferWalker(urwid.SimpleListWalker):
    pass


class EventLog(urwid.ListBox, layoutwidget.LayoutWidget):
    keyctx = "eventlog"

            

Reported by Pylint.

Missing class docstring
Error

Line: 8 Column: 1

              from mitmproxy import log


class LogBufferWalker(urwid.SimpleListWalker):
    pass


class EventLog(urwid.ListBox, layoutwidget.LayoutWidget):
    keyctx = "eventlog"

            

Reported by Pylint.

Missing class docstring
Error

Line: 12 Column: 1

                  pass


class EventLog(urwid.ListBox, layoutwidget.LayoutWidget):
    keyctx = "eventlog"
    title = "Events"

    def __init__(self, master):
        self.master = master

            

Reported by Pylint.

Method could be a function
Error

Line: 29 Column: 5

              
        super().__init__(self.walker)

    def load(self, loader):
        loader.add_option(
            "console_focus_follow", bool, False,
            "Focus follows new flows."
        )


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 29 Column: 5

              
        super().__init__(self.walker)

    def load(self, loader):
        loader.add_option(
            "console_focus_follow", bool, False,
            "Focus follows new flows."
        )


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 35 Column: 5

                          "Focus follows new flows."
        )

    def set_focus(self, index):
        if 0 <= index < len(self.walker):
            super().set_focus(index)

    def keypress(self, size, key):
        if key == "m_end":

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 39 Column: 5

                      if 0 <= index < len(self.walker):
            super().set_focus(index)

    def keypress(self, size, key):
        if key == "m_end":
            self.set_focus(len(self.walker) - 1)
        elif key == "m_start":
            self.set_focus(0)
        return super().keypress(size, key)

            

Reported by Pylint.

test/mitmproxy/tservers.py
14 issues
Unused variable 'i'
Error

Line: 25 Column: 13

                      return f

    async def dummy_cycle(self, master, n, content):
        for i in range(n):
            await self.cycle(master, content)
        await master._shutdown()

    def flowfile(self, path):
        with open(path, "wb") as f:

            

Reported by Pylint.

Access to a protected member _shutdown of a client class
Error

Line: 27 Column: 15

                  async def dummy_cycle(self, master, n, content):
        for i in range(n):
            await self.cycle(master, content)
        await master._shutdown()

    def flowfile(self, path):
        with open(path, "wb") as f:
            fw = io.FlowWriter(f)
            t = tflow.tflow(resp=True)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from unittest import mock

from mitmproxy import controller
from mitmproxy import eventsequence
from mitmproxy import io
from mitmproxy.proxy import server_hooks
from mitmproxy.test import tflow
from mitmproxy.test import tutils


            

Reported by Pylint.

Missing class docstring
Error

Line: 11 Column: 1

              from mitmproxy.test import tutils


class MasterTest:

    async def cycle(self, master, content):
        f = tflow.tflow(req=tutils.treq(content=content))
        layer = mock.Mock("mitmproxy.proxy.protocol.base.Layer")
        layer.client_conn = f.client_conn

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

              
class MasterTest:

    async def cycle(self, master, content):
        f = tflow.tflow(req=tutils.treq(content=content))
        layer = mock.Mock("mitmproxy.proxy.protocol.base.Layer")
        layer.client_conn = f.client_conn
        layer.reply = controller.DummyReply()
        await master.addons.handle_lifecycle(server_hooks.ClientConnectedHook(layer))

            

Reported by Pylint.

Variable name "f" doesn't conform to snake_case naming style
Error

Line: 14 Column: 9

              class MasterTest:

    async def cycle(self, master, content):
        f = tflow.tflow(req=tutils.treq(content=content))
        layer = mock.Mock("mitmproxy.proxy.protocol.base.Layer")
        layer.client_conn = f.client_conn
        layer.reply = controller.DummyReply()
        await master.addons.handle_lifecycle(server_hooks.ClientConnectedHook(layer))
        for e in eventsequence.iterate(f):

            

Reported by Pylint.

Variable name "e" doesn't conform to snake_case naming style
Error

Line: 19 Column: 13

                      layer.client_conn = f.client_conn
        layer.reply = controller.DummyReply()
        await master.addons.handle_lifecycle(server_hooks.ClientConnectedHook(layer))
        for e in eventsequence.iterate(f):
            await master.addons.handle_lifecycle(e)
        await master.addons.handle_lifecycle(server_hooks.ClientDisconnectedHook(layer))
        return f

    async def dummy_cycle(self, master, n, content):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 24 Column: 5

                      await master.addons.handle_lifecycle(server_hooks.ClientDisconnectedHook(layer))
        return f

    async def dummy_cycle(self, master, n, content):
        for i in range(n):
            await self.cycle(master, content)
        await master._shutdown()

    def flowfile(self, path):

            

Reported by Pylint.

Argument name "n" doesn't conform to snake_case naming style
Error

Line: 24 Column: 5

                      await master.addons.handle_lifecycle(server_hooks.ClientDisconnectedHook(layer))
        return f

    async def dummy_cycle(self, master, n, content):
        for i in range(n):
            await self.cycle(master, content)
        await master._shutdown()

    def flowfile(self, path):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 29 Column: 5

                          await self.cycle(master, content)
        await master._shutdown()

    def flowfile(self, path):
        with open(path, "wb") as f:
            fw = io.FlowWriter(f)
            t = tflow.tflow(resp=True)
            fw.add(t)

            

Reported by Pylint.

mitmproxy/proxy/layers/http/_upstream_proxy.py
14 issues
Unable to import 'h11._receivebuffer'
Error

Line: 4 Column: 1

              import time
from typing import Optional, Tuple

from h11._receivebuffer import ReceiveBuffer

from mitmproxy import http, connection
from mitmproxy.net.http import http1
from mitmproxy.proxy import commands, context, layer, tunnel
from mitmproxy.proxy.layers.http._hooks import HttpConnectUpstreamHook

            

Reported by Pylint.

TODO: Make url.parse compatible with bytearrays
Error

Line: 80 Column: 3

                      self.buf += data
        response_head = self.buf.maybe_extract_lines()
        if response_head:
            response_head = [bytes(x) for x in response_head]  # TODO: Make url.parse compatible with bytearrays
            try:
                response = http1.read_response_head(response_head)
            except ValueError as e:
                proxyaddr = human.format_address(self.tunnel_connection.address)
                yield commands.Log(f"{proxyaddr}: {e}")

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import time
from typing import Optional, Tuple

from h11._receivebuffer import ReceiveBuffer

from mitmproxy import http, connection
from mitmproxy.net.http import http1
from mitmproxy.proxy import commands, context, layer, tunnel
from mitmproxy.proxy.layers.http._hooks import HttpConnectUpstreamHook

            

Reported by Pylint.

Missing class docstring
Error

Line: 14 Column: 1

              from mitmproxy.utils import human


class HttpUpstreamProxy(tunnel.TunnelLayer):
    buf: ReceiveBuffer
    send_connect: bool
    conn: connection.Server
    tunnel_connection: connection.Server


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 35 Column: 5

                      self.send_connect = send_connect

    @classmethod
    def make(cls, ctx: context.Context, send_connect: bool) -> tunnel.LayerStack:
        spec = ctx.server.via
        assert spec
        assert spec.scheme in ("http", "https")

        http_proxy = connection.Server(spec.address)

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 37
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  @classmethod
    def make(cls, ctx: context.Context, send_connect: bool) -> tunnel.LayerStack:
        spec = ctx.server.via
        assert spec
        assert spec.scheme in ("http", "https")

        http_proxy = connection.Server(spec.address)

        stack = tunnel.LayerStack()

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 38
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  def make(cls, ctx: context.Context, send_connect: bool) -> tunnel.LayerStack:
        spec = ctx.server.via
        assert spec
        assert spec.scheme in ("http", "https")

        http_proxy = connection.Server(spec.address)

        stack = tunnel.LayerStack()
        if spec.scheme == "https":

            

Reported by Bandit.

Either all return statements in a function should return an expression, or none of them should.
Error

Line: 51 Column: 5

              
        return stack

    def start_handshake(self) -> layer.CommandGenerator[None]:
        if not self.send_connect:
            return (yield from super().start_handshake())
        assert self.conn.address
        flow = http.HTTPFlow(self.context.client, self.tunnel_connection)
        flow.request = http.Request(

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 54
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  def start_handshake(self) -> layer.CommandGenerator[None]:
        if not self.send_connect:
            return (yield from super().start_handshake())
        assert self.conn.address
        flow = http.HTTPFlow(self.context.client, self.tunnel_connection)
        flow.request = http.Request(
            host=self.conn.address[0],
            port=self.conn.address[1],
            method=b"CONNECT",

            

Reported by Bandit.

Line too long (104/100)
Error

Line: 74 Column: 1

                      raw = http1.assemble_request(flow.request)
        yield commands.SendData(self.tunnel_connection, raw)

    def receive_handshake_data(self, data: bytes) -> layer.CommandGenerator[Tuple[bool, Optional[str]]]:
        if not self.send_connect:
            return (yield from super().receive_handshake_data(data))
        self.buf += data
        response_head = self.buf.maybe_extract_lines()
        if response_head:

            

Reported by Pylint.