Exemplo n.º 1
0
    def __init__(
        self,
        eth_address: str = None,
        password: str = None,
        access_token: str = None,
        refresh_token: str = None,
        handler: APIHandler = None,
        staging: bool = False,
        no_cache: bool = False,
        middlewares: List[BaseMiddleware] = None,
    ):
        self.eth_address = eth_address
        self.password = password

        if not middlewares:
            # initialize without custom middlewares
            middlewares = [
                ClientToolNameMiddleware(),
                AnalysisCacheMiddleware(no_cache),
            ]
        else:
            # add tool name and analysis cache middleware
            type_list = [type(m) for m in middlewares]
            if ClientToolNameMiddleware not in type_list:
                middlewares.append(ClientToolNameMiddleware())
            if AnalysisCacheMiddleware not in type_list:
                middlewares.append(AnalysisCacheMiddleware(no_cache))

        self.handler = handler or APIHandler(middlewares=middlewares,
                                             staging=staging)

        self.access_token = access_token
        self.refresh_token = refresh_token
Exemplo n.º 2
0
def test_custom_middlewares():
    assert_middlewares(Client())
    assert_middlewares(Client(middlewares=None))
    assert_middlewares(Client(middlewares=[]))
    assert_middlewares(Client(middlewares=[AnalysisCacheMiddleware()]))
    assert_middlewares(Client(middlewares=[ClientToolNameMiddleware()]))
    assert_middlewares(
        Client(middlewares=[AnalysisCacheMiddleware(), ClientToolNameMiddleware()])
    )
Exemplo n.º 3
0
def main():
    parser = argparse.ArgumentParser(
        description="Submit analysis to MythX API")
    create_parser(parser)
    args = parser.parse_args()

    config["endpoints"]["production"] = args.api_url

    handler = APIHandler(middlewares=[
        ClientToolNameMiddleware(name="ApiTests"),
        AnalysisCacheMiddleware(no_cache=args.no_cache),
    ])
    logging.info(f"Running MythX API tests without cache: {args.no_cache}")
    c = Client(eth_address=ETH_ADDRESS, password=PASSWORD, handler=handler)
    logging.info(f"Submit analysis to API: {args.api_url}")
    resp = c.analyze(**API_PAYLOAD)
    logging.info(resp.to_dict())

    while not c.analysis_ready(resp.uuid):
        logging.info("Checking analysis status")
        time.sleep(1)

    issues = c.report(resp.uuid)
    detected_issues = issues.to_dict()
    logging.info(json.dumps(detected_issues, indent=2))
    return detected_issues
Exemplo n.º 4
0
def cli(ctx, **kwargs):
    """Your CLI for interacting with https://mythx.io/
    \f

    :param ctx: Click context holding group-level parameters
    :param debug: Boolean to enable the `logging` debug mode
    :param api_key: User JWT access token from the MythX dashboard
    :param username: The MythX account ETH address/username
    :param password: The account password from the MythX dashboard
    :param fmt: The formatter to use for the subcommand output
    :param ci: Boolean to return exit code 1 on medium/high-sev issues
    :param output: Output file to write the results into
    """

    ctx.obj = dict(kwargs)
    ctx.obj["retval"] = 0
    toolname_mw = ClientToolNameMiddleware(
        name="mythx-cli-{}".format(__version__))
    if kwargs["api_key"] is not None:
        ctx.obj["client"] = Client(access_token=kwargs["api_key"],
                                   middlewares=[toolname_mw])
    elif kwargs["username"] and kwargs["password"]:
        ctx.obj["client"] = Client(eth_address=kwargs["username"],
                                   password=kwargs["password"],
                                   middlewares=[toolname_mw])
    else:
        raise click.UsageError((
            "The trial user has been deprecated. You can still use the MythX CLI for free "
            "by signing up for a free account at https://mythx.io/ and entering your access "
            "credentials."))
    if kwargs["debug"]:
        for name in logging.root.manager.loggerDict:
            logging.getLogger(name).setLevel(logging.DEBUG)
Exemplo n.º 5
0
def cli(ctx, **kwargs):
    """Your CLI for interacting with https://mythx.io/
    \f

    :param ctx: Click context holding group-level parameters
    :param debug: Boolean to enable the `logging` debug mode
    :param access_token: User JWT access token from the MythX dashboard
    :param eth_address: The MythX account ETH address/username
    :param password: The account password from the MythX dashboard
    :param staging: Boolean to redirect requests to MythX staging
    :param fmt: The formatter to use for the subcommand output
    """

    ctx.obj = dict(kwargs)
    toolname_mw = ClientToolNameMiddleware(
        name="mythx-cli-{}".format(__version__))
    if kwargs["access_token"] is not None:
        ctx.obj["client"] = Client(
            access_token=kwargs["access_token"],
            staging=kwargs["staging"],
            middlewares=[toolname_mw],
        )
    elif kwargs["eth_address"] and kwargs["password"]:
        ctx.obj["client"] = Client(
            eth_address=kwargs["eth_address"],
            password=kwargs["password"],
            staging=kwargs["staging"],
            middlewares=[toolname_mw],
        )
    else:
        # default to trial user client
        ctx.obj["client"] = Client(
            eth_address="0x0000000000000000000000000000000000000000",
            password="******",
            staging=kwargs["staging"],
            middlewares=[toolname_mw],
        )
    if kwargs["debug"]:
        for name in logging.root.manager.loggerDict:
            logging.getLogger(name).setLevel(logging.DEBUG)

    return 0
Exemplo n.º 6
0
def get_mythx_client():
    # if both eth address and username are None,
    if ARGV["access-token"]:
        authenticated = True
        auth_args = {"access_token": ARGV["access-token"]}
    elif ARGV["eth-address"] and ARGV["password"]:
        authenticated = True
        auth_args = {
            "eth_address": ARGV["eth-address"],
            "password": ARGV["password"]
        }
    elif environ.get("MYTHX_ACCESS_TOKEN"):
        authenticated = True
        auth_args = {"access_token": environ.get("MYTHX_ACCESS_TOKEN")}
    elif environ.get("MYTHX_ETH_ADDRESS") and environ.get("MYTHX_PASSWORD"):
        authenticated = True
        auth_args = {
            "eth_address": environ.get("MYTHX_ETH_ADDRESS"),
            "password": environ.get("MYTHX_PASSWORD"),
        }
    else:
        authenticated = False
        auth_args = {
            "eth_address": "0x0000000000000000000000000000000000000000",
            "password": "******",
        }

    return (
        Client(
            **auth_args,
            middlewares=[
                ClientToolNameMiddleware(name="brownie-{}".format(__version__))
            ],
        ),
        authenticated,
    )
Exemplo n.º 7
0
def cli(
    ctx,
    debug: bool,
    api_key: str,
    username: str,
    password: str,
    fmt: str,
    ci: bool,
    output: str,
    yes: bool,
    config: str,
    stdout: bool,
) -> None:
    """Your CLI for interacting with https://mythx.io/

    \f

    :param ctx: Click context holding group-level parameters
    :param debug: Boolean to enable the `logging` debug mode
    :param api_key: User JWT api token from the MythX dashboard
    :param username: The MythX account ETH address/username
    :param password: The account password from the MythX dashboard
    :param fmt: The formatter to use for the subcommand output
    :param ci: Boolean to return exit code 1 on medium/high-sev issues
    :param output: Output file to write the results into
    :param config: YAML config file to read default parameters from
    :param stdout: Force printing to stdout and ignore output files
    """

    # set loggers to debug mode
    if debug:
        for name in logging.root.manager.loggerDict:
            logging.getLogger(name).setLevel(logging.DEBUG)

    ctx.obj = {
        "debug": debug,
        "api_key": api_key,
        "username": username,
        "password": password,
        "fmt": fmt,
        "ci": ci,
        "output": output,
        "yes": yes,
        "config": config,
    }

    LOGGER.debug("Initializing configuration context")
    config_file = config or ".mythx.yml"
    if Path(config_file).is_file():
        LOGGER.debug(f"Parsing config at {config_file}")
        with open(config_file) as config_f:
            parsed_config = yaml.safe_load(config_f.read())
    else:
        parsed_config = {"analyze": {}}

    # The analyze context is updated separately in the command
    # implementation
    ctx.obj["analyze"] = parsed_config.get("analyze", {})

    # overwrite context with top-level YAML config keys if necessary
    update_context(ctx.obj, "ci", parsed_config, "ci", False)
    if stdout:
        # if forced stdout, don't set output file
        ctx.obj["output"] = None
    else:
        update_context(ctx.obj, "output", parsed_config, "output", None)
    update_context(ctx.obj, "fmt", parsed_config, "format", "table")
    update_context(ctx.obj, "yes", parsed_config, "confirm", False)

    # set return value - used for CI failures
    ctx.obj["retval"] = 0

    LOGGER.debug(f"Initializing tool name middleware with {__version__}")
    toolname_mw = ClientToolNameMiddleware(
        name="mythx-cli-{}".format(__version__))

    if api_key is not None:
        LOGGER.debug("Initializing client with API key")
        ctx.obj["client"] = Client(api_key=api_key, middlewares=[toolname_mw])
    elif username and password:
        LOGGER.debug("Initializing client with username and password")
        ctx.obj["client"] = Client(username=username,
                                   password=password,
                                   middlewares=[toolname_mw])
    else:
        raise click.UsageError((
            "The trial user has been deprecated. You can still use the MythX CLI for free "
            "by signing up for a free account at https://mythx.io/ and entering your access "
            "credentials."))
Exemplo n.º 8
0
)
from mythx_models.response import (
    AnalysisListResponse,
    AnalysisStatusResponse,
    AnalysisSubmissionResponse,
    AuthLoginResponse,
    AuthLogoutResponse,
    AuthRefreshResponse,
    DetectedIssuesResponse,
)

from pythx.middleware.toolname import ClientToolNameMiddleware

from .common import generate_request_dict, get_test_case

DEFAULT_CTN_MIDDLEWARE = ClientToolNameMiddleware()
CUSTOM_CTN_MIDDLEWARE = ClientToolNameMiddleware(name="test")


@pytest.mark.parametrize(
    "middleware,request_dict,name_added",
    [
        (
            DEFAULT_CTN_MIDDLEWARE,
            generate_request_dict(
                get_test_case("testdata/analysis-list-request.json",
                              AnalysisListRequest)),
            False,
        ),
        (
            DEFAULT_CTN_MIDDLEWARE,