Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 22 additions & 30 deletions server/app/interfaces/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,18 @@ def xml(cls, data: bytes, expect_type: Type[T], stripped: bool) -> T:
raise BadRequest(str(e)) from e
return cls.assert_type(rv, expect_type)

@classmethod
def _check_request_body_content_type(cls, request: Request):
"""
Raise and exception if the request body content type is different from expected.
"""
valid_content_types = ("application/json", "application/xml", "text/xml")

if request.mimetype not in valid_content_types:
raise werkzeug.exceptions.UnsupportedMediaType(
f"Invalid content-type: {request.mimetype}! Supported types: " + ", ".join(valid_content_types)
)

@classmethod
def request_body(cls, request: Request, expect_type: Type[T], stripped: bool) -> T:
"""
Expand All @@ -588,12 +600,7 @@ def request_body(cls, request: Request, expect_type: Type[T], stripped: bool) ->
In the meeting (25.11.2020) we discussed, this may refer to a reverse proxy in front of this WSGI app,
which should limit the maximum content length.
"""
valid_content_types = ("application/json", "application/xml", "text/xml")

if request.mimetype not in valid_content_types:
raise werkzeug.exceptions.UnsupportedMediaType(
f"Invalid content-type: {request.mimetype}! Supported types: " + ", ".join(valid_content_types)
)
cls._check_request_body_content_type(request)

if request.mimetype == "application/json":
return cls.json(request.get_data(), expect_type, stripped)
Expand All @@ -605,37 +612,22 @@ def request_body_list(cls, request: Request, expect_type: Type[T], stripped: boo
Deserializes the request body to an instance (or list of instances)
of the expected type.
"""
# TODO: Refactor this method and request_body to avoid code duplication
valid_content_types = ("application/json", "application/xml", "text/xml")

if request.mimetype not in valid_content_types:
raise werkzeug.exceptions.UnsupportedMediaType(
f"Invalid content-type: {request.mimetype}! Supported types: " + ", ".join(valid_content_types)
)
cls._check_request_body_content_type(request)

if request.mimetype == "application/json":
raw_data = request.get_data()
try:
parsed = json.loads(raw_data)
except Exception as e:
raise werkzeug.exceptions.BadRequest(f"Invalid JSON: {e}")
# Prüfe, ob parsed ein Array ist:
if isinstance(parsed, list):
# Für jedes Element wird die Konvertierung angewandt.
return [cls._convert_single_json_item(item, expect_type, stripped) for item in parsed] # type: ignore
else:
return [cls._convert_single_json_item(parsed, expect_type, stripped)]
else:
return [cls.xml(request.get_data(), expect_type, stripped)]

@classmethod
def _convert_single_json_item(cls, data: Any, expect_type: Type[T], stripped: bool) -> T:
"""
Converts a single JSON-Object (as a Python-Dict) to an object of type expect_type.
Here the dictionary is first serialized back to a JSON-string and returned as bytes.
"""
json_bytes = json.dumps(data).encode("utf-8")
return cls.json(json_bytes, expect_type, stripped)
# Check if parsed is a list. Accordingly, expect_single is
# - True if parsed is *not* a list
# - False if parsed is a list
expect_single = not isinstance(parsed, list)
res = cls.json_list(raw_data, expect_type, stripped, expect_single)
return res

return [cls.xml(request.get_data(), expect_type, stripped)]


def is_stripped_request(request: Request) -> bool:
Expand Down
16 changes: 0 additions & 16 deletions server/app/interfaces/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,22 +378,6 @@ def __init__(
strict_slashes=False,
)

# TODO: the parameters can be typed via builtin wsgiref with Python 3.11+
def __call__(self, environ, start_response) -> Iterable[bytes]:
response: Response = self.handle_request(Request(environ))
return response(environ, start_response)

def _get_obj_ts(self, identifier: model.Identifier, type_: Type[T]) -> T:
identifiable = self.object_store.get(identifier)
if not isinstance(identifiable, type_):
raise NotFound(f"No {type_.__name__} with {identifier} found!")
return identifiable

def _get_all_obj_of_type(self, type_: Type[T]) -> Iterator[T]:
for obj in self.object_store:
if isinstance(obj, type_):
yield obj

def _resolve_reference(self, reference: model.ModelReference[model.base._RT]) -> model.base._RT:
try:
return reference.resolve(self.object_store)
Expand Down
18 changes: 17 additions & 1 deletion server/test/interfaces/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
from basyx.aas import model
from basyx.aas.adapter._generic import XML_NS_MAP
from lxml import etree
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import BadRequest, UnsupportedMediaType
from werkzeug.test import EnvironBuilder


class TestPagination(unittest.TestCase):
Expand Down Expand Up @@ -316,3 +317,18 @@ def test_paginated_list(self):
for ref in result:
self.assertEqual({"keys", "type"}, ref.keys())
self.assertGreater(len(ref["keys"]), 0)

class TestHTTPApiDecoder(unittest.TestCase):
def test__check_request_body_content_type(self):
builder = EnvironBuilder(content_type="text/html")
with self.assertRaises(UnsupportedMediaType):
base.HTTPApiDecoder._check_request_body_content_type(builder.get_request())

builder = EnvironBuilder(content_type="application/json")
base.HTTPApiDecoder._check_request_body_content_type(builder.get_request())

builder = EnvironBuilder(content_type="application/xml")
base.HTTPApiDecoder._check_request_body_content_type(builder.get_request())

builder = EnvironBuilder(content_type="text/xml")
base.HTTPApiDecoder._check_request_body_content_type(builder.get_request())