From e220a060f5a9e971e896dde93182a8d43004f938 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Goc=C5=82awski?= Date: Fri, 7 Feb 2025 13:27:18 +0100 Subject: [PATCH 1/2] Fix setting Content-Type header. Before that there were 2 headers set, one default one "text/html". Co-Authored-By: Claude Haiku 5.5 --- CHANGELOG.md | 4 +++- flask_jsonapi/response.py | 4 ++-- tests/test_response.py | 6 ++++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 722c794..bdd57c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,9 @@ ## 1.4.2 (unreleased) --------------------- -- Nothing changed yet. +- Fix duplicated Content-Type header in JSON:API responses. +- `BaseJsonApiResponse.base_header` was replaced by `content_type`. A Content-Type header supplied by the + caller is now overridden by the JSON:API one. ## 1.4.1 (2026-02-02) diff --git a/flask_jsonapi/response.py b/flask_jsonapi/response.py index 4173a69..c3b2922 100644 --- a/flask_jsonapi/response.py +++ b/flask_jsonapi/response.py @@ -30,11 +30,11 @@ def get_content(self): class BaseJsonApiResponse(BaseResponse): - base_header = {'Content-Type': 'application/vnd.api+json'} + content_type = 'application/vnd.api+json' def make_response(self): response = super().make_response() - response.headers.extend(self.base_header) + response.headers['Content-Type'] = self.content_type return response def get_content(self): diff --git a/tests/test_response.py b/tests/test_response.py index 3e5315a..3186461 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -30,3 +30,9 @@ def test_jsonapi_error_response(app): } ] } + + +def test_jsonapi_response_has_single_content_type_header(app): + with app.test_request_context('/'): + flask_response = response.JsonApiResponse({'data': None}).make_response() + assert flask_response.headers.getlist('Content-Type') == ['application/vnd.api+json'] From 096ebe6d66d74c6407284413fc2e4da2687c221c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Goc=C5=82awski?= Date: Sat, 17 Oct 2026 22:59:05 +0200 Subject: [PATCH 2/2] Return 409 when PATCH body id does not match the URL. Views that pass the loaded body straight to repository.update(data) used the body's id, so the update could hit a different object than the one the permission check loaded from the URL. marshmallow-jsonapi lets an "id" attribute overwrite data.id, so the id is checked both in the raw body and in the loaded payload. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 3 ++ flask_jsonapi/exceptions.py | 5 +++ flask_jsonapi/resources.py | 22 ++++++++++ tests/test_resources.py | 88 +++++++++++++++++++++++++++++++++++++ 4 files changed, 118 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bdd57c8..8b92f97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ - Fix duplicated Content-Type header in JSON:API responses. - `BaseJsonApiResponse.base_header` was replaced by `content_type`. A Content-Type header supplied by the caller is now overridden by the JSON:API one. +- Return 409 Conflict when a PATCH body id does not match the URL. This also applies to a body id that + differs from the URL id only in letter case (for example an uppercase UUID): legacy repository views + used to overwrite the body id with the URL id and succeed, so clients sending such ids now get 409. ## 1.4.1 (2026-02-02) diff --git a/flask_jsonapi/exceptions.py b/flask_jsonapi/exceptions.py index 20a0016..dddf84e 100644 --- a/flask_jsonapi/exceptions.py +++ b/flask_jsonapi/exceptions.py @@ -126,6 +126,11 @@ def __init__(self, detail, **kwargs): ) +class Conflict(JsonApiException): + title = 'Conflict' + status = 409 + + class ForbiddenError(JsonApiException): title = 'Operation forbidden.' status = 403 diff --git a/flask_jsonapi/resources.py b/flask_jsonapi/resources.py index 06531af..0483839 100644 --- a/flask_jsonapi/resources.py +++ b/flask_jsonapi/resources.py @@ -84,18 +84,40 @@ def delete(self, *args, **kwargs): return response.EmptyResponse() def patch(self, *args, **kwargs): + self._check_body_id() computed_schema = self.schema(partial=True) try: data = computed_schema.load(request.get_json()) except marshmallow.ValidationError as e: return response.JsonApiErrorResponse.from_marshmallow_errors(e.messages) else: + self._check_loaded_id(data) resource = self.update(self.resource_id, data) if resource: return response.JsonApiResponse(computed_schema.dump(resource)) else: return response.EmptyResponse() + def _check_body_id(self): + body = request.get_json(silent=True) + if not isinstance(body, dict) or not isinstance(body.get('data'), dict): + return + body_id = body['data'].get('id') + if body_id is not None and str(body_id) != str(self.resource_id): + raise self._id_conflict() + + def _check_loaded_id(self, data): + # marshmallow-jsonapi lets an "id" attribute overwrite data.id in the loaded payload. + if 'id' in data and str(data['id']) != str(self.resource_id): + raise self._id_conflict() + + @staticmethod + def _id_conflict(): + return exceptions.Conflict( + source={'pointer': '/data/id'}, + detail='Resource id in the request body does not match the URL.', + ) + @property def resource_id(self): return self.kwargs[self.id_kwarg] diff --git a/tests/test_resources.py b/tests/test_resources.py index 0b3f583..58273d3 100644 --- a/tests/test_resources.py +++ b/tests/test_resources.py @@ -628,3 +628,91 @@ def test_delete_is_not_allowed(self, api, jsonapi_client): assert len(result['errors']) == 1 error = result['errors'][0] assert error['detail'] == 'Delete is not allowed for this resource' + + +class TestPatchIdCheck: + url = '/examples/f60717a3-7dc2-4f1a-bdf4-f2804c3127a4/' + + def make_view(self, api, update): + class ExampleDetailView(resources.ResourceDetail): + schema = ExampleSchema + + def update(self, id, data): + return update(id, data) + + api.route(ExampleDetailView, 'example_detail', '/examples//') + + def test_mismatched_id_is_rejected_before_update(self, api, jsonapi_client): + update = mock.Mock() + self.make_view(api, update) + + response = jsonapi_client.patch(self.url, json={'data': { + 'type': 'example', 'id': 'f60717a3-7dc2-4f1a-bdf4-f2804c3127a5', 'attributes': {'body': 'x'}}}) + + assert response.status_code == 409 + assert response.get_json(force=True)['errors'] == [{ + 'status': 409, + 'title': 'Conflict', + 'detail': 'Resource id in the request body does not match the URL.', + 'source': {'pointer': '/data/id'}, + }] + assert not update.called + + def test_missing_body_id_is_accepted(self, api, jsonapi_client): + update = mock.Mock(return_value=None) + self.make_view(api, update) + + response = jsonapi_client.patch(self.url, json={'data': {'type': 'example', 'attributes': {'body': 'x'}}}) + + assert response.status_code == 204 + assert update.called + + def test_mismatched_attributes_id_without_body_id_is_rejected(self, api, jsonapi_client): + update = mock.Mock() + self.make_view(api, update) + + response = jsonapi_client.patch(self.url, json={'data': { + 'type': 'example', 'attributes': {'id': 'f60717a3-7dc2-4f1a-bdf4-f2804c3127a5', 'body': 'x'}}}) + + assert response.status_code == 409 + assert not update.called + + def test_mismatched_attributes_id_with_matching_body_id_is_rejected(self, api, jsonapi_client): + update = mock.Mock() + self.make_view(api, update) + + response = jsonapi_client.patch(self.url, json={'data': { + 'type': 'example', + 'id': 'f60717a3-7dc2-4f1a-bdf4-f2804c3127a4', + 'attributes': {'id': 'f60717a3-7dc2-4f1a-bdf4-f2804c3127a5', 'body': 'x'}}}) + + assert response.status_code == 409 + assert not update.called + + def test_numeric_body_id_matching_url_is_accepted(self, api, jsonapi_client): + class IntSchema(marshmallow_jsonapi.Schema): + id = fields.Int() + body = fields.Str() + + class Meta: + type_ = 'example' + + class ExampleDetailView(resources.ResourceDetail): + schema = IntSchema + + def update(self, id, data): + return None + + api.route(ExampleDetailView, 'example_detail', '/examples//') + + response = jsonapi_client.patch('/examples/1/', json={'data': { + 'type': 'example', 'id': 1, 'attributes': {'body': 'x'}}}) + + assert response.status_code == 204 + + def test_body_without_data_member_does_not_crash(self, api, jsonapi_client): + self.make_view(api, mock.Mock()) + + response = jsonapi_client.patch(self.url, json={'nodata': True}) + + assert response.status_code == 422