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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- Honor structured HTTP Content-Type when redundant CloudEvents metadata headers
are present, using the event attributes and data from the message body.

## [2.2.0]

### Changed
Expand Down
19 changes: 18 additions & 1 deletion src/cloudevents/core/bindings/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,8 @@ def from_http(
Auto-detects CloudEvents version and uses appropriate event factory if not provided.

Automatically detects whether the message uses binary or structured content mode:
- If any ce- prefixed headers are present → binary mode
- If Content-Type matches the supplied event format → structured mode
- Otherwise, if any ce- prefixed headers are present → binary mode
- Otherwise → structured mode

This function provides a convenient way to handle both content modes without
Expand Down Expand Up @@ -300,6 +301,22 @@ def from_http(
:param event_factory: Factory function to create CloudEvent instances (auto-detected if None)
:return: CloudEvent instance
"""
# Structured messages may also carry ce- metadata headers (HTTP binding 3.2.3).
# Their Content-Type determines the mode; the body remains authoritative.
content_type = next(
(
value
for key, value in message.headers.items()
if key.lower() == CONTENT_TYPE_HEADER
),
"",
)
Comment on lines +304 to +313

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this belongs to the HTTPMessage class. please extract this as get_content_type() -> str | None.

if (
content_type.partition(";")[0].strip().lower()
== event_format.get_content_type().partition(";")[0].strip().lower()
):
Comment on lines +314 to +317

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's move .partition(";")[0].strip().lower() to a named helper.

return from_structured(message, event_format, event_factory)

if any(key.lower().startswith(CE_PREFIX) for key in message.headers.keys()):
return from_binary(message, event_format, event_factory)

Expand Down
62 changes: 55 additions & 7 deletions tests/test_core/test_bindings/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,23 +710,71 @@ def test_from_http_case_insensitive_detection() -> None:
assert event.get_type() == "com.example.test"


def test_from_http_mixed_headers() -> None:
"""Test from_http when both ce- headers and structured content are present"""
@pytest.mark.parametrize(
"content_type_header, content_type",
[
("content-type", "application/cloudevents+json"),
("Content-Type", "application/cloudevents+json; charset=UTF-8"),
("CONTENT-TYPE", "Application/CloudEvents+JSON"),
],
)
@pytest.mark.parametrize("explicit_factory", [False, True])
def test_from_http_mixed_headers(
content_type_header: str, content_type: str, explicit_factory: bool
) -> None:
"""Structured Content-Type takes precedence over redundant metadata headers."""
message = HTTPMessage(
headers={
"ce-type": "com.example.binary",
"ce-source": "/binary",
"ce-id": "123",
"ce-specversion": "1.0",
content_type_header: content_type,
},
body=b'{"type": "com.example.structured", "source": "/structured", "id": "456", "specversion": "1.0", "data": {"ok": true}}',
)
event = from_http(message, JSONFormat(), CloudEvent if explicit_factory else None)

assert event.get_type() == "com.example.structured"
assert event.get_source() == "/structured"
assert event.get_id() == "456"
assert event.get_data() == {"ok": True}


def test_from_http_structured_with_partial_metadata_headers() -> None:
"""Optional metadata headers need not contain a complete binary event."""
message = HTTPMessage(
headers={
"content-type": "application/cloudevents+json",
"ce-subject": "redundant-header",
},
body=b'{"type": "com.example.structured", "source": "/structured", "id": "456", "specversion": "1.0"}',
body=b'{"type": "com.example.test", "source": "/test", "id": "123", "specversion": "1.0"}',
)
event = from_http(message, JSONFormat(), CloudEvent)

# Binary mode should take precedence (ce- headers present)
assert event.get_type() == "com.example.binary"
assert event.get_source() == "/binary"
event = from_http_event(message)

assert event.get_id() == "123"
assert "subject" not in event.get_attributes()


def test_from_http_structured_with_custom_format() -> None:
"""Mode detection uses the supplied format's media type."""

class CustomJSONFormat(JSONFormat):
def get_content_type(self) -> str:
return "application/cloudevents+custom"

original = create_event(data={"ok": True})
structured = to_structured(original, CustomJSONFormat())
message = HTTPMessage(
headers={**structured.headers, "ce-subject": "redundant-header"},
body=structured.body,
)

event = from_http(message, CustomJSONFormat())

assert event.get_id() == original.get_id()
assert event.get_data() == {"ok": True}


def test_percent_encoding_special_chars() -> None:
Expand Down
Loading