The following issues were found

mitmproxy/proxy/layers/__init__.py
6 issues
Unable to import '__init__.http'
Error

Line: 2 Column: 1

              from . import modes
from .http import HttpLayer
from .tcp import TCPLayer
from .tls import ClientTLSLayer, ServerTLSLayer
from .websocket import WebsocketLayer

__all__ = [
    "modes",
    "HttpLayer",

            

Reported by Pylint.

Unable to import '__init__.tcp'
Error

Line: 3 Column: 1

              from . import modes
from .http import HttpLayer
from .tcp import TCPLayer
from .tls import ClientTLSLayer, ServerTLSLayer
from .websocket import WebsocketLayer

__all__ = [
    "modes",
    "HttpLayer",

            

Reported by Pylint.

Unable to import '__init__.tls'
Error

Line: 4 Column: 1

              from . import modes
from .http import HttpLayer
from .tcp import TCPLayer
from .tls import ClientTLSLayer, ServerTLSLayer
from .websocket import WebsocketLayer

__all__ = [
    "modes",
    "HttpLayer",

            

Reported by Pylint.

Unable to import '__init__.websocket'
Error

Line: 5 Column: 1

              from .http import HttpLayer
from .tcp import TCPLayer
from .tls import ClientTLSLayer, ServerTLSLayer
from .websocket import WebsocketLayer

__all__ = [
    "modes",
    "HttpLayer",
    "TCPLayer",

            

Reported by Pylint.

Module import itself
Error

Line: 1 Column: 1

              from . import modes
from .http import HttpLayer
from .tcp import TCPLayer
from .tls import ClientTLSLayer, ServerTLSLayer
from .websocket import WebsocketLayer

__all__ = [
    "modes",
    "HttpLayer",

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from . import modes
from .http import HttpLayer
from .tcp import TCPLayer
from .tls import ClientTLSLayer, ServerTLSLayer
from .websocket import WebsocketLayer

__all__ = [
    "modes",
    "HttpLayer",

            

Reported by Pylint.

mitmproxy/addons/termlog.py
6 issues
Missing module docstring
Error

Line: 1 Column: 1

              from typing import IO, Optional

import click

from mitmproxy import log
from mitmproxy import ctx


class TermLog:

            

Reported by Pylint.

Missing class docstring
Error

Line: 9 Column: 1

              from mitmproxy import ctx


class TermLog:
    def __init__(self, outfile=None):
        self.outfile: Optional[IO] = outfile

    def load(self, loader):
        loader.add_option(

            

Reported by Pylint.

Method could be a function
Error

Line: 13 Column: 5

                  def __init__(self, outfile=None):
        self.outfile: Optional[IO] = outfile

    def load(self, loader):
        loader.add_option(
            "termlog_verbosity", str, 'info',
            "Log verbosity.",
            choices=log.LogTierOrder
        )

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

                  def __init__(self, outfile=None):
        self.outfile: Optional[IO] = outfile

    def load(self, loader):
        loader.add_option(
            "termlog_verbosity", str, 'info',
            "Log verbosity.",
            choices=log.LogTierOrder
        )

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 20 Column: 5

                          choices=log.LogTierOrder
        )

    def add_log(self, e):
        if log.log_tier(ctx.options.termlog_verbosity) >= log.log_tier(e.level):
            click.secho(
                e.msg,
                file=self.outfile,
                fg=dict(error="red", warn="yellow",

            

Reported by Pylint.

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

Line: 20 Column: 5

                          choices=log.LogTierOrder
        )

    def add_log(self, e):
        if log.log_tier(ctx.options.termlog_verbosity) >= log.log_tier(e.level):
            click.secho(
                e.msg,
                file=self.outfile,
                fg=dict(error="red", warn="yellow",

            

Reported by Pylint.

docs/build.py
6 issues
Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3
import shutil
import subprocess
from pathlib import Path


here = Path(__file__).parent

for script in sorted((here / "scripts").glob("*.py")):

            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

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

              #!/usr/bin/env python3
import shutil
import subprocess
from pathlib import Path


here = Path(__file__).parent

for script in sorted((here / "scripts").glob("*.py")):

            

Reported by Bandit.

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

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

              
for script in sorted((here / "scripts").glob("*.py")):
    print(f"Generating output for {script.name}...")
    out = subprocess.check_output(["python3", script.absolute()], cwd=here, text=True)
    if out:
        (here / "src" / "generated" / f"{script.stem}.html").write_text(out, encoding="utf8")

if (here / "public").exists():
    shutil.rmtree(here / "public")

            

Reported by Bandit.

Starting a process with a partial executable path
Security injection

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

              
for script in sorted((here / "scripts").glob("*.py")):
    print(f"Generating output for {script.name}...")
    out = subprocess.check_output(["python3", script.absolute()], cwd=here, text=True)
    if out:
        (here / "src" / "generated" / f"{script.stem}.html").write_text(out, encoding="utf8")

if (here / "public").exists():
    shutil.rmtree(here / "public")

            

Reported by Bandit.

Starting a process with a partial executable path
Security injection

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

              
if (here / "public").exists():
    shutil.rmtree(here / "public")
subprocess.run(["hugo"], cwd=here / "src", check=True)

            

Reported by Bandit.

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

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

              
if (here / "public").exists():
    shutil.rmtree(here / "public")
subprocess.run(["hugo"], cwd=here / "src", check=True)

            

Reported by Bandit.

mitmproxy/platform/__init__.py
6 issues
Module import itself
Error

Line: 20 Column: 5

              """

if re.match(r"linux(?:2)?", sys.platform):
    from . import linux

    original_addr = linux.original_addr
elif sys.platform == "darwin" or sys.platform.startswith("freebsd"):
    from . import osx


            

Reported by Pylint.

Module import itself
Error

Line: 24 Column: 5

              
    original_addr = linux.original_addr
elif sys.platform == "darwin" or sys.platform.startswith("freebsd"):
    from . import osx

    original_addr = osx.original_addr
elif sys.platform.startswith("openbsd"):
    from . import openbsd


            

Reported by Pylint.

Module import itself
Error

Line: 28 Column: 5

              
    original_addr = osx.original_addr
elif sys.platform.startswith("openbsd"):
    from . import openbsd

    original_addr = openbsd.original_addr
elif sys.platform == "win32":
    from . import windows


            

Reported by Pylint.

Module import itself
Error

Line: 32 Column: 5

              
    original_addr = openbsd.original_addr
elif sys.platform == "win32":
    from . import windows

    resolver = windows.Resolver()
    init_transparent_mode = resolver.setup  # noqa
    original_addr = resolver.original_addr
else:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import re
import socket
import sys
from typing import Callable, Optional, Tuple


def init_transparent_mode() -> None:
    """
    Initialize transparent mode.

            

Reported by Pylint.

Constant name "original_addr" doesn't conform to UPPER_CASE naming style
Error

Line: 38 Column: 5

                  init_transparent_mode = resolver.setup  # noqa
    original_addr = resolver.original_addr
else:
    original_addr = None

__all__ = [
    "original_addr",
    "init_transparent_mode"
]

            

Reported by Pylint.

examples/addons/io-read-saved-flows.py
6 issues
Unable to import 'mitmproxy'
Error

Line: 5 Column: 1

              """
Read a mitmproxy dump file.
"""
from mitmproxy import io, http
from mitmproxy.exceptions import FlowReadException
import pprint
import sys

with open(sys.argv[1], "rb") as logfile:

            

Reported by Pylint.

Unable to import 'mitmproxy.exceptions'
Error

Line: 6 Column: 1

              Read a mitmproxy dump file.
"""
from mitmproxy import io, http
from mitmproxy.exceptions import FlowReadException
import pprint
import sys

with open(sys.argv[1], "rb") as logfile:
    freader = io.FlowReader(logfile)

            

Reported by Pylint.

Module name "io-read-saved-flows" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              #!/usr/bin/env python
"""
Read a mitmproxy dump file.
"""
from mitmproxy import io, http
from mitmproxy.exceptions import FlowReadException
import pprint
import sys


            

Reported by Pylint.

standard import "import pprint" should be placed before "from mitmproxy import io, http"
Error

Line: 7 Column: 1

              """
from mitmproxy import io, http
from mitmproxy.exceptions import FlowReadException
import pprint
import sys

with open(sys.argv[1], "rb") as logfile:
    freader = io.FlowReader(logfile)
    pp = pprint.PrettyPrinter(indent=4)

            

Reported by Pylint.

standard import "import sys" should be placed before "from mitmproxy import io, http"
Error

Line: 8 Column: 1

              from mitmproxy import io, http
from mitmproxy.exceptions import FlowReadException
import pprint
import sys

with open(sys.argv[1], "rb") as logfile:
    freader = io.FlowReader(logfile)
    pp = pprint.PrettyPrinter(indent=4)
    try:

            

Reported by Pylint.

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

Line: 20 Column: 5

                              print(f.request.host)
            pp.pprint(f.get_state())
            print("")
    except FlowReadException as e:
        print(f"Flow file corrupted: {e}")

            

Reported by Pylint.

test/mitmproxy/data/addonscripts/recorder/recorder.py
6 issues
Unable to import 'mitmproxy'
Error

Line: 1 Column: 1

              from mitmproxy import ctx
from mitmproxy import hooks


class Recorder:
    call_log = []

    def __init__(self, name="recorder"):
        self.name = name

            

Reported by Pylint.

Unable to import 'mitmproxy'
Error

Line: 2 Column: 1

              from mitmproxy import ctx
from mitmproxy import hooks


class Recorder:
    call_log = []

    def __init__(self, name="recorder"):
        self.name = name

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from mitmproxy import ctx
from mitmproxy import hooks


class Recorder:
    call_log = []

    def __init__(self, name="recorder"):
        self.name = name

            

Reported by Pylint.

Missing class docstring
Error

Line: 5 Column: 1

              from mitmproxy import hooks


class Recorder:
    call_log = []

    def __init__(self, name="recorder"):
        self.name = name


            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 5 Column: 1

              from mitmproxy import hooks


class Recorder:
    call_log = []

    def __init__(self, name="recorder"):
        self.name = name


            

Reported by Pylint.

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

Line: 14 Column: 17

                  def __getattr__(self, attr):
        if attr in hooks.all_hooks:
            def prox(*args, **kwargs):
                lg = (self.name, attr, args, kwargs)
                if attr != "add_log":
                    ctx.log.info(str(lg))
                    self.call_log.append(lg)
                    ctx.log.debug(f"{self.name} {attr}")


            

Reported by Pylint.

examples/addons/options-simple.py
6 issues
Unable to import 'mitmproxy'
Error

Line: 8 Column: 1

              
    mitmproxy -s options-simple.py --set addheader true
"""
from mitmproxy import ctx


class AddHeader:
    def __init__(self):
        self.num = 0

            

Reported by Pylint.

Module name "options-simple" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              """
Add a new mitmproxy option.

Usage:

    mitmproxy -s options-simple.py --set addheader true
"""
from mitmproxy import ctx


            

Reported by Pylint.

Missing class docstring
Error

Line: 11 Column: 1

              from mitmproxy import ctx


class AddHeader:
    def __init__(self):
        self.num = 0

    def load(self, loader):
        loader.add_option(

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 15 Column: 5

                  def __init__(self):
        self.num = 0

    def load(self, loader):
        loader.add_option(
            name = "addheader",
            typespec = bool,
            default = False,
            help = "Add a count header to responses",

            

Reported by Pylint.

Method could be a function
Error

Line: 15 Column: 5

                  def __init__(self):
        self.num = 0

    def load(self, loader):
        loader.add_option(
            name = "addheader",
            typespec = bool,
            default = False,
            help = "Add a count header to responses",

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 23 Column: 5

                          help = "Add a count header to responses",
        )

    def response(self, flow):
        if ctx.options.addheader:
            self.num = self.num + 1
            flow.response.headers["count"] = str(self.num)



            

Reported by Pylint.

test/conftest.py
6 issues
Unable to import 'pytest'
Error

Line: 6 Column: 1

              
from mitmproxy.utils import data

import pytest

pytest_plugins = ('test.full_coverage_plugin',)

skip_windows = pytest.mark.skipif(
    os.name == "nt",

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
import socket

from mitmproxy.utils import data

import pytest

pytest_plugins = ('test.full_coverage_plugin',)


            

Reported by Pylint.

third party import "import pytest" should be placed before "from mitmproxy.utils import data"
Error

Line: 6 Column: 1

              
from mitmproxy.utils import data

import pytest

pytest_plugins = ('test.full_coverage_plugin',)

skip_windows = pytest.mark.skipif(
    os.name == "nt",

            

Reported by Pylint.

Constant name "no_ipv6" doesn't conform to UPPER_CASE naming style
Error

Line: 25 Column: 5

                  s.bind(("::1", 0))
    s.close()
except OSError:
    no_ipv6 = True
else:
    no_ipv6 = False

skip_no_ipv6 = pytest.mark.skipif(
    no_ipv6,

            

Reported by Pylint.

Constant name "no_ipv6" doesn't conform to UPPER_CASE naming style
Error

Line: 27 Column: 5

              except OSError:
    no_ipv6 = True
else:
    no_ipv6 = False

skip_no_ipv6 = pytest.mark.skipif(
    no_ipv6,
    reason='Host has no IPv6 support'
)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 36 Column: 1

              

@pytest.fixture()
def tdata():
    return data.Data(__name__)

            

Reported by Pylint.

setup.py
6 issues
Redefining built-in 'open'
Error

Line: 3 Column: 1

              import os
import re
from codecs import open

from setuptools import find_packages, setup

# Based on https://github.com/pypa/sampleproject/blob/main/setup.py
# and https://python-packaging-user-guide.readthedocs.org/


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
import re
from codecs import open

from setuptools import find_packages, setup

# Based on https://github.com/pypa/sampleproject/blob/main/setup.py
# and https://python-packaging-user-guide.readthedocs.org/


            

Reported by Pylint.

Constant name "long_description_content_type" doesn't conform to UPPER_CASE naming style
Error

Line: 14 Column: 1

              
with open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()
long_description_content_type = "text/markdown"

with open(os.path.join(here, "mitmproxy", "version.py")) as f:
    match = re.search(r'VERSION = "(.+?)"', f.read())
    assert match
    VERSION = match.group(1)

            

Reported by Pylint.

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

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

              
with open(os.path.join(here, "mitmproxy", "version.py")) as f:
    match = re.search(r'VERSION = "(.+?)"', f.read())
    assert match
    VERSION = match.group(1)

setup(
    name="mitmproxy",
    version=VERSION,

            

Reported by Bandit.

Line too long (105/100)
Error

Line: 24 Column: 1

              setup(
    name="mitmproxy",
    version=VERSION,
    description="An interactive, SSL/TLS-capable intercepting proxy for HTTP/1, HTTP/2, and WebSockets.",
    long_description=long_description,
    long_description_content_type=long_description_content_type,
    url="http://mitmproxy.org",
    author="Aldo Cortesi",
    author_email="aldo@corte.si",

            

Reported by Pylint.

Line too long (106/100)
Error

Line: 67 Column: 1

                  },
    python_requires='>=3.8',
    # https://packaging.python.org/en/latest/requirements/#install-requires
    # It is not considered best practice to use install_requires to pin dependencies to specific versions.
    install_requires=[
        "asgiref>=3.2.10,<3.5",
        "blinker>=1.4, <1.5",
        "Brotli>=1.0,<1.1",
        "certifi>=2019.9.11",  # no semver here - this should always be on the last release!

            

Reported by Pylint.

mitmproxy/command_lexer.py
6 issues
TODO: There is a lot of work to be done here.
Error

Line: 5 Column: 3

              
import pyparsing

# TODO: There is a lot of work to be done here.
# The current implementation is written in a way that _any_ input is valid,
# which does not make sense once things get more complex.

PartialQuotedString = pyparsing.Regex(
    re.compile(

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import re

import pyparsing

# TODO: There is a lot of work to be done here.
# The current implementation is written in a way that _any_ input is valid,
# which does not make sense once things get more complex.

PartialQuotedString = pyparsing.Regex(

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 27 Column: 1

              ).leaveWhitespace()


def quote(val: str) -> str:
    if val and all(char not in val for char in "'\" \r\n\t"):
        return val
    if '"' not in val:
        return f'"{val}"'
    if "'" not in val:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 37 Column: 1

                  return '"' + val.replace('"', r"\x22") + '"'


def unquote(x: str) -> str:
    if len(x) > 1 and x[0] in "'\"" and x[0] == x[-1]:
        return x[1:-1]
    else:
        return x

            

Reported by Pylint.

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

Line: 37 Column: 1

                  return '"' + val.replace('"', r"\x22") + '"'


def unquote(x: str) -> str:
    if len(x) > 1 and x[0] in "'\"" and x[0] == x[-1]:
        return x[1:-1]
    else:
        return x

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 38 Column: 5

              

def unquote(x: str) -> str:
    if len(x) > 1 and x[0] in "'\"" and x[0] == x[-1]:
        return x[1:-1]
    else:
        return x

            

Reported by Pylint.