Exemple #1
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
Exemple #2
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
Exemple #3
0
def test_send_request_unauthenticated(requests_mock):
    requests_mock.get("mock://test.com/path", text="resp", status_code=400)
    with pytest.raises(MythXAPIError):
        APIHandler.send_request({
            "method": "GET",
            "headers": {},
            "url": testdata.MOCK_API_URL,
            "payload": {},
            "params": {},
        })

    assert requests_mock.called == 1
    h = requests_mock.request_history[0]
    assert h.method == "GET"
    assert h.url == testdata.MOCK_API_URL
    assert h.headers.get("Authorization") is None
Exemple #4
0
def test_send_request_failure(requests_mock):
    requests_mock.get("mock://test.com/path", text="resp", status_code=400)
    with pytest.raises(MythXAPIError):
        APIHandler.send_request(
            {
                "method": "GET",
                "headers": {},
                "url": testdata.MOCK_API_URL,
                "payload": {},
                "params": {},
            },
            auth_header={"Authorization": "Bearer foo"},
        )

    assert requests_mock.called == 1
    h = requests_mock.request_history[0]
    assert h.method == "GET"
    assert h.url == testdata.MOCK_API_URL
    assert h.headers["Authorization"] == "Bearer foo"
Exemple #5
0
    def __init__(
        self,
        username: str = None,
        password: str = None,
        api_key: str = None,
        refresh_token: str = None,
        handler: APIHandler = None,
        no_cache: bool = False,
        middlewares: List[BaseMiddleware] = None,
        api_url: str = None,
    ):
        """Instantiate a new MythX API client.

        Please note that it is not recommended to authenticate with the MythX API
        using username and password. The preferred method should be by passing the API
        key obtained from the dashboard at https://dashboard.mythx.io/ by either
        providing it as a parameter, or setting the :code:`MYTHX_API_KEY` environment
        variable.

        If a login action using username and password is chosen, the API key and JWT
        refresh token are set internally if the login attempt was successful.

        The middleware list and the API URL are directly forwarded to the API handler
        class unless a custom instance has already been provided.

        :param username: The MythX account's username
        :param password: The MythX account's password
        :param api_key: The MythX API key from the dashboard
        :param refresh_token: The JWT refresh token
        :param handler: Use a custom API handler instance
        :param no_cache: Disable the cache (special privileges required)
        :param middlewares: A list of custom middlewares to include
        :param api_url: A custom API endpoint for dedicated MythX deployments
        """
        self.username = username
        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,
                                             api_url=api_url)
        self.api_key = api_key
        self.refresh_token = refresh_token
Exemple #6
0
def test_send_request_successful(requests_mock):
    requests_mock.get("mock://test.com/path", text="resp")
    resp = APIHandler.send_request(
        {
            "method": "GET",
            "headers": {},
            "url": testdata.MOCK_API_URL,
            "payload": {},
            "params": {},
        },
        auth_header={"Authorization": "Bearer foo"},
    )
    assert resp == "resp"
    assert requests_mock.called == 1
    h = requests_mock.request_history[0]
    assert h.method == "GET"
    assert h.url == testdata.MOCK_API_URL
    assert h.headers["Authorization"] == "Bearer foo"
Exemple #7
0
def test_send_request_successful(requests_mock):
    test_url = "mock://test.com/path"
    requests_mock.get(test_url, text='{"resp":"test"}')
    resp = APIHandler.send_request(
        {
            "method": "GET",
            "headers": {},
            "url": test_url,
            "payload": {},
            "params": {}
        },
        auth_header={"Authorization": "Bearer foo"},
    )
    assert resp == {"resp": "test"}
    assert requests_mock.called == 1
    h = requests_mock.request_history[0]
    assert h.method == "GET"
    assert h.url == test_url
    assert h.headers["Authorization"] == "Bearer foo"
Exemple #8
0
def test_middleware_default_empty():
    assert APIHandler().middlewares == []
Exemple #9
0
from pythx.middleware.base import BaseMiddleware

from .common import get_test_case


class TestMiddleware(BaseMiddleware):
    def process_request(self, req):
        req["test"] = "test"
        return req

    def process_response(self, resp):
        resp.test = "test"
        return resp


API_HANDLER = APIHandler(middlewares=[TestMiddleware()])


def assert_request_dict_keys(d):
    assert d.get("method") is not None
    assert d.get("payload") is not None
    assert d.get("headers") is not None
    assert d.get("url") is not None
    assert d.get("params") is not None


def assert_request_dict_content(d, request_obj):
    assert d["method"] == request_obj.method
    assert d["payload"] == request_obj.payload
    assert d["headers"] == request_obj.headers
    assert d["params"] == request_obj.parameters
Exemple #10
0
from mythx_models.exceptions import MythXAPIError

from . import common as testdata


class TestMiddleware(BaseMiddleware):
    def process_request(self, req):
        req["test"] = "test"
        return req

    def process_response(self, resp):
        resp.test = "test"
        return resp


STAGING_HANDLER = APIHandler(middlewares=[TestMiddleware()], staging=True)
PROD_HANDLER = APIHandler(middlewares=[TestMiddleware()])


def assert_request_dict_keys(d):
    assert d.get("method") is not None
    assert d.get("payload") is not None
    assert d.get("headers") is not None
    assert d.get("url") is not None
    assert d.get("params") is not None


def assert_request_dict_content(d, request_obj):
    assert d["method"] == request_obj.method
    assert d["payload"] == request_obj.payload
    assert d["headers"] == request_obj.headers