예제 #1
0
def validate_id_value(value, field_name):
    if not isinstance(value, str):
        raise Http400(
            "{} must be string.".format(field_name),
            error_code=ErrorCode.MESSAGE_VALUE_WRONG_TYPE,
        )

    if value == '':
        raise Http400(
            "{} cannot be blank.".format(field_name),
            error_code=ErrorCode.MESSAGE_VALUE_BLANK,
        )

    if len(value) > MESSAGE_TASK_ID_MAX_LENGTH:
        raise Http400(
            "{} cannot be longer than {} chars.".format(
                field_name, MESSAGE_TASK_ID_MAX_LENGTH),
            error_code=ErrorCode.MESSAGE_VALUE_WRONG_LENGTH,
        )

    if VALID_ID_REGEX.fullmatch(value) is None:
        raise Http400(
            f'{field_name} must contain only alphanumeric chars.',
            error_code=ErrorCode.MESSAGE_VALUE_NOT_ALLOWED,
        )
예제 #2
0
def validate_ethereum_addresses(requestor_ethereum_address,
                                provider_ethereum_address):
    if not isinstance(requestor_ethereum_address, str):
        raise Http400(
            "Requestor's ethereum address must be a string",
            error_code=ErrorCode.MESSAGE_VALUE_NOT_STRING,
        )

    if not isinstance(provider_ethereum_address, str):
        raise Http400(
            "Provider's ethereum address must be a string",
            error_code=ErrorCode.MESSAGE_VALUE_NOT_STRING,
        )

    if not len(requestor_ethereum_address) == ETHEREUM_ADDRESS_LENGTH:
        raise Http400(
            f"Requestor's ethereum address must contains exactly {ETHEREUM_ADDRESS_LENGTH} characters ",
            error_code=ErrorCode.MESSAGE_VALUE_WRONG_LENGTH,
        )

    if not len(provider_ethereum_address) == ETHEREUM_ADDRESS_LENGTH:
        raise Http400(
            f"Provider's ethereum address must contains exactly {ETHEREUM_ADDRESS_LENGTH} characters ",
            error_code=ErrorCode.MESSAGE_VALUE_WRONG_LENGTH,
        )
예제 #3
0
def validate_task_to_compute(task_to_compute: message.TaskToCompute):
    if not isinstance(task_to_compute, message.TaskToCompute):
        raise Http400(
            f"Expected TaskToCompute instead of {type(task_to_compute).__name__}.",
            error_code=ErrorCode.MESSAGE_INVALID,
        )

    if any(
            map(lambda x: x is None, [
                getattr(task_to_compute, attribute) for attribute in [
                    'compute_task_def', 'provider_public_key',
                    'requestor_public_key'
                ]
            ])):
        raise Http400(
            "Invalid TaskToCompute",
            error_code=ErrorCode.MESSAGE_WRONG_FIELDS,
        )

    validate_int_value(task_to_compute.compute_task_def['deadline'])

    validate_id_value(task_to_compute.compute_task_def['task_id'], 'task_id')
    validate_id_value(task_to_compute.compute_task_def['subtask_id'],
                      'subtask_id')

    validate_hex_public_key(task_to_compute.provider_public_key,
                            'provider_public_key')
    validate_hex_public_key(task_to_compute.requestor_public_key,
                            'requestor_public_key')
    validate_secure_hash_algorithm(task_to_compute.package_hash)
    validate_subtask_price_task_to_compute(task_to_compute)
예제 #4
0
def hex_to_bytes_convert(client_public_key: str):
    if not isinstance(client_public_key, str):
        raise Http400("Client public key must be string",
                      error_code=ErrorCode.MESSAGE_VALUE_NOT_STRING)
    if not len(client_public_key) == GOLEM_PUBLIC_KEY_HEX_LENGTH:
        raise Http400("Client public key must be length of 128 characters",
                      error_code=ErrorCode.MESSAGE_VALUE_WRONG_LENGTH)
    key_bytes = decode_hex(client_public_key)
    assert len(key_bytes) == GOLEM_PUBLIC_KEY_LENGTH
    return key_bytes
예제 #5
0
def validate_subtask_price_task_to_compute(
        task_to_compute: message.tasks.TaskToCompute):
    if not isinstance(task_to_compute.price, int):
        raise Http400(
            "Price must be a integer",
            error_code=ErrorCode.MESSAGE_VALUE_NOT_INTEGER,
        )
    if task_to_compute.price < 0:
        raise Http400(
            "Price cannot be a negative value",
            error_code=ErrorCode.MESSAGE_VALUE_NEGATIVE,
        )
예제 #6
0
def get_validated_client_public_key_from_client_message(
        golem_message: message.base.Message):
    if isinstance(golem_message, message.concents.ForcePayment):
        if (isinstance(golem_message.subtask_results_accepted_list, list)
                and len(golem_message.subtask_results_accepted_list) > 0):
            task_to_compute = golem_message.subtask_results_accepted_list[
                0].task_to_compute
        else:
            raise Http400(
                "subtask_results_accepted_list must be a list type and contains at least one message",
                error_code=ErrorCode.MESSAGE_VALUE_WRONG_LENGTH,
            )

    elif isinstance(golem_message, message.tasks.TaskMessage):
        if not golem_message.is_valid():
            raise GolemMessageValidationError(
                "Golem message invalid", error_code=ErrorCode.MESSAGE_INVALID)
        task_to_compute = golem_message.task_to_compute
    else:
        raise Http400(
            "Unknown message type",
            error_code=ErrorCode.MESSAGE_UNKNOWN,
        )

    if task_to_compute is not None:
        if isinstance(golem_message, (
                message.ForceReportComputedTask,
                message.concents.ForceSubtaskResults,
                message.concents.ForcePayment,
                message.concents.SubtaskResultsVerify,
        )):
            client_public_key = task_to_compute.provider_public_key
            validate_hex_public_key(client_public_key, 'provider_public_key')
        elif isinstance(golem_message, (
                message.AckReportComputedTask,
                message.RejectReportComputedTask,
                message.concents.ForceGetTaskResult,
                message.concents.ForceSubtaskResultsResponse,
        )):
            client_public_key = task_to_compute.requestor_public_key
            validate_hex_public_key(client_public_key, 'requestor_public_key')
        else:
            raise Http400(
                "Unknown message type",
                error_code=ErrorCode.MESSAGE_UNKNOWN,
            )

        return hex_to_bytes_convert(client_public_key)

    return None
예제 #7
0
def validate_all_messages_identical(
        golem_messages_list: List[message.Message]):
    assert isinstance(golem_messages_list, list)
    assert len(golem_messages_list) >= 1
    assert all(
        isinstance(golem_message, message.Message)
        for golem_message in golem_messages_list)
    assert len(
        set(type(golem_message) for golem_message in golem_messages_list)) == 1

    base_golem_message = golem_messages_list[0]

    for i, golem_message in enumerate(golem_messages_list[1:], start=1):
        for slot in base_golem_message.__slots__:
            if getattr(base_golem_message, slot) != getattr(
                    golem_message, slot):
                raise Http400(
                    '{} messages are not identical. '
                    'There is a difference between messages with index 0 on passed list and with index {}'
                    'The difference is on field {}: {} is not equal {}'.format(
                        type(base_golem_message).__name__,
                        i,
                        slot,
                        getattr(base_golem_message, slot),
                        getattr(golem_message, slot),
                    ),
                    error_code=ErrorCode.MESSAGES_NOT_IDENTICAL,
                )
예제 #8
0
def validate_key_with_desired_parameters(key_name: str, key_value: Union[bytes,
                                                                         str],
                                         expected_type, expected_length: int):

    if not isinstance(key_value, expected_type):
        raise Http400(
            "{} must be {}.".format(key_name, str(expected_type)),
            error_code=ErrorCode.MESSAGE_VALUE_WRONG_TYPE,
        )

    if len(key_value) != expected_length:
        raise Http400(
            "The length of {} must be exactly {} characters.".format(
                key_name, expected_length),
            error_code=ErrorCode.MESSAGE_VALUE_WRONG_LENGTH,
        )
예제 #9
0
def validate_report_computed_task_time_window(report_computed_task):
    assert isinstance(report_computed_task, message.ReportComputedTask)

    if report_computed_task.timestamp < report_computed_task.task_to_compute.timestamp:
        raise Http400(
            "ReportComputedTask timestamp is older then nested TaskToCompute.",
            error_code=ErrorCode.MESSAGE_TIMESTAMP_TOO_OLD,
        )
예제 #10
0
async def change_user_password(
    old_password: str,
    current_password: str,
    user: User = Depends(get_current_active_user)) -> User:
    if not verify_password(old_password, user.password):
        return Http400("Incorrect password")
    user.password = current_password
    user.save()
    return user
예제 #11
0
def validate_int_value(value):
    """
    Checks if value is an integer. If not, tries to cast it to an integer.
    Then checks if value is non-negative.

    """
    if not isinstance(value, int):
        try:
            value = int(value)
        except (ValueError, TypeError):
            raise Http400(
                "Wrong type, expected a value that can be converted to an integer.",
                error_code=ErrorCode.MESSAGE_VALUE_NOT_INTEGER,
            )
    if value < 0:
        raise Http400(
            "Wrong type, expected non-negative integer but negative integer provided.",
            error_code=ErrorCode.MESSAGE_VALUE_WRONG_TYPE,
        )
예제 #12
0
def validate_golem_message_client_authorization(
        golem_message: message.concents.ClientAuthorization):
    if not isinstance(golem_message, message.concents.ClientAuthorization):
        raise Http400(
            'Expected ClientAuthorization.',
            error_code=ErrorCode.AUTH_CLIENT_AUTH_MESSAGE_MISSING,
        )

    validate_bytes_public_key(golem_message.client_public_key,
                              'client_public_key')
예제 #13
0
def validate_golem_message_subtask_results_rejected(
        subtask_results_rejected: message.tasks.SubtaskResultsRejected):
    if not isinstance(subtask_results_rejected,
                      message.tasks.SubtaskResultsRejected):
        raise Http400(
            "subtask_results_rejected should be of type:  SubtaskResultsRejected",
            error_code=ErrorCode.MESSAGE_INVALID,
        )
    validate_task_to_compute(
        subtask_results_rejected.report_computed_task.task_to_compute)
예제 #14
0
def validate_that_golem_messages_are_signed_with_key(
    public_key: bytes,
    *golem_messages: message.base.Message,
) -> None:
    for golem_message in golem_messages:
        if not is_golem_message_signed_with_key(public_key, golem_message):
            raise Http400(
                f'There was an exception when validating if golem_message {golem_message.__class__.__name__} is signed with '
                f'public key {public_key}.',
                error_code=ErrorCode.MESSAGE_SIGNATURE_WRONG,
            )
예제 #15
0
def deserialize_message(raw_message_data: bytes) -> message.Message:
    try:
        golem_message = message.Message.deserialize(raw_message_data,
                                                    None,
                                                    check_time=False)
        assert golem_message is not None
        return golem_message
    except MessageError as exception:
        raise Http400(
            "Unable to deserialize Golem Message: {}.".format(exception),
            error_code=ErrorCode.MESSAGE_UNABLE_TO_DESERIALIZE,
        )
예제 #16
0
def validate_golem_message_signed_with_key(
    golem_message: message.base.Message,
    public_key: bytes,
):
    assert isinstance(golem_message, message.base.Message)

    validate_bytes_public_key(public_key, 'public_key')

    try:
        golem_message.verify_signature(public_key)
    except MessageError as exception:
        error_message = join_messages(
            'There was an exception when validating if golem_message {} is signed with public key {}.'
            .format(
                golem_message.TYPE,
                public_key,
            ), str(exception))
        raise Http400(
            error_message,
            error_code=ErrorCode.MESSAGE_SIGNATURE_WRONG,
        )
예제 #17
0
async def get_super_user(current_user: User = Depends(
    get_current_user)) -> User:
    if current_user.is_superuser:
        return current_user
    return Http400("You are not super user")
예제 #18
0
async def get_admin_user(current_user: User = Depends(
    get_current_user)) -> User:
    if current_user.is_admin:
        return current_user
    return Http400("You are not administrator")
예제 #19
0
async def get_current_active_user(current_user: User = Depends(
    get_current_user)) -> User:
    if current_user.is_active:
        return current_user
    return Http400("Inactive user")
예제 #20
0
def gatekeeper_access_denied_response_400_mock(_message,
                                               _path=None,
                                               _subtask_id=None,
                                               _client_key=None):
    Client.objects.get_or_create_full_clean(CONCENT_PUBLIC_KEY)
    raise Http400('', error_code=ErrorCode.MESSAGE_UNEXPECTED)
예제 #21
0
 def dummy_view_handle_http_400_exception(_request, _message,
                                          _client_public_key):
     raise Http400('dummy', error_code=ErrorCode.MESSAGE_UNEXPECTED)
예제 #22
0
def _mock_raise_http400(_):
    raise Http400(
        'dummy http400',
        error_code=ErrorCode.MESSAGE_UNEXPECTED,
    )
예제 #23
0
def _create_client_and_raise_http400_error_mock(*_args, **_kwargs):
    _create_client_mock_and_return_none()
    raise Http400('', error_code=ErrorCode.MESSAGE_UNEXPECTED)
예제 #24
0
 async def change_password(old_password: str, password: str, user: User):
     if not verify_password(old_password, user.password):
         return Http400("Incorrect password")
     user.password = password
     await user.save()
     return model.from_orm(user)
예제 #25
0
def _log_changes_in_subtask_states_400_mock(_logger, _message,
                                            _client_public_key):
    Client.objects.get_or_create_full_clean(CONCENT_PUBLIC_KEY)
    raise Http400('', error_code=ErrorCode.MESSAGE_UNEXPECTED)