mirror of
https://github.com/vee1e/mitmproxy.git
synced 2026-09-02 18:57:22 +00:00
Bumps the github-actions group with 3 updates: [install-pinned/ruff](https://github.com/install-pinned/ruff), [apple-actions/import-codesign-certs](https://github.com/apple-actions/import-codesign-certs) and [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action). Updates `install-pinned/ruff` from fe472defb50a6a2c00ea3a3982534e86e69991e8 to 38b373a3a8635c2be31d92314e816a491fda910a <details> <summary>Commits</summary> <ul> <li><a href="38b373a3a8"><code>38b373a</code></a> update README.md (ruff 0.3.0)</li> <li><a href="06af3ea1c3"><code>06af3ea</code></a> update pins (ruff 0.3.0)</li> <li><a href="be1c354876"><code>be1c354</code></a> update README.md (ruff 0.2.2)</li> <li><a href="c9779bbd5b"><code>c9779bb</code></a> update pins (ruff 0.2.2)</li> <li><a href="48831a86ce"><code>48831a8</code></a> update README.md (ruff 0.2.1)</li> <li><a href="6775b5f352"><code>6775b5f</code></a> update pins (ruff 0.2.1)</li> <li><a href="bc12a64c2f"><code>bc12a64</code></a> update README.md (ruff 0.2.0)</li> <li><a href="3b8cceff45"><code>3b8ccef</code></a> update pins (ruff 0.2.0)</li> <li>See full diff in <a href="fe472defb5...38b373a3a8">compare view</a></li> </ul> </details> <br /> Updates `apple-actions/import-codesign-certs` from 5565bb656f60c98c8fc515f3444dd8db73545dc2 to 493007ed063995cf2d4fbca064704150548f8bb5 <details> <summary>Commits</summary> <ul> <li><a href="493007ed06"><code>493007e</code></a> Merge pull request <a href="https://redirect.github.com/apple-actions/import-codesign-certs/issues/62">#62</a> from himself65/patch-1</li> <li><a href="2e5aa07267"><code>2e5aa07</code></a> Update README.md</li> <li>See full diff in <a href="5565bb656f...493007ed06">compare view</a></li> </ul> </details> <br /> Updates `docker/setup-buildx-action` from 3.0.0 to 3.1.0 <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/docker/setup-buildx-action/releases">docker/setup-buildx-action's releases</a>.</em></p> <blockquote> <h2>v3.1.0</h2> <ul> <li><code>cache-binary</code> input to enable/disable caching binary to GHA cache backend by <a href="https://github.com/crazy-max"><code>@crazy-max</code></a> in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/300">docker/setup-buildx-action#300</a></li> <li>build(deps): bump <code>@babel/traverse</code> from 7.17.3 to 7.23.2 in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/282">docker/setup-buildx-action#282</a></li> <li>build(deps): bump <code>@docker/actions-toolkit</code> from 0.12.0 to 0.17.0 in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/281">docker/setup-buildx-action#281</a> <a href="https://redirect.github.com/docker/setup-buildx-action/pull/284">docker/setup-buildx-action#284</a> <a href="https://redirect.github.com/docker/setup-buildx-action/pull/299">docker/setup-buildx-action#299</a></li> <li>build(deps): bump uuid from 9.0.0 to 9.0.1 in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/271">docker/setup-buildx-action#271</a></li> <li>build(deps): bump undici from 5.26.3 to 5.28.3 in <a href="https://redirect.github.com/docker/setup-buildx-action/pull/297">docker/setup-buildx-action#297</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/docker/setup-buildx-action/compare/v3.0.0...v3.1.0">https://github.com/docker/setup-buildx-action/compare/v3.0.0...v3.1.0</a></p> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="0d103c3126"><code>0d103c3</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-buildx-action/issues/300">#300</a> from crazy-max/cache-binary</li> <li><a href="f19477aacd"><code>f19477a</code></a> chore: update generated content</li> <li><a href="a4180f835d"><code>a4180f8</code></a> cache-binary input to enable/disable caching binary to GHA cache backend</li> <li><a href="524315340d"><code>5243153</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-buildx-action/issues/299">#299</a> from docker/dependabot/npm_and_yarn/docker/actions-to...</li> <li><a href="3679a54023"><code>3679a54</code></a> chore: update generated content</li> <li><a href="37a22a2fb2"><code>37a22a2</code></a> build(deps): bump <code>@docker/actions-toolkit</code> from 0.14.0 to 0.17.0</li> <li><a href="65afe610a1"><code>65afe61</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-buildx-action/issues/297">#297</a> from docker/dependabot/npm_and_yarn/undici-5.28.3</li> <li><a href="fcb8f722fd"><code>fcb8f72</code></a> chore: update generated content</li> <li><a href="f62b9a17c0"><code>f62b9a1</code></a> Merge pull request <a href="https://redirect.github.com/docker/setup-buildx-action/issues/298">#298</a> from crazy-max/bump-gha</li> <li><a href="74c5b717e5"><code>74c5b71</code></a> bump codecov/codecov-action from 3 to 4</li> <li>Additional commits viewable in <a href="f95db51fdd...0d103c3126">compare view</a></li> </ul> </details> <br /> Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore <dependency name> major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) - `@dependabot ignore <dependency name> minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) - `@dependabot ignore <dependency name>` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) - `@dependabot unignore <dependency name>` will remove all of the ignore conditions of the specified dependency - `@dependabot unignore <dependency name> <ignore condition>` will remove the ignore condition of the specified dependency and ignore conditions </details> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
342 lines
11 KiB
Python
342 lines
11 KiB
Python
"""
|
|
This module manages and invokes typed commands.
|
|
"""
|
|
|
|
import functools
|
|
import inspect
|
|
import logging
|
|
import sys
|
|
import textwrap
|
|
import types
|
|
from collections.abc import Callable
|
|
from collections.abc import Iterable
|
|
from collections.abc import Sequence
|
|
from typing import Any
|
|
from typing import NamedTuple
|
|
|
|
import pyparsing
|
|
|
|
import mitmproxy.types
|
|
from mitmproxy import command_lexer
|
|
from mitmproxy import exceptions
|
|
from mitmproxy.command_lexer import unquote
|
|
|
|
|
|
def verify_arg_signature(f: Callable, args: Iterable[Any], kwargs: dict) -> None:
|
|
sig = inspect.signature(f, eval_str=True)
|
|
try:
|
|
sig.bind(*args, **kwargs)
|
|
except TypeError as v:
|
|
raise exceptions.CommandError("command argument mismatch: %s" % v.args[0])
|
|
|
|
|
|
def typename(t: type) -> str:
|
|
"""
|
|
Translates a type to an explanatory string.
|
|
"""
|
|
if t == inspect._empty: # type: ignore
|
|
raise exceptions.CommandError("missing type annotation")
|
|
to = mitmproxy.types.CommandTypes.get(t, None)
|
|
if not to:
|
|
raise exceptions.CommandError(
|
|
"unsupported type: %s" % getattr(t, "__name__", t)
|
|
)
|
|
return to.display
|
|
|
|
|
|
def _empty_as_none(x: Any) -> Any:
|
|
if x == inspect.Signature.empty:
|
|
return None
|
|
return x
|
|
|
|
|
|
class CommandParameter(NamedTuple):
|
|
name: str
|
|
type: type
|
|
kind: inspect._ParameterKind = inspect.Parameter.POSITIONAL_OR_KEYWORD
|
|
|
|
def __str__(self):
|
|
if self.kind is inspect.Parameter.VAR_POSITIONAL:
|
|
return f"*{self.name}"
|
|
else:
|
|
return self.name
|
|
|
|
|
|
class Command:
|
|
name: str
|
|
manager: "CommandManager"
|
|
signature: inspect.Signature
|
|
help: str | None
|
|
|
|
def __init__(self, manager: "CommandManager", name: str, func: Callable) -> None:
|
|
self.name = name
|
|
self.manager = manager
|
|
self.func = func
|
|
self.signature = inspect.signature(self.func, eval_str=True)
|
|
|
|
if func.__doc__:
|
|
txt = func.__doc__.strip()
|
|
self.help = "\n".join(textwrap.wrap(txt))
|
|
else:
|
|
self.help = None
|
|
|
|
# This fails with a CommandException if types are invalid
|
|
for name, parameter in self.signature.parameters.items():
|
|
t = parameter.annotation
|
|
if not mitmproxy.types.CommandTypes.get(parameter.annotation, None):
|
|
raise exceptions.CommandError(
|
|
f"Argument {name} has an unknown type {t} in {func}."
|
|
)
|
|
if self.return_type and not mitmproxy.types.CommandTypes.get(
|
|
self.return_type, None
|
|
):
|
|
raise exceptions.CommandError(
|
|
f"Return type has an unknown type ({self.return_type}) in {func}."
|
|
)
|
|
|
|
@property
|
|
def return_type(self) -> type | None:
|
|
return _empty_as_none(self.signature.return_annotation)
|
|
|
|
@property
|
|
def parameters(self) -> list[CommandParameter]:
|
|
"""Returns a list of CommandParameters."""
|
|
ret = []
|
|
for name, param in self.signature.parameters.items():
|
|
ret.append(CommandParameter(name, param.annotation, param.kind))
|
|
return ret
|
|
|
|
def signature_help(self) -> str:
|
|
params = " ".join(str(param) for param in self.parameters)
|
|
if self.return_type:
|
|
ret = f" -> {typename(self.return_type)}"
|
|
else:
|
|
ret = ""
|
|
return f"{self.name} {params}{ret}"
|
|
|
|
def prepare_args(self, args: Sequence[str]) -> inspect.BoundArguments:
|
|
try:
|
|
bound_arguments = self.signature.bind(*args)
|
|
except TypeError:
|
|
expected = f"Expected: {str(self.signature.parameters)}"
|
|
received = f"Received: {str(args)}"
|
|
raise exceptions.CommandError(
|
|
f"Command argument mismatch: \n {expected}\n {received}"
|
|
)
|
|
|
|
for name, value in bound_arguments.arguments.items():
|
|
param = self.signature.parameters[name]
|
|
convert_to = param.annotation
|
|
if param.kind == param.VAR_POSITIONAL:
|
|
bound_arguments.arguments[name] = tuple(
|
|
parsearg(self.manager, x, convert_to) for x in value
|
|
)
|
|
else:
|
|
bound_arguments.arguments[name] = parsearg(
|
|
self.manager, value, convert_to
|
|
)
|
|
|
|
bound_arguments.apply_defaults()
|
|
|
|
return bound_arguments
|
|
|
|
def call(self, args: Sequence[str]) -> Any:
|
|
"""
|
|
Call the command with a list of arguments. At this point, all
|
|
arguments are strings.
|
|
"""
|
|
bound_args = self.prepare_args(args)
|
|
ret = self.func(*bound_args.args, **bound_args.kwargs)
|
|
if ret is None and self.return_type is None:
|
|
return
|
|
typ = mitmproxy.types.CommandTypes.get(self.return_type)
|
|
assert typ
|
|
if not typ.is_valid(self.manager, typ, ret):
|
|
raise exceptions.CommandError(
|
|
f"{self.name} returned unexpected data - expected {typ.display}"
|
|
)
|
|
return ret
|
|
|
|
|
|
class ParseResult(NamedTuple):
|
|
value: str
|
|
type: type
|
|
valid: bool
|
|
|
|
|
|
class CommandManager:
|
|
commands: dict[str, Command]
|
|
|
|
def __init__(self, master):
|
|
self.master = master
|
|
self.commands = {}
|
|
|
|
def collect_commands(self, addon):
|
|
for i in dir(addon):
|
|
if not i.startswith("__"):
|
|
o = getattr(addon, i)
|
|
try:
|
|
# hasattr is not enough, see https://github.com/mitmproxy/mitmproxy/issues/3794
|
|
is_command = isinstance(getattr(o, "command_name", None), str)
|
|
except Exception:
|
|
pass # getattr may raise if o implements __getattr__.
|
|
else:
|
|
if is_command:
|
|
try:
|
|
self.add(o.command_name, o)
|
|
except exceptions.CommandError as e:
|
|
logging.warning(
|
|
f"Could not load command {o.command_name}: {e}"
|
|
)
|
|
|
|
def add(self, path: str, func: Callable):
|
|
self.commands[path] = Command(self, path, func)
|
|
|
|
@functools.lru_cache(maxsize=128)
|
|
def parse_partial(
|
|
self, cmdstr: str
|
|
) -> tuple[Sequence[ParseResult], Sequence[CommandParameter]]:
|
|
"""
|
|
Parse a possibly partial command. Return a sequence of ParseResults and a sequence of remainder type help items.
|
|
"""
|
|
|
|
parts: pyparsing.ParseResults = command_lexer.expr.parseString(
|
|
cmdstr, parseAll=True
|
|
)
|
|
|
|
parsed: list[ParseResult] = []
|
|
next_params: list[CommandParameter] = [
|
|
CommandParameter("", mitmproxy.types.Cmd),
|
|
CommandParameter("", mitmproxy.types.CmdArgs),
|
|
]
|
|
expected: CommandParameter | None = None
|
|
for part in parts:
|
|
if part.isspace():
|
|
parsed.append(
|
|
ParseResult(
|
|
value=part,
|
|
type=mitmproxy.types.Space,
|
|
valid=True,
|
|
)
|
|
)
|
|
continue
|
|
|
|
if expected and expected.kind is inspect.Parameter.VAR_POSITIONAL:
|
|
assert not next_params
|
|
elif next_params:
|
|
expected = next_params.pop(0)
|
|
else:
|
|
expected = CommandParameter("", mitmproxy.types.Unknown)
|
|
|
|
arg_is_known_command = (
|
|
expected.type == mitmproxy.types.Cmd and part in self.commands
|
|
)
|
|
arg_is_unknown_command = (
|
|
expected.type == mitmproxy.types.Cmd and part not in self.commands
|
|
)
|
|
command_args_following = (
|
|
next_params and next_params[0].type == mitmproxy.types.CmdArgs
|
|
)
|
|
if arg_is_known_command and command_args_following:
|
|
next_params = self.commands[part].parameters + next_params[1:]
|
|
if arg_is_unknown_command and command_args_following:
|
|
next_params.pop(0)
|
|
|
|
to = mitmproxy.types.CommandTypes.get(expected.type, None)
|
|
valid = False
|
|
if to:
|
|
try:
|
|
to.parse(self, expected.type, part)
|
|
except ValueError:
|
|
valid = False
|
|
else:
|
|
valid = True
|
|
|
|
parsed.append(
|
|
ParseResult(
|
|
value=part,
|
|
type=expected.type,
|
|
valid=valid,
|
|
)
|
|
)
|
|
|
|
return parsed, next_params
|
|
|
|
def call(self, command_name: str, *args: Any) -> Any:
|
|
"""
|
|
Call a command with native arguments. May raise CommandError.
|
|
"""
|
|
if command_name not in self.commands:
|
|
raise exceptions.CommandError("Unknown command: %s" % command_name)
|
|
return self.commands[command_name].func(*args)
|
|
|
|
def call_strings(self, command_name: str, args: Sequence[str]) -> Any:
|
|
"""
|
|
Call a command using a list of string arguments. May raise CommandError.
|
|
"""
|
|
if command_name not in self.commands:
|
|
raise exceptions.CommandError("Unknown command: %s" % command_name)
|
|
|
|
return self.commands[command_name].call(args)
|
|
|
|
def execute(self, cmdstr: str) -> Any:
|
|
"""
|
|
Execute a command string. May raise CommandError.
|
|
"""
|
|
parts, _ = self.parse_partial(cmdstr)
|
|
if not parts:
|
|
raise exceptions.CommandError(f"Invalid command: {cmdstr!r}")
|
|
command_name, *args = (
|
|
unquote(part.value) for part in parts if part.type != mitmproxy.types.Space
|
|
)
|
|
return self.call_strings(command_name, args)
|
|
|
|
def dump(self, out=sys.stdout) -> None:
|
|
cmds = list(self.commands.values())
|
|
cmds.sort(key=lambda x: x.signature_help())
|
|
for c in cmds:
|
|
for hl in (c.help or "").splitlines():
|
|
print("# " + hl, file=out)
|
|
print(c.signature_help(), file=out)
|
|
print(file=out)
|
|
|
|
|
|
def parsearg(manager: CommandManager, spec: str, argtype: type) -> Any:
|
|
"""
|
|
Convert a string to a argument to the appropriate type.
|
|
"""
|
|
t = mitmproxy.types.CommandTypes.get(argtype, None)
|
|
if not t:
|
|
raise exceptions.CommandError(f"Unsupported argument type: {argtype}")
|
|
try:
|
|
return t.parse(manager, argtype, spec)
|
|
except ValueError as e:
|
|
raise exceptions.CommandError(str(e)) from e
|
|
|
|
|
|
def command(name: str | None = None):
|
|
def decorator(function):
|
|
@functools.wraps(function)
|
|
def wrapper(*args, **kwargs):
|
|
verify_arg_signature(function, args, kwargs)
|
|
return function(*args, **kwargs)
|
|
|
|
wrapper.__dict__["command_name"] = name or function.__name__.replace("_", ".")
|
|
return wrapper
|
|
|
|
return decorator
|
|
|
|
|
|
def argument(name, type):
|
|
"""
|
|
Set the type of a command argument at runtime. This is useful for more
|
|
specific types such as mitmproxy.types.Choice, which we cannot annotate
|
|
directly as mypy does not like that.
|
|
"""
|
|
|
|
def decorator(f: types.FunctionType) -> types.FunctionType:
|
|
assert name in f.__annotations__
|
|
f.__annotations__[name] = type
|
|
return f
|
|
|
|
return decorator
|