Ejemplo n.º 1
0
async def test_script_print_stdout():
    with taddons.context() as tctx:
        with addonmanager.safecall():
            ns = script.load_script(
                tutils.test_data.path("mitmproxy/data/addonscripts/print.py"))
            ns.load(addonmanager.Loader(tctx.master))
        assert await tctx.master.await_log("stdoutprint")
Ejemplo n.º 2
0
 def test_concurrent_err(self):
     with taddons.context() as tctx:
         sc = script.Script(
             tutils.test_data.path(
                 "mitmproxy/data/addonscripts/concurrent_decorator_err.py"))
         l = addonmanager.Loader(tctx.master)
         sc.load(l)
         assert tctx.master.has_log("decorator not supported")
Ejemplo n.º 3
0
def test_script_print_stdout():
    with taddons.context() as tctx:
        with mock.patch('mitmproxy.ctx.log.warn') as mock_warn:
            with script.scriptenv("path", []):
                ns = script.load_script(
                    tutils.test_data.path(
                        "mitmproxy/data/addonscripts/print.py"), [])
                ns.load(addonmanager.Loader(tctx.master))
        mock_warn.assert_called_once_with("stdoutprint")
Ejemplo n.º 4
0
 def test_addon(self):
     with taddons.context() as tctx:
         sc = script.Script(
             tutils.test_data.path("mitmproxy/data/addonscripts/addon.py"))
         l = addonmanager.Loader(tctx.master)
         sc.load(l)
         tctx.configure(sc)
         assert sc.ns.event_log == [
             'scriptload', 'addonload', 'addonconfigure'
         ]
Ejemplo n.º 5
0
def test_script_print_stdout():
    with taddons.context() as tctx:
        with mock.patch('mitmproxy.ctx.master.tell') as mock_warn:
            with addonmanager.safecall():
                ns = script.load_script(
                    tutils.test_data.path(
                        "mitmproxy/data/addonscripts/print.py"))
                ns.load(addonmanager.Loader(tctx.master))
        mock_warn.assert_called_once_with("log",
                                          log.LogEntry("stdoutprint", "warn"))
Ejemplo n.º 6
0
 def script(self, path):
     """
         Loads a script from path, and returns the enclosed addon.
     """
     sc = script.Script(path)
     loader = addonmanager.Loader(self.master)
     self.master.addons.invoke_addon(sc, "load", loader)
     self.configure(sc)
     self.master.addons.invoke_addon(sc, "tick")
     return sc.addons[0] if sc.addons else None
Ejemplo n.º 7
0
def test_loader():
    with taddons.context() as tctx:
        l = addonmanager.Loader(tctx.master)
        l.add_option("custom_option", bool, False, "help")
        l.add_option("custom_option", bool, False, "help")

        def cmd(a: str) -> str:
            return "foo"

        l.add_command("test.command", cmd)
Ejemplo n.º 8
0
    def configure(self, options, updated):
        if "scripts" in updated:
            for s in options.scripts:
                if options.scripts.count(s) > 1:
                    raise exceptions.OptionsError("Duplicate script: %s" % s)

            for a in ctx.master.addons.chain[:]:
                if isinstance(a, Script) and a.name not in options.scripts:
                    ctx.log.info("Un-loading script: %s" % a.name)
                    ctx.master.addons.remove(a)

            # The machinations below are to ensure that:
            #   - Scripts remain in the same order
            #   - Scripts are listed directly after the script addon. This is
            #   needed to ensure that interactions with, for instance, flow
            #   serialization remains correct.
            #   - Scripts are not initialized un-necessarily. If only a
            #   script's order in the script list has changed, it should simply
            #   be moved.

            current = {}
            for a in ctx.master.addons.chain[:]:
                if isinstance(a, Script):
                    current[a.name] = a
                    ctx.master.addons.chain.remove(a)

            ordered = []
            newscripts = []
            for s in options.scripts:
                if s in current:
                    ordered.append(current[s])
                else:
                    ctx.log.info("Loading script: %s" % s)
                    try:
                        sc = Script(s)
                    except ValueError as e:
                        raise exceptions.OptionsError(str(e))
                    ordered.append(sc)
                    newscripts.append(sc)

            ochain = ctx.master.addons.chain
            pos = ochain.index(self)
            ctx.master.addons.chain = ochain[:pos + 1] + ordered + ochain[pos +
                                                                          1:]

            for s in newscripts:
                l = addonmanager.Loader(ctx.master)
                ctx.master.addons.invoke_addon(s, "load", l)
                if self.is_running:
                    # If we're already running, we configure and tell the addon
                    # we're up and running.
                    ctx.master.addons.invoke_addon(s, "configure", options,
                                                   options.keys())
                    ctx.master.addons.invoke_addon(s, "running")
Ejemplo n.º 9
0
 def test_exception(self):
     with taddons.context() as tctx:
         sc = script.Script(
             tutils.test_data.path("mitmproxy/data/addonscripts/error.py"))
         l = addonmanager.Loader(tctx.master)
         sc.load(l)
         f = tflow.tflow(resp=True)
         sc.request(f)
         assert tctx.master.logs[0].level == "error"
         assert len(tctx.master.logs[0].msg.splitlines()) == 6
         assert re.search(
             r'addonscripts[\\/]error.py", line \d+, in request',
             tctx.master.logs[0].msg)
         assert re.search(r'addonscripts[\\/]error.py", line \d+, in mkerr',
                          tctx.master.logs[0].msg)
         assert tctx.master.logs[0].msg.endswith("ValueError: Error!\n")
Ejemplo n.º 10
0
    def test_concurrent(self):
        with taddons.context() as tctx:
            sc = script.Script(
                tutils.test_data.path(
                    "mitmproxy/data/addonscripts/concurrent_decorator.py"))
            l = addonmanager.Loader(tctx.master)
            sc.load(l)

            f1, f2 = tflow.tflow(), tflow.tflow()
            tctx.cycle(sc, f1)
            tctx.cycle(sc, f2)
            start = time.time()
            while time.time() - start < 5:
                if f1.reply.state == f2.reply.state == "committed":
                    return
            raise ValueError("Script never acked")
Ejemplo n.º 11
0
 def script_run(self, flows: typing.Sequence[flow.Flow], path: str) -> None:
     """
         Run a script on the specified flows. The script is loaded with
         default options, and all lifecycle events for each flow are
         simulated.
     """
     try:
         s = Script(path)
         l = addonmanager.Loader(ctx.master)
         ctx.master.addons.invoke_addon(s, "load", l)
         ctx.master.addons.invoke_addon(s, "configure", ctx.options.keys())
         # Script is loaded on the first tick
         ctx.master.addons.invoke_addon(s, "tick")
         for f in flows:
             for evt, arg in eventsequence.iterate(f):
                 ctx.master.addons.invoke_addon(s, evt, arg)
     except exceptions.OptionsError as e:
         raise exceptions.CommandError("Error running script: %s" % e) from e
Ejemplo n.º 12
0
def test_loader():
    with taddons.context() as tctx:
        l = addonmanager.Loader(tctx.master)
        l.add_option("custom_option", bool, False, "help")
        assert "custom_option" in l.master.options

        # calling this again with the same signature is a no-op.
        l.add_option("custom_option", bool, False, "help")
        assert not tctx.master.has_log("Over-riding existing option")

        # a different signature should emit a warning though.
        l.add_option("custom_option", bool, True, "help")
        assert tctx.master.has_log("Over-riding existing option")

        def cmd(a: str) -> str:
            return "foo"

        l.add_command("test.command", cmd)
Ejemplo n.º 13
0
async def test_loader():
    with taddons.context() as tctx:
        with mock.patch("mitmproxy.ctx.log.warn") as warn:
            l = addonmanager.Loader(tctx.master)
            l.add_option("custom_option", bool, False, "help")
            assert "custom_option" in l.master.options

            # calling this again with the same signature is a no-op.
            l.add_option("custom_option", bool, False, "help")
            assert not warn.called

            # a different signature should emit a warning though.
            l.add_option("custom_option", bool, True, "help")
            assert warn.called

            def cmd(a: str) -> str:
                return "foo"

            l.add_command("test.command", cmd)
Ejemplo n.º 14
0
def test_loader():
    with taddons.context() as tctx:
        l = addonmanager.Loader(tctx.master)
        l.add_option("custom_option", bool, False, "help")
        l.add_option("custom_option", bool, False, "help")
Ejemplo n.º 15
0
 def load_script(self):
     self.ns = load_script(self.path, self.args)
     l = addonmanager.Loader(ctx.master)
     self.run("load", l)
     if l.boot_into_addon:
         self.ns = l.boot_into_addon