Example #1
0
def _base_handler(additional_functions=None, ctx=None, data=None, loop=None):
    """This function routes calls to sub-functions, thereby allowing
       a single function to stay hot for longer. If you want
       to add additional functions then add them via the
       'additional_functions' argument. This should accept 'function'
       and 'args', returning some output if the function is found,
       or 'None' if the function is not available

       Args:
        additional_functions (function): function to be routed
        ctx: currently unused
        data (str): to be passed as arguments to other functions
        TODO - expand this
        loop: currently unused

        Returns:
            dict: JSON serialisable dict

       """

    # Make sure we set the flag to say that this code is running
    # as part of a service
    from Acquire.Service import push_is_running_service, \
        pop_is_running_service, unpack_arguments, \
        get_service_private_key, pack_return_value, \
        create_return_value

    push_is_running_service()

    result = None

    try:
        (function, args, keys) = unpack_arguments(data,
                                                  get_service_private_key)
    except Exception as e:
        function = None
        args = None
        result = e
        keys = None

    if result is None:
        try:
            result = _handle(function=function,
                             additional_functions=additional_functions,
                             args=args)
        except Exception as e:
            result = e

    result = create_return_value(payload=result)

    try:
        result = pack_return_value(payload=result, key=keys)
    except Exception as e:
        result = pack_return_value(payload=create_return_value(e))

    pop_is_running_service()
    return result
def test_json_keys():
    privkey = PrivateKey()
    pubkey = privkey.public_key()

    args = {
        "message": "Hello, this is a message",
        "status": 0,
        "long": [random.random() for _ in range(1000)]
    }

    packed = pack_arguments(args)

    crypted = pubkey.encrypt(packed)

    uncrypted = privkey.decrypt(crypted)

    unpacked = unpack_arguments(uncrypted)

    assert (args == unpacked)
Example #3
0
async def handler(ctx, data=None, loop=None):
    """This function routes calls to sub-functions, thereby allowing
       a single accounting function to stay hot for longer"""
    try:
        pr = start_profile()
    except:
        pass

    try:
        args = unpack_arguments(data, get_service_private_key)
    except Exception as e:
        result = {"status": -1,
                  "message": "Cannot unpack arguments: %s" % e}
        return json.dumps(result)
    except:
        result = {"status": -1,
                  "message": "Cannot unpack arguments: Unknown error!"}
        return json.dumps(result)

    try:
        function = str(args["function"])
    except:
        function = None

    try:
        if function is None:
            from root import run as _root
            result = _root(args)
        elif function == "create_account":
            from create_account import run as _create_account
            result = _create_account(args)
        elif function == "deposit":
            from deposit import run as _deposit
            result = _deposit(args)
        elif function == "get_account_uids":
            from get_account_uids import run as _get_account_uids
            result = _get_account_uids(args)
        elif function == "get_info":
            from get_info import run as _get_info
            result = _get_info(args)
        elif function == "perform":
            from perform import run as _perform
            result = _perform(args)
        elif function == "setup":
            from setup import run as _setup
            result = _setup(args)
        else:
            result = {"status": -1,
                      "message": "Unknown function '%s'" % function}

    except Exception as e:
        result = {"status": -1,
                  "message": "Error %s: %s" % (e.__class__, str(e))}

    try:
        end_profile(pr, result)
    except:
        pass

    try:
        return pack_return_value(result, args)
    except Exception as e:
        message = {"status": -1,
                   "message": "Error packing results: %s" % e}
        return json.dumps(message)
    except:
        message = {"status": -1,
                   "message": "Error packing results: Unknown error"}
        return json.dumps(message)
Example #4
0
async def handler(ctx, data=None, loop=None):
    """This function routes calls to sub-functions, thereby allowing
       a single identity function to stay hot for longer"""

    try:
        pr = start_profile()
    except:
        pass

    try:
        args = unpack_arguments(data, get_service_private_key)
    except Exception as e:
        result = {"status": -1,
                  "message": "Cannot unpack arguments: %s" % e}
        return json.dumps(result)
    except:
        result = {"status": -1,
                  "message": "Cannot unpack arguments: Unknown error!"}
        return json.dumps(result)

    try:
        function = str(args["function"])
    except:
        function = None

    try:
        if function is None:
            from root import run as _root
            result = _root(args)
        elif function == "request_login":
            from request_login import run as _request_login
            result = _request_login(args)
        elif function == "get_keys":
            from get_keys import run as _get_keys
            result = _get_keys(args)
        elif function == "get_status":
            from get_status import run as _get_status
            result = _get_status(args)
        elif function == "login":
            from login import run as _login
            result = _login(args)
        elif function == "logout":
            from logout import run as _logout
            result = _logout(args)
        elif function == "register":
            from register import run as _register
            result = _register(args)
        elif function == "request_login":
            from request_login import run as _request_login
            result = _request_login(args)
        elif function == "setup":
            from setup import run as _setup
            result = _setup(args)
        elif function == "whois":
            from whois import run as _whois
            result = _whois(args)
        elif function == "test":
            from test import run as _test
            result = _test(args)
        else:
            result = {"status": -1,
                      "message": "Unknown function '%s'" % function}

    except Exception as e:
        result = {"status": -1,
                  "message": "Error %s: %s" % (e.__class__, str(e))}

    try:
        end_profile(pr, result)
    except:
        pass

    try:
        return pack_return_value(result, args)
    except Exception as e:
        message = {"status": -1,
                   "message": "Error packing results: %s" % e}
        return json.dumps(message)
    except:
        message = {"status": -1,
                   "message": "Error packing results: Unknown error"}
        return json.dumps(message)
def test_pack_unpack_args_returnvals():
    privkey = get_private_key("testing")
    pubkey = privkey.public_key()

    args = {"message": "Hello, this is a message",
            "status": 0,
            "long": [random.random() for _ in range(2)]}

    func = "test_function"

    packed = pack_arguments(function=func, args=args)

    crypted = pubkey.encrypt(packed)

    uncrypted = privkey.decrypt(crypted)

    (f, unpacked, keys) = unpack_arguments(args=uncrypted)

    print(keys)

    assert(args == unpacked)
    assert(f == func)

    packed = pack_arguments(function=func, args=args,
                            key=pubkey, response_key=pubkey,
                            public_cert=pubkey)

    data = json.loads(packed.decode("utf-8"))

    assert(data["encrypted"])
    assert(data["fingerprint"] == privkey.fingerprint())

    payload = privkey.decrypt(string_to_bytes(data["data"]))
    payload = json.loads(payload)

    assert(payload["sign_with_service_key"] == privkey.fingerprint())
    assert(payload["encryption_public_key"] == bytes_to_string(pubkey.bytes()))
    assert(payload["payload"] == args)

    (f, unpacked, keys) = unpack_arguments(function=func, args=packed,
                                           key=privkey)

    message = {"message": "OK"}

    return_value = create_return_value(message)

    packed_result = pack_return_value(function=func,
                                      payload=return_value, key=keys,
                                      private_cert=privkey)

    result = json.loads(packed_result.decode("utf-8"))

    assert(result["fingerprint"] == privkey.fingerprint())
    assert(result["encrypted"])
    data = string_to_bytes(result["data"])
    sig = string_to_bytes(result["signature"])

    pubkey.verify(signature=sig, message=data)

    data = json.loads(privkey.decrypt(data))

    assert(data["payload"]["return"] == message)

    result = unpack_return_value(return_value=packed_result,
                                 key=privkey, public_cert=pubkey)

    assert(result == message)

    try:
        return_value = create_return_value(_foo())
    except Exception as e:
        return_value = create_return_value(e)

    packed_result = pack_return_value(function=func,
                                      payload=return_value, key=keys,
                                      private_cert=privkey)

    with pytest.raises(PermissionError):
        result = unpack_return_value(function=func, return_value=packed_result,
                                     key=privkey, public_cert=pubkey)