The following issues were found

mitmproxy/types.py
69 issues
Method '__getitem__' is abstract in class 'Sequence' but is not overridden
Error

Line: 35 Column: 1

                  pass


class CutSpec(typing.Sequence[str]):
    pass


class Data(typing.Sequence[typing.Sequence[typing.Union[str, bytes]]]):
    pass

            

Reported by Pylint.

Method '__len__' is abstract in class 'Sized' but is not overridden
Error

Line: 35 Column: 1

                  pass


class CutSpec(typing.Sequence[str]):
    pass


class Data(typing.Sequence[typing.Sequence[typing.Union[str, bytes]]]):
    pass

            

Reported by Pylint.

Parameters differ from overridden 'parse' method
Error

Line: 91 Column: 5

                  def completion(self, manager: "CommandManager", t: type, s: str) -> typing.Sequence[str]:
        return ["false", "true"]

    def parse(self, manager: "CommandManager", t: type, s: str) -> bool:
        if s == "true":
            return True
        elif s == "false":
            return False
        else:

            

Reported by Pylint.

Unused argument 't'
Error

Line: 91 Column: 48

                  def completion(self, manager: "CommandManager", t: type, s: str) -> typing.Sequence[str]:
        return ["false", "true"]

    def parse(self, manager: "CommandManager", t: type, s: str) -> bool:
        if s == "true":
            return True
        elif s == "false":
            return False
        else:

            

Reported by Pylint.

Unused argument 't'
Error

Line: 128 Column: 48

                  def completion(self, manager: "CommandManager", t: type, s: str) -> typing.Sequence[str]:
        return []

    def parse(self, manager: "CommandManager", t: type, s: str) -> str:
        try:
            return self.escape_sequences.sub(self._unescape, s)
        except ValueError as e:
            raise exceptions.TypeError(f"Invalid str: {e}") from e


            

Reported by Pylint.

Parameters differ from overridden 'parse' method
Error

Line: 128 Column: 5

                  def completion(self, manager: "CommandManager", t: type, s: str) -> typing.Sequence[str]:
        return []

    def parse(self, manager: "CommandManager", t: type, s: str) -> str:
        try:
            return self.escape_sequences.sub(self._unescape, s)
        except ValueError as e:
            raise exceptions.TypeError(f"Invalid str: {e}") from e


            

Reported by Pylint.

Unused argument 't'
Error

Line: 145 Column: 48

                  def completion(self, manager: "CommandManager", t: type, s: str) -> typing.Sequence[str]:
        return []

    def parse(self, manager: "CommandManager", t: type, s: str) -> bytes:
        try:
            return strutils.escaped_str_to_bytes(s)
        except ValueError as e:
            raise exceptions.TypeError(str(e))


            

Reported by Pylint.

Parameters differ from overridden 'parse' method
Error

Line: 145 Column: 5

                  def completion(self, manager: "CommandManager", t: type, s: str) -> typing.Sequence[str]:
        return []

    def parse(self, manager: "CommandManager", t: type, s: str) -> bytes:
        try:
            return strutils.escaped_str_to_bytes(s)
        except ValueError as e:
            raise exceptions.TypeError(str(e))


            

Reported by Pylint.

Unused argument 't'
Error

Line: 162 Column: 48

                  def completion(self, manager: "CommandManager", t: type, s: str) -> typing.Sequence[str]:
        return []

    def parse(self, manager: "CommandManager", t: type, s: str) -> str:
        return s

    def is_valid(self, manager: "CommandManager", typ: typing.Any, val: typing.Any) -> bool:
        return False


            

Reported by Pylint.

Parameters differ from overridden 'parse' method
Error

Line: 162 Column: 5

                  def completion(self, manager: "CommandManager", t: type, s: str) -> typing.Sequence[str]:
        return []

    def parse(self, manager: "CommandManager", t: type, s: str) -> str:
        return s

    def is_valid(self, manager: "CommandManager", typ: typing.Any, val: typing.Any) -> bool:
        return False


            

Reported by Pylint.

mitmproxy/certs.py
68 issues
No value for argument 'backend' in function call
Error

Line: 66 Column: 22

                      return self.to_pem()

    def set_state(self, state):
        self._cert = x509.load_pem_x509_certificate(state)

    @classmethod
    def from_pem(cls, data: bytes) -> "Cert":
        cert = x509.load_pem_x509_certificate(data)  # type: ignore
        return cls(cert)

            

Reported by Pylint.

No value for argument 'backend' in function call
Error

Line: 70 Column: 16

              
    @classmethod
    def from_pem(cls, data: bytes) -> "Cert":
        cert = x509.load_pem_x509_certificate(data)  # type: ignore
        return cls(cert)

    def to_pem(self) -> bytes:
        return self._cert.public_bytes(serialization.Encoding.PEM)


            

Reported by Pylint.

No value for argument 'backend' in function call
Error

Line: 172 Column: 19

              ) -> Tuple[rsa.RSAPrivateKeyWithSerialization, x509.Certificate]:
    now = datetime.datetime.now()

    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=key_size,
    )  # type: ignore
    name = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, cn),

            

Reported by Pylint.

Module 'cryptography.hazmat.primitives.serialization.pkcs12' has no 'serialize_key_and_certificates' member
Error

Line: 391 Column: 17

              
            # PKCS12 format for Windows devices
            (path / f"{basename}-ca.p12").write_bytes(
                pkcs12.serialize_key_and_certificates(  # type: ignore
                    name=basename.encode(),
                    key=key,
                    cert=ca,
                    cas=None,
                    encryption_algorithm=serialization.NoEncryption(),

            

Reported by Pylint.

Module 'cryptography.hazmat.primitives.serialization.pkcs12' has no 'serialize_key_and_certificates' member
Error

Line: 408 Column: 13

              
        # Dump the certificate in PKCS12 format for Windows devices
        (path / f"{basename}-ca-cert.p12").write_bytes(
            pkcs12.serialize_key_and_certificates(
                name=basename.encode(),
                key=None,  # type: ignore
                cert=ca,
                cas=None,
                encryption_algorithm=serialization.NoEncryption(),

            

Reported by Pylint.

No value for argument 'backend' in function call
Error

Line: 508 Column: 16

                  if the private key is unencrypted.
    """
    try:
        return serialization.load_pem_private_key(data, password)  # type: ignore
    except TypeError:
        if password is not None:
            return load_pem_private_key(data, None)
        raise

            

Reported by Pylint.

Redefining name 'x509' from outer scope (line 10)
Error

Line: 77 Column: 30

                      return self._cert.public_bytes(serialization.Encoding.PEM)

    @classmethod
    def from_pyopenssl(self, x509: OpenSSL.crypto.X509) -> "Cert":
        return Cert(x509.to_cryptography())

    def to_pyopenssl(self) -> OpenSSL.crypto.X509:
        return OpenSSL.crypto.X509.from_cryptography(self._cert)


            

Reported by Pylint.

Access to a protected member _lib of a client class
Error

Line: 311 Column: 15

              
        # we could use cryptography for this, but it's unclear how to convert cryptography's object to pyOpenSSL's
        # expected format.
        bio = OpenSSL.SSL._lib.BIO_new_file(str(path).encode(sys.getfilesystemencoding()), b"r")  # type: ignore
        if bio != OpenSSL.SSL._ffi.NULL:  # type: ignore
            bio = OpenSSL.SSL._ffi.gc(bio, OpenSSL.SSL._lib.BIO_free)  # type: ignore
            dh = OpenSSL.SSL._lib.PEM_read_bio_DHparams(  # type: ignore
                bio,
                OpenSSL.SSL._ffi.NULL,  # type: ignore

            

Reported by Pylint.

Access to a protected member _ffi of a client class
Error

Line: 312 Column: 19

                      # we could use cryptography for this, but it's unclear how to convert cryptography's object to pyOpenSSL's
        # expected format.
        bio = OpenSSL.SSL._lib.BIO_new_file(str(path).encode(sys.getfilesystemencoding()), b"r")  # type: ignore
        if bio != OpenSSL.SSL._ffi.NULL:  # type: ignore
            bio = OpenSSL.SSL._ffi.gc(bio, OpenSSL.SSL._lib.BIO_free)  # type: ignore
            dh = OpenSSL.SSL._lib.PEM_read_bio_DHparams(  # type: ignore
                bio,
                OpenSSL.SSL._ffi.NULL,  # type: ignore
                OpenSSL.SSL._ffi.NULL,  # type: ignore

            

Reported by Pylint.

Access to a protected member _ffi of a client class
Error

Line: 313 Column: 19

                      # expected format.
        bio = OpenSSL.SSL._lib.BIO_new_file(str(path).encode(sys.getfilesystemencoding()), b"r")  # type: ignore
        if bio != OpenSSL.SSL._ffi.NULL:  # type: ignore
            bio = OpenSSL.SSL._ffi.gc(bio, OpenSSL.SSL._lib.BIO_free)  # type: ignore
            dh = OpenSSL.SSL._lib.PEM_read_bio_DHparams(  # type: ignore
                bio,
                OpenSSL.SSL._ffi.NULL,  # type: ignore
                OpenSSL.SSL._ffi.NULL,  # type: ignore
                OpenSSL.SSL._ffi.NULL  # type: ignore

            

Reported by Pylint.

test/mitmproxy/addons/test_script.py
67 issues
Unable to import 'pytest'
Error

Line: 6 Column: 1

              import sys
import traceback

import pytest

from mitmproxy import addonmanager
from mitmproxy import exceptions
from mitmproxy.addons import script
from mitmproxy.proxy.layers.http import HttpRequestHook

            

Reported by Pylint.

Unused variable 'i'
Error

Line: 115 Column: 17

                          await tctx.master.await_log("Loading")

            tctx.master.clear()
            for i in range(20):
                f.write("\n")
                if tctx.master.has_log("Loading"):
                    break
                await asyncio.sleep(0.1)
            else:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import asyncio
import os
import sys
import traceback

import pytest

from mitmproxy import addonmanager
from mitmproxy import exceptions

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 21 Column: 1

              

@pytest.mark.asyncio
async def test_load_script(tdata):
    with taddons.context() as tctx:
        ns = script.load_script(
            tdata.path(
                "mitmproxy/data/addonscripts/recorder/recorder.py"
            )

            

Reported by Pylint.

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

Line: 23 Column: 9

              @pytest.mark.asyncio
async def test_load_script(tdata):
    with taddons.context() as tctx:
        ns = script.load_script(
            tdata.path(
                "mitmproxy/data/addonscripts/recorder/recorder.py"
            )
        )
        assert ns.addons

            

Reported by Pylint.

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

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

                              "mitmproxy/data/addonscripts/recorder/recorder.py"
            )
        )
        assert ns.addons

        script.load_script(
            "nonexistent"
        )
        await tctx.master.await_log("No such file or directory")

            

Reported by Bandit.

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

Line: 49 Column: 5

                  This only succeeds if they get assigned different basenames.

    """
    ns = script.load_script(
        tdata.path(
            "mitmproxy/data/addonscripts/addon.py"
        )
    )
    assert ns.addons

            

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

                          "mitmproxy/data/addonscripts/addon.py"
        )
    )
    assert ns.addons
    ns2 = script.load_script(
        tdata.path(
            "mitmproxy/data/addonscripts/same_filename/addon.py"
        )
    )

            

Reported by Bandit.

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

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

                          "mitmproxy/data/addonscripts/same_filename/addon.py"
        )
    )
    assert ns.name != ns2.name
    assert not hasattr(ns2, "addons")


class TestScript:
    def test_notfound(self):

            

Reported by Bandit.

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

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

                      )
    )
    assert ns.name != ns2.name
    assert not hasattr(ns2, "addons")


class TestScript:
    def test_notfound(self):
        with taddons.context():

            

Reported by Bandit.

examples/contrib/webscanner_helper/test_proxyauth_selenium.py
64 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              from unittest import mock
from unittest.mock import MagicMock

import pytest

from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.http import HTTPFlow


            

Reported by Pylint.

Unable to import 'mitmproxy.test'
Error

Line: 6 Column: 1

              
import pytest

from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.http import HTTPFlow

from examples.contrib.webscanner_helper.proxyauth_selenium import logger, randomString, AuthorizationOracle, \
    SeleniumAddon

            

Reported by Pylint.

Unable to import 'mitmproxy.test'
Error

Line: 7 Column: 1

              import pytest

from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.http import HTTPFlow

from examples.contrib.webscanner_helper.proxyauth_selenium import logger, randomString, AuthorizationOracle, \
    SeleniumAddon


            

Reported by Pylint.

Unable to import 'mitmproxy.http'
Error

Line: 8 Column: 1

              
from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.http import HTTPFlow

from examples.contrib.webscanner_helper.proxyauth_selenium import logger, randomString, AuthorizationOracle, \
    SeleniumAddon



            

Reported by Pylint.

Unable to import 'examples.contrib.webscanner_helper.proxyauth_selenium'
Error

Line: 10 Column: 1

              from mitmproxy.test import tutils
from mitmproxy.http import HTTPFlow

from examples.contrib.webscanner_helper.proxyauth_selenium import logger, randomString, AuthorizationOracle, \
    SeleniumAddon


class TestRandomString:


            

Reported by Pylint.

Unused argument 'flow'
Error

Line: 27 Column: 39

              

class AuthenticationOracleTest(AuthorizationOracle):
    def is_unauthorized_request(self, flow: HTTPFlow) -> bool:
        return True

    def is_unauthorized_response(self, flow: HTTPFlow) -> bool:
        return True


            

Reported by Pylint.

Unused argument 'flow'
Error

Line: 30 Column: 40

                  def is_unauthorized_request(self, flow: HTTPFlow) -> bool:
        return True

    def is_unauthorized_response(self, flow: HTTPFlow) -> bool:
        return True


oracle = AuthenticationOracleTest()


            

Reported by Pylint.

Redefining name 'selenium_addon' from outer scope (line 38)
Error

Line: 53 Column: 35

              
class TestSeleniumAddon:

    def test_request_replay(self, selenium_addon):
        f = tflow.tflow(resp=tutils.tresp())
        f.request.is_replay = True
        with mock.patch.object(logger, 'warning') as mock_warning:
            selenium_addon.request(f)
        mock_warning.assert_called()

            

Reported by Pylint.

Redefining name 'selenium_addon' from outer scope (line 38)
Error

Line: 60 Column: 28

                          selenium_addon.request(f)
        mock_warning.assert_called()

    def test_request(self, selenium_addon):
        f = tflow.tflow(resp=tutils.tresp())
        f.request.url = "http://example.com/login.php"
        selenium_addon.set_cookies = False
        assert not selenium_addon.set_cookies
        with mock.patch.object(logger, 'debug') as mock_debug:

            

Reported by Pylint.

Redefining name 'selenium_addon' from outer scope (line 38)
Error

Line: 70 Column: 37

                      mock_debug.assert_called()
        assert selenium_addon.set_cookies

    def test_request_filtered(self, selenium_addon):
        f = tflow.tflow(resp=tutils.tresp())
        selenium_addon.set_cookies = False
        assert not selenium_addon.set_cookies
        selenium_addon.request(f)
        assert not selenium_addon.set_cookies

            

Reported by Pylint.

examples/contrib/webscanner_helper/test_urlinjection.py
64 issues
Unable to import 'mitmproxy'
Error

Line: 4 Column: 1

              import json
from unittest import mock

from mitmproxy import flowfilter
from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlinjection import InjectionGenerator, HTMLInjection, RobotsInjection, \
    SitemapInjection, \

            

Reported by Pylint.

Unable to import 'mitmproxy.test'
Error

Line: 5 Column: 1

              from unittest import mock

from mitmproxy import flowfilter
from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlinjection import InjectionGenerator, HTMLInjection, RobotsInjection, \
    SitemapInjection, \
    UrlInjectionAddon, logger

            

Reported by Pylint.

Unable to import 'mitmproxy.test'
Error

Line: 6 Column: 1

              
from mitmproxy import flowfilter
from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlinjection import InjectionGenerator, HTMLInjection, RobotsInjection, \
    SitemapInjection, \
    UrlInjectionAddon, logger


            

Reported by Pylint.

Unable to import 'examples.contrib.webscanner_helper.urlinjection'
Error

Line: 8 Column: 1

              from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlinjection import InjectionGenerator, HTMLInjection, RobotsInjection, \
    SitemapInjection, \
    UrlInjectionAddon, logger

index = json.loads(
    "{\"http://example.com:80\": {\"/\": {\"GET\": [301]}}, \"http://www.example.com:80\": {\"/test\": {\"POST\": [302]}}}")

            

Reported by Pylint.

Using an f-string that does not have any interpolated variables
Error

Line: 103 Column: 15

                      tmpfile = tmpdir.join("tmpfile")
        with open(tmpfile, "w") as tfile:
            json.dump(index, tfile)
        flt = f"~u .*/site.html$"
        url_injection = UrlInjectionAddon(f"~u .*/site.html$", tmpfile, HTMLInjection(insert=True))
        assert "http://example.com:80" in url_injection.url_store
        fltr = flowfilter.parse(flt)
        f = tflow.tflow(resp=tutils.tresp())
        f.request.url = "http://example.com/site.html"

            

Reported by Pylint.

Using an f-string that does not have any interpolated variables
Error

Line: 104 Column: 43

                      with open(tmpfile, "w") as tfile:
            json.dump(index, tfile)
        flt = f"~u .*/site.html$"
        url_injection = UrlInjectionAddon(f"~u .*/site.html$", tmpfile, HTMLInjection(insert=True))
        assert "http://example.com:80" in url_injection.url_store
        fltr = flowfilter.parse(flt)
        f = tflow.tflow(resp=tutils.tresp())
        f.request.url = "http://example.com/site.html"
        assert fltr(f)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import json
from unittest import mock

from mitmproxy import flowfilter
from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlinjection import InjectionGenerator, HTMLInjection, RobotsInjection, \
    SitemapInjection, \

            

Reported by Pylint.

Line too long (113/100)
Error

Line: 8 Column: 1

              from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlinjection import InjectionGenerator, HTMLInjection, RobotsInjection, \
    SitemapInjection, \
    UrlInjectionAddon, logger

index = json.loads(
    "{\"http://example.com:80\": {\"/\": {\"GET\": [301]}}, \"http://www.example.com:80\": {\"/test\": {\"POST\": [302]}}}")

            

Reported by Pylint.

Line too long (124/100)
Error

Line: 13 Column: 1

                  UrlInjectionAddon, logger

index = json.loads(
    "{\"http://example.com:80\": {\"/\": {\"GET\": [301]}}, \"http://www.example.com:80\": {\"/test\": {\"POST\": [302]}}}")


class TestInjectionGenerator:

    def test_inject(self):

            

Reported by Pylint.

Missing class docstring
Error

Line: 16 Column: 1

                  "{\"http://example.com:80\": {\"/\": {\"GET\": [301]}}, \"http://www.example.com:80\": {\"/test\": {\"POST\": [302]}}}")


class TestInjectionGenerator:

    def test_inject(self):
        f = tflow.tflow(resp=tutils.tresp())
        injection_generator = InjectionGenerator()
        injection_generator.inject(index=index, flow=f)

            

Reported by Pylint.

test/mitmproxy/utils/test_strutils.py
64 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest

from mitmproxy.utils import strutils


def test_always_bytes():
    assert strutils.always_bytes(bytes(range(256))) == bytes(range(256))
    assert strutils.always_bytes("foo") == b"foo"
    with pytest.raises(ValueError):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest

from mitmproxy.utils import strutils


def test_always_bytes():
    assert strutils.always_bytes(bytes(range(256))) == bytes(range(256))
    assert strutils.always_bytes("foo") == b"foo"
    with pytest.raises(ValueError):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 6 Column: 1

              from mitmproxy.utils import strutils


def test_always_bytes():
    assert strutils.always_bytes(bytes(range(256))) == bytes(range(256))
    assert strutils.always_bytes("foo") == b"foo"
    with pytest.raises(ValueError):
        strutils.always_bytes("\u2605", "ascii")
    with pytest.raises(TypeError):

            

Reported by Pylint.

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

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

              

def test_always_bytes():
    assert strutils.always_bytes(bytes(range(256))) == bytes(range(256))
    assert strutils.always_bytes("foo") == b"foo"
    with pytest.raises(ValueError):
        strutils.always_bytes("\u2605", "ascii")
    with pytest.raises(TypeError):
        strutils.always_bytes(42, "ascii")

            

Reported by Bandit.

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_always_bytes():
    assert strutils.always_bytes(bytes(range(256))) == bytes(range(256))
    assert strutils.always_bytes("foo") == b"foo"
    with pytest.raises(ValueError):
        strutils.always_bytes("\u2605", "ascii")
    with pytest.raises(TypeError):
        strutils.always_bytes(42, "ascii")


            

Reported by Bandit.

Missing function or method docstring
Error

Line: 15 Column: 1

                      strutils.always_bytes(42, "ascii")


def test_always_str():
    with pytest.raises(TypeError):
        strutils.always_str(42)
    assert strutils.always_str("foo") == "foo"
    assert strutils.always_str(b"foo") == "foo"
    assert strutils.always_str(None) is None

            

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

              def test_always_str():
    with pytest.raises(TypeError):
        strutils.always_str(42)
    assert strutils.always_str("foo") == "foo"
    assert strutils.always_str(b"foo") == "foo"
    assert strutils.always_str(None) is None


def test_escape_control_characters():

            

Reported by Bandit.

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

                  with pytest.raises(TypeError):
        strutils.always_str(42)
    assert strutils.always_str("foo") == "foo"
    assert strutils.always_str(b"foo") == "foo"
    assert strutils.always_str(None) is None


def test_escape_control_characters():
    assert strutils.escape_control_characters("one") == "one"

            

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

                      strutils.always_str(42)
    assert strutils.always_str("foo") == "foo"
    assert strutils.always_str(b"foo") == "foo"
    assert strutils.always_str(None) is None


def test_escape_control_characters():
    assert strutils.escape_control_characters("one") == "one"
    assert strutils.escape_control_characters("\00ne") == ".ne"

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 23 Column: 1

                  assert strutils.always_str(None) is None


def test_escape_control_characters():
    assert strutils.escape_control_characters("one") == "one"
    assert strutils.escape_control_characters("\00ne") == ".ne"
    assert strutils.escape_control_characters("\nne") == "\nne"
    assert strutils.escape_control_characters("\nne", False) == ".ne"
    assert strutils.escape_control_characters("\u2605") == "\u2605"

            

Reported by Pylint.

test/mitmproxy/net/http/http1/test_read.py
64 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest

from mitmproxy.http import Headers
from mitmproxy.net.http.http1.read import (
    read_request_head,
    read_response_head, connection_close, expected_http_body_size,
    _read_request_line, _read_response_line, _read_headers, get_header_tokens
)
from mitmproxy.test.tutils import treq, tresp

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest

from mitmproxy.http import Headers
from mitmproxy.net.http.http1.read import (
    read_request_head,
    read_response_head, connection_close, expected_http_body_size,
    _read_request_line, _read_response_line, _read_headers, get_header_tokens
)
from mitmproxy.test.tutils import treq, tresp

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 1

              from mitmproxy.test.tutils import treq, tresp


def test_get_header_tokens():
    headers = Headers()
    assert get_header_tokens(headers, "foo") == []
    headers["foo"] = "bar"
    assert get_header_tokens(headers, "foo") == ["bar"]
    headers["foo"] = "bar, voing"

            

Reported by Pylint.

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

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

              
def test_get_header_tokens():
    headers = Headers()
    assert get_header_tokens(headers, "foo") == []
    headers["foo"] = "bar"
    assert get_header_tokens(headers, "foo") == ["bar"]
    headers["foo"] = "bar, voing"
    assert get_header_tokens(headers, "foo") == ["bar", "voing"]
    headers.set_all("foo", ["bar, voing", "oink"])

            

Reported by Bandit.

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

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

                  headers = Headers()
    assert get_header_tokens(headers, "foo") == []
    headers["foo"] = "bar"
    assert get_header_tokens(headers, "foo") == ["bar"]
    headers["foo"] = "bar, voing"
    assert get_header_tokens(headers, "foo") == ["bar", "voing"]
    headers.set_all("foo", ["bar, voing", "oink"])
    assert get_header_tokens(headers, "foo") == ["bar", "voing", "oink"]


            

Reported by Bandit.

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

                  headers["foo"] = "bar"
    assert get_header_tokens(headers, "foo") == ["bar"]
    headers["foo"] = "bar, voing"
    assert get_header_tokens(headers, "foo") == ["bar", "voing"]
    headers.set_all("foo", ["bar, voing", "oink"])
    assert get_header_tokens(headers, "foo") == ["bar", "voing", "oink"]


def test_connection_close():

            

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

                  headers["foo"] = "bar, voing"
    assert get_header_tokens(headers, "foo") == ["bar", "voing"]
    headers.set_all("foo", ["bar, voing", "oink"])
    assert get_header_tokens(headers, "foo") == ["bar", "voing", "oink"]


def test_connection_close():
    headers = Headers()
    assert connection_close(b"HTTP/1.0", headers)

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 23 Column: 1

                  assert get_header_tokens(headers, "foo") == ["bar", "voing", "oink"]


def test_connection_close():
    headers = Headers()
    assert connection_close(b"HTTP/1.0", headers)
    assert not connection_close(b"HTTP/1.1", headers)
    assert not connection_close(b"HTTP/2.0", headers)


            

Reported by Pylint.

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

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

              
def test_connection_close():
    headers = Headers()
    assert connection_close(b"HTTP/1.0", headers)
    assert not connection_close(b"HTTP/1.1", headers)
    assert not connection_close(b"HTTP/2.0", headers)

    headers["connection"] = "keep-alive"
    assert not connection_close(b"HTTP/1.1", headers)

            

Reported by Bandit.

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

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

              def test_connection_close():
    headers = Headers()
    assert connection_close(b"HTTP/1.0", headers)
    assert not connection_close(b"HTTP/1.1", headers)
    assert not connection_close(b"HTTP/2.0", headers)

    headers["connection"] = "keep-alive"
    assert not connection_close(b"HTTP/1.1", headers)


            

Reported by Bandit.

examples/contrib/webscanner_helper/test_mapping.py
63 issues
Unable to import 'mitmproxy.test'
Error

Line: 5 Column: 1

              from unittest import mock
from unittest.mock import MagicMock

from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.mapping import MappingAddon, MappingAddonConfig



            

Reported by Pylint.

Unable to import 'mitmproxy.test'
Error

Line: 6 Column: 1

              from unittest.mock import MagicMock

from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.mapping import MappingAddon, MappingAddonConfig


class TestConfig:

            

Reported by Pylint.

Unable to import 'examples.contrib.webscanner_helper.mapping'
Error

Line: 8 Column: 1

              from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.mapping import MappingAddon, MappingAddonConfig


class TestConfig:

    def test_config(self):

            

Reported by Pylint.

Method should have "self" as first argument
Error

Line: 159 Column: 5

                      else:
            assert False

    def test_dump(selfself, tmpdir):
        tmpfile = tmpdir.join("tmpfile")
        with open(tmpfile, "w") as tfile:
            tfile.write("{}")
        mapping = MappingAddon(tmpfile, persistent=True)
        with mock.patch('examples.complex.webscanner_helper.urldict.URLDict.dump', selfself.mock_dump):

            

Reported by Pylint.

Access to a protected member _dump of a client class
Error

Line: 29 Column: 33

                      with open(tmpfile, "w") as tfile:
            tfile.write(mapping_content)
        mapping = MappingAddon(tmpfile)
        assert "My Text" in str(mapping.mapping_templates._dump())

    def test_load(self, tmpdir):
        tmpfile = tmpdir.join("tmpfile")
        with open(tmpfile, "w") as tfile:
            tfile.write(mapping_content)

            

Reported by Pylint.

Unused argument 'f'
Error

Line: 150 Column: 25

                          results = tfile.read()
        assert mapping_content in results

    def mock_dump(self, f: TextIO, value_dumper: Callable):
        assert value_dumper(None) == "None"
        try:
            value_dumper("Test")
        except RuntimeError:
            assert True

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from typing import TextIO, Callable
from unittest import mock
from unittest.mock import MagicMock

from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.mapping import MappingAddon, MappingAddonConfig


            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 11 Column: 1

              from examples.contrib.webscanner_helper.mapping import MappingAddon, MappingAddonConfig


class TestConfig:

    def test_config(self):
        assert MappingAddonConfig.HTML_PARSER == "html.parser"



            

Reported by Pylint.

Missing class docstring
Error

Line: 11 Column: 1

              from examples.contrib.webscanner_helper.mapping import MappingAddon, MappingAddonConfig


class TestConfig:

    def test_config(self):
        assert MappingAddonConfig.HTML_PARSER == "html.parser"



            

Reported by Pylint.

Method could be a function
Error

Line: 13 Column: 5

              
class TestConfig:

    def test_config(self):
        assert MappingAddonConfig.HTML_PARSER == "html.parser"


url = "http://10.10.10.10"
new_content = "My Text"

            

Reported by Pylint.

mitmproxy/net/tls.py
63 issues
Unable to import 'kaitaistruct'
Error

Line: 14 Column: 1

              
from OpenSSL.crypto import X509
from cryptography.hazmat.primitives.asymmetric import rsa
from kaitaistruct import KaitaiStream

from OpenSSL import SSL, crypto
from mitmproxy import certs
from mitmproxy.contrib.kaitaistruct import tls_client_hello
from mitmproxy.net import check

            

Reported by Pylint.

Instance of 'Context' has no 'set_keylog_callback' member
Error

Line: 126 Column: 9

              
    # SSLKEYLOGFILE
    if log_master_secret:
        context.set_keylog_callback(log_master_secret)

    return context


@lru_cache(256)

            

Reported by Pylint.

TODO: just SSL attributes once https://github.com/pyca/pyopenssl/pull/985 has landed.
Error

Line: 24 Column: 3

              
# redeclared here for strict type checking
class Method(Enum):
    # TODO: just SSL attributes once https://github.com/pyca/pyopenssl/pull/985 has landed.
    TLS_SERVER_METHOD = getattr(SSL, "TLS_SERVER_METHOD", 8)
    TLS_CLIENT_METHOD = getattr(SSL, "TLS_CLIENT_METHOD", 9)


# TODO: remove once https://github.com/pyca/pyopenssl/pull/985 has landed.

            

Reported by Pylint.

TODO: remove once https://github.com/pyca/pyopenssl/pull/985 has landed.
Error

Line: 29 Column: 3

                  TLS_CLIENT_METHOD = getattr(SSL, "TLS_CLIENT_METHOD", 9)


# TODO: remove once https://github.com/pyca/pyopenssl/pull/985 has landed.
try:
    SSL._lib.TLS_server_method  # type: ignore
except AttributeError as e:  # pragma: no cover
    raise RuntimeError("Your installation of the cryptography Python package is outdated.") from e


            

Reported by Pylint.

Access to a protected member _lib of a client class
Error

Line: 31 Column: 5

              
# TODO: remove once https://github.com/pyca/pyopenssl/pull/985 has landed.
try:
    SSL._lib.TLS_server_method  # type: ignore
except AttributeError as e:  # pragma: no cover
    raise RuntimeError("Your installation of the cryptography Python package is outdated.") from e

SSL.Context._methods.setdefault(Method.TLS_SERVER_METHOD.value, SSL._lib.TLS_server_method)  # type: ignore
SSL.Context._methods.setdefault(Method.TLS_CLIENT_METHOD.value, SSL._lib.TLS_client_method)  # type: ignore

            

Reported by Pylint.

Access to a protected member _methods of a client class
Error

Line: 35 Column: 1

              except AttributeError as e:  # pragma: no cover
    raise RuntimeError("Your installation of the cryptography Python package is outdated.") from e

SSL.Context._methods.setdefault(Method.TLS_SERVER_METHOD.value, SSL._lib.TLS_server_method)  # type: ignore
SSL.Context._methods.setdefault(Method.TLS_CLIENT_METHOD.value, SSL._lib.TLS_client_method)  # type: ignore


class Version(Enum):
    UNBOUNDED = 0

            

Reported by Pylint.

Access to a protected member _lib of a client class
Error

Line: 35 Column: 65

              except AttributeError as e:  # pragma: no cover
    raise RuntimeError("Your installation of the cryptography Python package is outdated.") from e

SSL.Context._methods.setdefault(Method.TLS_SERVER_METHOD.value, SSL._lib.TLS_server_method)  # type: ignore
SSL.Context._methods.setdefault(Method.TLS_CLIENT_METHOD.value, SSL._lib.TLS_client_method)  # type: ignore


class Version(Enum):
    UNBOUNDED = 0

            

Reported by Pylint.

Access to a protected member _methods of a client class
Error

Line: 36 Column: 1

                  raise RuntimeError("Your installation of the cryptography Python package is outdated.") from e

SSL.Context._methods.setdefault(Method.TLS_SERVER_METHOD.value, SSL._lib.TLS_server_method)  # type: ignore
SSL.Context._methods.setdefault(Method.TLS_CLIENT_METHOD.value, SSL._lib.TLS_client_method)  # type: ignore


class Version(Enum):
    UNBOUNDED = 0
    # TODO: just SSL attributes once https://github.com/pyca/pyopenssl/pull/985 has landed.

            

Reported by Pylint.

Access to a protected member _lib of a client class
Error

Line: 36 Column: 65

                  raise RuntimeError("Your installation of the cryptography Python package is outdated.") from e

SSL.Context._methods.setdefault(Method.TLS_SERVER_METHOD.value, SSL._lib.TLS_server_method)  # type: ignore
SSL.Context._methods.setdefault(Method.TLS_CLIENT_METHOD.value, SSL._lib.TLS_client_method)  # type: ignore


class Version(Enum):
    UNBOUNDED = 0
    # TODO: just SSL attributes once https://github.com/pyca/pyopenssl/pull/985 has landed.

            

Reported by Pylint.

TODO: just SSL attributes once https://github.com/pyca/pyopenssl/pull/985 has landed.
Error

Line: 41 Column: 3

              
class Version(Enum):
    UNBOUNDED = 0
    # TODO: just SSL attributes once https://github.com/pyca/pyopenssl/pull/985 has landed.
    SSL3 = getattr(SSL, "SSL3_VERSION", 768)
    TLS1 = getattr(SSL, "TLS1_VERSION", 768)
    TLS1_1 = getattr(SSL, "TLS1_1_VERSION", 770)
    TLS1_2 = getattr(SSL, "TLS1_2_VERSION", 771)
    TLS1_3 = getattr(SSL, "TLS1_3_VERSION", 772)

            

Reported by Pylint.

mitmproxy/proxy/layers/http/_http2.py
63 issues
Unable to import 'h2.config'
Error

Line: 6 Column: 1

              from enum import Enum
from typing import ClassVar, DefaultDict, Dict, List, Optional, Sequence, Tuple, Type, Union

import h2.config
import h2.connection
import h2.errors
import h2.events
import h2.exceptions
import h2.settings

            

Reported by Pylint.

Unable to import 'h2.connection'
Error

Line: 7 Column: 1

              from typing import ClassVar, DefaultDict, Dict, List, Optional, Sequence, Tuple, Type, Union

import h2.config
import h2.connection
import h2.errors
import h2.events
import h2.exceptions
import h2.settings
import h2.stream

            

Reported by Pylint.

Unable to import 'h2.errors'
Error

Line: 8 Column: 1

              
import h2.config
import h2.connection
import h2.errors
import h2.events
import h2.exceptions
import h2.settings
import h2.stream
import h2.utilities

            

Reported by Pylint.

Unable to import 'h2.events'
Error

Line: 9 Column: 1

              import h2.config
import h2.connection
import h2.errors
import h2.events
import h2.exceptions
import h2.settings
import h2.stream
import h2.utilities


            

Reported by Pylint.

Unable to import 'h2.exceptions'
Error

Line: 10 Column: 1

              import h2.connection
import h2.errors
import h2.events
import h2.exceptions
import h2.settings
import h2.stream
import h2.utilities

from mitmproxy import http, version

            

Reported by Pylint.

Unable to import 'h2.settings'
Error

Line: 11 Column: 1

              import h2.errors
import h2.events
import h2.exceptions
import h2.settings
import h2.stream
import h2.utilities

from mitmproxy import http, version
from mitmproxy.connection import Connection

            

Reported by Pylint.

Unable to import 'h2.stream'
Error

Line: 12 Column: 1

              import h2.events
import h2.exceptions
import h2.settings
import h2.stream
import h2.utilities

from mitmproxy import http, version
from mitmproxy.connection import Connection
from mitmproxy.net.http import status_codes, url

            

Reported by Pylint.

Unable to import 'h2.utilities'
Error

Line: 13 Column: 1

              import h2.exceptions
import h2.settings
import h2.stream
import h2.utilities

from mitmproxy import http, version
from mitmproxy.connection import Connection
from mitmproxy.net.http import status_codes, url
from mitmproxy.utils import human

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 19 Column: 1

              from mitmproxy.connection import Connection
from mitmproxy.net.http import status_codes, url
from mitmproxy.utils import human
from . import RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, ResponseData, \
    ResponseEndOfMessage, ResponseHeaders, RequestTrailers, ResponseTrailers, ResponseProtocolError
from ._base import HttpConnection, HttpEvent, ReceiveHttp, format_error
from ._http_h2 import BufferedH2Connection, H2ConnectionLogger
from ...commands import CloseConnection, Log, SendData
from ...context import Context

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 21 Column: 1

              from mitmproxy.utils import human
from . import RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, ResponseData, \
    ResponseEndOfMessage, ResponseHeaders, RequestTrailers, ResponseTrailers, ResponseProtocolError
from ._base import HttpConnection, HttpEvent, ReceiveHttp, format_error
from ._http_h2 import BufferedH2Connection, H2ConnectionLogger
from ...commands import CloseConnection, Log, SendData
from ...context import Context
from ...events import ConnectionClosed, DataReceived, Event, Start
from ...layer import CommandGenerator

            

Reported by Pylint.