diff --git a/backend/src/baserow/api/decorators.py b/backend/src/baserow/api/decorators.py index 6ae117f45d..4a299ca62f 100644 --- a/backend/src/baserow/api/decorators.py +++ b/backend/src/baserow/api/decorators.py @@ -5,7 +5,7 @@ from pytz.exceptions import UnknownTimeZoneError from django.utils import timezone -from rest_framework import status +from rest_framework import status, serializers from rest_framework.exceptions import APIException from .utils import ( @@ -14,7 +14,10 @@ from .utils import ( validate_data, validate_data_custom_fields, ) -from .exceptions import RequestBodyValidationException +from .exceptions import ( + QueryParameterValidationException, + RequestBodyValidationException, +) def map_exceptions(exceptions): @@ -57,6 +60,68 @@ def map_exceptions(exceptions): return map_exceptions_decorator +def validate_query_parameters(serializer: serializers.Serializer): + """ + This decorator can validate the query parameters using a serializer. If the query + parameters match the fields on the serializer it will add the query params to the + kwargs. If not it will raise an APIException with structured details about what is + wrong. + + The name of the field on the serializer must be the name of the expected query + parameter in the query string. + By passing "required=False" to the serializer field, we allow the query + parameter to be unset. + + Example: + class MoveRowQueryParamsSerializer(serializers.Serializer): + before_id = serializers.IntegerField(required=False) + + @validate_query_parameters(MoveRowQueryParamsSerializer) + def patch(self, request, query_params): + raise SomeException('This is a test') + + HTTP/1.1 400 + URL: /api/database/rows/table/11/1/move/?before_id=wrong_type + { + "error": "ERROR_QUERY_PARAMETER_VALIDATION", + "detail": { + "before_id": [ + { + "error": "A valid integer is required.", + "code": "invalid" + } + ] + } + } + + :raises ValueError: When the `query_params` attribute is already in the kwargs. This + decorator tries to add the `query_params` attribute, but cannot do that if it is + already present. + """ + + def validate_decorator(func): + def func_wrapper(*args, **kwargs): + request = get_request(args) + + if "query_params" in kwargs: + raise ValueError("The query_params attribute is already in the kwargs.") + + params_dict = request.GET.dict() + + kwargs["query_params"] = validate_data( + serializer, + params_dict, + partial=False, + exception_to_raise=QueryParameterValidationException, + ) + + return func(*args, **kwargs) + + return func_wrapper + + return validate_decorator + + def validate_body(serializer_class, partial=False): """ This decorator can validate the request body using a serializer. If the body is diff --git a/backend/src/baserow/api/exceptions.py b/backend/src/baserow/api/exceptions.py index 69be62834e..164dd90b75 100644 --- a/backend/src/baserow/api/exceptions.py +++ b/backend/src/baserow/api/exceptions.py @@ -13,3 +13,11 @@ class UnknownFieldProvided(Exception): """ Raised when an unknown field is provided to an API endpoint. """ + + +class QueryParameterValidationException(APIException): + def __init__(self, detail=None, code=None): + super().__init__( + {"error": "ERROR_QUERY_PARAMETER_VALIDATION", "detail": detail}, code=code + ) + self.status_code = 400 diff --git a/backend/src/baserow/api/utils.py b/backend/src/baserow/api/utils.py index 4b2645e94d..e0d6a7e57e 100644 --- a/backend/src/baserow/api/utils.py +++ b/backend/src/baserow/api/utils.py @@ -59,7 +59,12 @@ def map_exceptions(mapping): raise exc -def validate_data(serializer_class, data, partial=False): +def validate_data( + serializer_class, + data, + partial=False, + exception_to_raise=RequestBodyValidationException, +): """ Validates the provided data via the provided serializer class. If the data doesn't match with the schema of the serializer an api exception containing more detailed @@ -88,7 +93,7 @@ def validate_data(serializer_class, data, partial=False): serializer = serializer_class(data=data, partial=partial) if not serializer.is_valid(): detail = serialize_errors_recursive(serializer.errors) - raise RequestBodyValidationException(detail) + raise exception_to_raise(detail) return serializer.data diff --git a/backend/src/baserow/contrib/database/api/rows/serializers.py b/backend/src/baserow/contrib/database/api/rows/serializers.py index 922c4c5e2d..d410fe8751 100644 --- a/backend/src/baserow/contrib/database/api/rows/serializers.py +++ b/backend/src/baserow/contrib/database/api/rows/serializers.py @@ -217,3 +217,11 @@ def get_example_row_metadata_field_serializer(): example_pagination_row_serializer_class = get_example_pagination_serializer_class( get_example_row_serializer_class(True, user_field_names=True) ) + + +class MoveRowQueryParamsSerializer(serializers.Serializer): + before_id = serializers.IntegerField(required=False) + + +class CreateRowQueryParamsSerializer(serializers.Serializer): + before = serializers.IntegerField(required=False) diff --git a/backend/src/baserow/contrib/database/api/rows/views.py b/backend/src/baserow/contrib/database/api/rows/views.py index 210d91a56c..ec1260a4ed 100644 --- a/backend/src/baserow/contrib/database/api/rows/views.py +++ b/backend/src/baserow/contrib/database/api/rows/views.py @@ -7,7 +7,7 @@ from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView -from baserow.api.decorators import map_exceptions +from baserow.api.decorators import map_exceptions, validate_query_parameters from baserow.api.errors import ERROR_USER_NOT_IN_GROUP from baserow.api.exceptions import RequestBodyValidationException from baserow.api.pagination import PageNumberPagination @@ -49,6 +49,8 @@ from baserow.contrib.database.views.registries import view_filter_type_registry from baserow.core.exceptions import UserNotInGroup from baserow.core.user_files.exceptions import UserFileDoesNotExist from .serializers import ( + MoveRowQueryParamsSerializer, + CreateRowQueryParamsSerializer, RowSerializer, get_example_row_serializer_class, get_row_serializer_class, @@ -345,7 +347,8 @@ class RowsView(APIView): RowDoesNotExist: ERROR_ROW_DOES_NOT_EXIST, } ) - def post(self, request, table_id): + @validate_query_parameters(CreateRowQueryParamsSerializer) + def post(self, request, table_id, query_params): """ Creates a new row for the given table_id. Also the post data is validated according to the tables field types. @@ -361,7 +364,7 @@ class RowsView(APIView): ) data = validate_data(validation_serializer, request.data) - before_id = request.GET.get("before") + before_id = query_params.get("before") before = ( RowHandler().get_row(request.user, table, before_id, model) if before_id @@ -691,7 +694,8 @@ class RowMoveView(APIView): NoPermissionToTable: ERROR_NO_PERMISSION_TO_TABLE, } ) - def patch(self, request, table_id, row_id): + @validate_query_parameters(MoveRowQueryParamsSerializer) + def patch(self, request, table_id, row_id, query_params): """Moves the row to another position.""" table = TableHandler().get_table(table_id) @@ -700,7 +704,7 @@ class RowMoveView(APIView): user_field_names = "user_field_names" in request.GET model = table.get_model() - before_id = request.GET.get("before_id") + before_id = query_params.get("before_id") before = ( RowHandler().get_row(request.user, table, before_id, model) if before_id diff --git a/backend/tests/baserow/api/test_api_decorators.py b/backend/tests/baserow/api/test_api_decorators.py index 6c47ee0867..4c31fc06de 100644 --- a/backend/tests/baserow/api/test_api_decorators.py +++ b/backend/tests/baserow/api/test_api_decorators.py @@ -15,10 +15,15 @@ from rest_framework.test import APIRequestFactory from baserow.api.decorators import ( map_exceptions, validate_body, + validate_query_parameters, validate_body_custom_fields, allowed_includes, accept_timezone, ) +from baserow.api.exceptions import ( + QueryParameterValidationException, + RequestBodyValidationException, +) from baserow.core.models import Group from baserow.core.registry import ( Instance, @@ -37,6 +42,10 @@ class TemporarySerializer(serializers.Serializer): field_2 = serializers.ChoiceField(choices=("choice_1", "choice_2")) +class TemporaryQueryParamSerializer(serializers.Serializer): + field_3 = serializers.IntegerField(required=True) + + class TemporaryBaseModelSerializer(serializers.ModelSerializer): class Meta: fields = ("name",) @@ -158,6 +167,161 @@ def test_validate_body(): validate_body(TemporarySerializer)(func)(*[object, request]) +def test_validate_query_parameter(): + factory = APIRequestFactory() + + request = Request( + factory.post( + "/some-page/?field_3=wrong_type", + content_type="application/json", + ), + parsers=[JSONParser()], + ) + func = MagicMock() + + with pytest.raises(QueryParameterValidationException) as api_exception_1: + validate_query_parameters(TemporaryQueryParamSerializer)(func)( + *[object, request] + ) + + assert api_exception_1.value.detail["error"] == "ERROR_QUERY_PARAMETER_VALIDATION" + assert api_exception_1.value.detail["detail"]["field_3"][0]["error"] == ( + "A valid integer is required." + ) + assert api_exception_1.value.detail["detail"]["field_3"][0]["code"] == "invalid" + assert api_exception_1.value.status_code == status.HTTP_400_BAD_REQUEST + + request = Request( + factory.post( + "/some-page/", + content_type="application/json", + ), + parsers=[JSONParser()], + ) + func = MagicMock() + + with pytest.raises(QueryParameterValidationException) as api_exception_2: + validate_query_parameters(TemporaryQueryParamSerializer)(func)( + *[object, request] + ) + + assert api_exception_2.value.detail["error"] == "ERROR_QUERY_PARAMETER_VALIDATION" + assert api_exception_2.value.detail["detail"]["field_3"][0]["error"] == ( + "This field is required." + ) + assert api_exception_2.value.detail["detail"]["field_3"][0]["code"] == ("required") + assert api_exception_2.value.status_code == status.HTTP_400_BAD_REQUEST + + request = Request( + factory.post( + "/some-page/?field_3=5", + content_type="application/json", + ), + parsers=[JSONParser()], + ) + func = MagicMock() + + validate_query_parameters(TemporaryQueryParamSerializer)(func)(*[object, request]) + + request = Request( + factory.post( + "/some-page/?field_3=-6", + content_type="application/json", + ), + parsers=[JSONParser()], + ) + func = MagicMock() + + validate_query_parameters(TemporaryQueryParamSerializer)(func)(*[object, request]) + + # Make sure that having additional query parameters in the query string will not + # have any effect on validating the parameters + request = Request( + factory.post( + "/some-page/?field_3=-6&field_6=5", + content_type="application/json", + ), + parsers=[JSONParser()], + ) + func = MagicMock() + + validate_query_parameters(TemporaryQueryParamSerializer)(func)(*[object, request]) + + +def test_validate_body_and_query_parameters(): + factory = APIRequestFactory() + + request = Request( + factory.post( + "/some-page/?field_3=wrong_type", + data=json.dumps({"field_1": "test", "field_2": "choice_1"}), + content_type="application/json", + ), + parsers=[JSONParser()], + ) + func = MagicMock() + + with pytest.raises(QueryParameterValidationException) as api_exception_1: + validate_body(TemporarySerializer)(func)(*[object, request]) + validate_query_parameters(TemporaryQueryParamSerializer)(func)( + *[object, request] + ) + assert api_exception_1.value.detail["error"] == "ERROR_QUERY_PARAMETER_VALIDATION" + + request = Request( + factory.post( + "/some-page/?field_3=5", + data=json.dumps({"field_1": "test"}), + content_type="application/json", + ), + parsers=[JSONParser()], + ) + func = MagicMock() + + with pytest.raises(RequestBodyValidationException) as api_exception_2: + validate_body(TemporarySerializer)(func)(*[object, request]) + validate_query_parameters(TemporaryQueryParamSerializer)(func)( + *[object, request] + ) + assert api_exception_2.value.detail["error"] == "ERROR_REQUEST_BODY_VALIDATION" + + # When both the request body and the query parameters are incorrect + # which Exception gets raised depends on the order of the decorators. + request = Request( + factory.post( + "/some-page/?field_3=wrong_type", + data=json.dumps({"field_1": "test"}), + content_type="application/json", + ), + parsers=[JSONParser()], + ) + func = MagicMock() + + with pytest.raises(RequestBodyValidationException) as api_exception_3: + validate_body(TemporarySerializer)(func)(*[object, request]) + validate_query_parameters(TemporaryQueryParamSerializer)(func)( + *[object, request] + ) + assert api_exception_3.value.detail["error"] == "ERROR_REQUEST_BODY_VALIDATION" + + request = Request( + factory.post( + "/some-page/?field_3=wrong_type", + data=json.dumps({"field_1": "test"}), + content_type="application/json", + ), + parsers=[JSONParser()], + ) + func = MagicMock() + + with pytest.raises(QueryParameterValidationException) as api_exception_4: + validate_query_parameters(TemporaryQueryParamSerializer)(func)( + *[object, request] + ) + validate_body(TemporarySerializer)(func)(*[object, request]) + assert api_exception_4.value.detail["error"] == "ERROR_QUERY_PARAMETER_VALIDATION" + + def test_validate_body_custom_fields(): factory = APIRequestFactory() registry = TemporaryTypeRegistry() diff --git a/backend/tests/baserow/api/test_api_utils.py b/backend/tests/baserow/api/test_api_utils.py index fa962ad783..d989cb7e38 100644 --- a/backend/tests/baserow/api/test_api_utils.py +++ b/backend/tests/baserow/api/test_api_utils.py @@ -4,6 +4,7 @@ from rest_framework import status, serializers from rest_framework.exceptions import APIException from rest_framework.serializers import CharField from rest_framework.status import HTTP_404_NOT_FOUND +from baserow.api.exceptions import QueryParameterValidationException from baserow.core.models import Group from baserow.core.registry import ( @@ -64,6 +65,11 @@ class TemporaryTypeRegistry(Registry): name = "temporary" +class TemporaryQueryParamSerializer(serializers.Serializer): + field_5 = serializers.IntegerField(required=True) + field_6 = serializers.CharField(max_length=20, required=False) + + def test_map_exceptions(): with pytest.raises(APIException) as api_exception_1: with map_exceptions({TemporaryException: "ERROR_TEMPORARY"}): @@ -164,6 +170,62 @@ def test_validate_data(): assert api_exception_3.value.detail["detail"][0]["field_1"][0]["code"] == "required" assert api_exception_3.value.detail["detail"][0]["field_2"][0]["code"] == "required" + with pytest.raises(QueryParameterValidationException) as api_exception_4: + validate_data( + TemporaryQueryParamSerializer, + {"field_5": "wrong_type"}, + exception_to_raise=QueryParameterValidationException, + ) + assert api_exception_4.value.status_code == status.HTTP_400_BAD_REQUEST + assert api_exception_4.value.detail["error"] == "ERROR_QUERY_PARAMETER_VALIDATION" + assert api_exception_4.value.detail["detail"]["field_5"][0]["code"] == "invalid" + assert api_exception_4.value.detail["detail"]["field_5"][0]["error"] == ( + "A valid integer is required." + ) + + with pytest.raises(QueryParameterValidationException) as api_exception_5: + validate_data( + TemporaryQueryParamSerializer, + {}, + exception_to_raise=QueryParameterValidationException, + ) + assert api_exception_5.value.status_code == status.HTTP_400_BAD_REQUEST + assert api_exception_5.value.detail["error"] == "ERROR_QUERY_PARAMETER_VALIDATION" + assert api_exception_5.value.detail["detail"]["field_5"][0]["code"] == "required" + assert api_exception_5.value.detail["detail"]["field_5"][0]["error"] == ( + "This field is required." + ) + + with pytest.raises(QueryParameterValidationException) as api_exception_6: + validate_data( + TemporaryQueryParamSerializer, + {"field_5": 5, "field_6": "string_is_way_too_long"}, + exception_to_raise=QueryParameterValidationException, + ) + assert api_exception_6.value.status_code == status.HTTP_400_BAD_REQUEST + assert api_exception_6.value.detail["error"] == "ERROR_QUERY_PARAMETER_VALIDATION" + assert api_exception_6.value.detail["detail"]["field_6"][0]["code"] == "max_length" + assert api_exception_6.value.detail["detail"]["field_6"][0]["error"] == ( + "Ensure this field has no more than 20 characters." + ) + + with pytest.raises(QueryParameterValidationException) as api_exception_7: + validate_data( + TemporaryQueryParamSerializer, + {"field_5": "wrong_type", "field_6": "string_is_way_too_long"}, + exception_to_raise=QueryParameterValidationException, + ) + assert api_exception_7.value.status_code == status.HTTP_400_BAD_REQUEST + assert api_exception_7.value.detail["error"] == "ERROR_QUERY_PARAMETER_VALIDATION" + assert api_exception_7.value.detail["detail"]["field_6"][0]["code"] == "max_length" + assert api_exception_7.value.detail["detail"]["field_6"][0]["error"] == ( + "Ensure this field has no more than 20 characters." + ) + assert api_exception_7.value.detail["detail"]["field_5"][0]["code"] == "invalid" + assert api_exception_7.value.detail["detail"]["field_5"][0]["error"] == ( + "A valid integer is required." + ) + def test_validate_data_custom_fields(): registry = TemporaryTypeRegistry() diff --git a/backend/tests/baserow/contrib/database/api/rows/test_row_views.py b/backend/tests/baserow/contrib/database/api/rows/test_row_views.py index 024f0360ea..318075a84a 100644 --- a/backend/tests/baserow/contrib/database/api/rows/test_row_views.py +++ b/backend/tests/baserow/contrib/database/api/rows/test_row_views.py @@ -1118,6 +1118,23 @@ def test_move_row(api_client, data_fixture): "order": "4.00000000000000000000", } + # Make sure that we receive an error message when calling move row + # with an before_id != int + url = reverse("api:database:rows:move", kwargs={"table_id": table.id, "row_id": 1}) + response = api_client.patch( + f"{url}?before_id=wrong_type", + format="json", + HTTP_AUTHORIZATION=f"JWT {jwt_token}", + ) + assert response.status_code == HTTP_400_BAD_REQUEST + response_json = response.json() + assert response_json["error"] == "ERROR_QUERY_PARAMETER_VALIDATION" + assert response_json["detail"]["before_id"][0]["code"] == "invalid" + assert ( + response_json["detail"]["before_id"][0]["error"] + == "A valid integer is required." + ) + @pytest.mark.django_db def test_delete_row(api_client, data_fixture): diff --git a/changelog.md b/changelog.md index 5199fbc09b..adc2e73d49 100644 --- a/changelog.md +++ b/changelog.md @@ -20,6 +20,8 @@ were deleted in rapid succession. * Fix accidentally locking of too many rows in various tables during update operations. * Introduced the has file type filter. +* Fixed bug where the backend would fail hard when an invalid integer was provided as + 'before_id' when moving a row by introducing a decorator to validate query parameters. ## Released (2021-08-11)