🐛(back) validate document content in serializer
We recently extract images url in the content. For this, we assume that the document content is always in base64. We enforce this assumption by checking if it's a valide base64 in the serializer.
This commit is contained in:
@@ -8,6 +8,10 @@ and this project adheres to
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## Fixed
|
||||
|
||||
- 🐛(back) validate document content in serializer #822
|
||||
|
||||
## [3.0.0] - 2025-03-28
|
||||
|
||||
## Added
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Client serializers for the impress core app."""
|
||||
|
||||
import binascii
|
||||
import mimetypes
|
||||
from base64 import b64decode
|
||||
|
||||
from django.conf import settings
|
||||
from django.db.models import Q
|
||||
@@ -299,6 +301,18 @@ class DocumentSerializer(ListDocumentSerializer):
|
||||
|
||||
return value
|
||||
|
||||
def validate_content(self, value):
|
||||
"""Validate the content field."""
|
||||
if not value:
|
||||
return None
|
||||
|
||||
try:
|
||||
b64decode(value, validate=True)
|
||||
except binascii.Error as err:
|
||||
raise serializers.ValidationError("Invalid base64 content.") from err
|
||||
|
||||
return value
|
||||
|
||||
def save(self, **kwargs):
|
||||
"""
|
||||
Process the content field to extract attachment keys and update the document's
|
||||
|
||||
@@ -328,3 +328,22 @@ def test_api_documents_update_administrator_or_owner_of_another(via, mock_user_t
|
||||
other_document.refresh_from_db()
|
||||
other_document_values = serializers.DocumentSerializer(instance=other_document).data
|
||||
assert other_document_values == old_document_values
|
||||
|
||||
|
||||
def test_api_documents_update_invalid_content():
|
||||
"""
|
||||
Updating a document with a non base64 encoded content should raise a validation error.
|
||||
"""
|
||||
user = factories.UserFactory(with_owned_document=True)
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
document = factories.DocumentFactory(users=[[user, "owner"]])
|
||||
|
||||
response = client.put(
|
||||
f"/api/v1.0/documents/{document.id!s}/",
|
||||
{"content": "invalid content"},
|
||||
format="json",
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"content": ["Invalid base64 content."]}
|
||||
|
||||
Reference in New Issue
Block a user