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

## [Unreleased]

### Fixed

- Fixed binary content mode writing Boolean attribute values as `True`/`False` and
Binary values as Python reprs in the HTTP, Kafka and RabbitMQ bindings; they are now
written as `true`/`false` and Base64. ([#336])

## [2.2.0]

### Changed
Expand Down Expand Up @@ -368,3 +374,4 @@ CloudEvents v2 is a rewrite with ongoing development ([#271])
[#279]: https://github.com/cloudevents/sdk-python/pull/279
[#284]: https://github.com/cloudevents/sdk-python/pull/284
[#291]: https://github.com/cloudevents/sdk-python/pull/291
[#336]: https://github.com/cloudevents/sdk-python/pull/336
30 changes: 23 additions & 7 deletions src/cloudevents/core/bindings/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
to handle CloudEvent attribute encoding and decoding per the CloudEvents specification.
"""

import base64
from datetime import datetime
from typing import Any, Final
from urllib.parse import quote, unquote
Expand All @@ -35,6 +36,27 @@
DATACONTENTTYPE_ATTR: Final[str] = "datacontenttype"


def attribute_to_string(value: Any) -> str:
"""
Convert a CloudEvent attribute value to its canonical string form, as defined by
the CloudEvents type system: Boolean as ``true``/``false``, Binary as Base64,
Timestamp as RFC 3339 (with ``Z`` for UTC). Other values use ``str()``.

:param value: The attribute value to convert
:return: The canonical string form of the value
"""
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (bytes, bytearray)):
return base64.b64encode(value).decode("ascii")
if isinstance(value, datetime):
str_value = value.isoformat()
if str_value.endswith("+00:00"):
str_value = str_value[:-6] + "Z"
return str_value
return str(value)


def encode_header_value(value: Any) -> str:
"""
Encode a CloudEvent attribute value for use in a protocol header.
Expand All @@ -45,13 +67,7 @@ def encode_header_value(value: Any) -> str:
:param value: The attribute value to encode
:return: Percent-encoded string suitable for protocol headers
"""
if isinstance(value, datetime):
str_value = value.isoformat()
if str_value.endswith("+00:00"):
str_value = str_value[:-6] + "Z"
return quote(str_value, safe="")

return quote(str(value), safe="")
return quote(attribute_to_string(value), safe="")


def decode_header_value(attr_name: str, value: str) -> Any:
Expand Down
13 changes: 4 additions & 9 deletions src/cloudevents/core/bindings/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# under the License.

from dataclasses import dataclass
from datetime import datetime
from typing import Any, Final
from urllib.parse import quote, unquote

Expand All @@ -24,6 +23,7 @@
CONTENT_TYPE_HEADER,
DATACONTENTTYPE_ATTR,
TIME_ATTR,
attribute_to_string,
get_event_factory_for_version,
)
from cloudevents.core.formats.base import Format
Expand All @@ -41,18 +41,13 @@ def _encode_header_value(value: Any) -> str:
"""
Encode a CloudEvent attribute value for use in an HTTP header.

Handles datetime objects (ISO 8601 with 'Z' suffix for UTC) and applies
percent-encoding per the CloudEvents HTTP binding spec (section 3.1.3.2).
Uses the canonical string form of the value (see ``attribute_to_string``) and
applies percent-encoding per the CloudEvents HTTP binding spec (section 3.1.3.2).

:param value: The attribute value to encode
:return: Percent-encoded string suitable for HTTP headers
"""
if isinstance(value, datetime):
str_value = value.isoformat()
if str_value.endswith("+00:00"):
str_value = str_value[:-6] + "Z"
return quote(str_value, safe=_CE_SAFE_CHARS)
return quote(str(value), safe=_CE_SAFE_CHARS)
return quote(attribute_to_string(value), safe=_CE_SAFE_CHARS)


def _decode_header_value(attr_name: str, value: str) -> Any:
Expand Down
10 changes: 2 additions & 8 deletions src/cloudevents/core/bindings/kafka.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# under the License.

from dataclasses import dataclass
from datetime import datetime
from typing import Any, Callable, Final

from dateutil.parser import isoparse
Expand All @@ -23,6 +22,7 @@
CONTENT_TYPE_HEADER,
DATACONTENTTYPE_ATTR,
TIME_ATTR,
attribute_to_string,
get_event_factory_for_version,
)
from cloudevents.core.formats.base import Format
Expand Down Expand Up @@ -114,13 +114,7 @@ def to_binary(
headers[CONTENT_TYPE_HEADER] = str(attr_value).encode("utf-8")
else:
header_name = f"{CE_PREFIX}{attr_name}"
if isinstance(attr_value, datetime):
s = attr_value.isoformat()
if s.endswith("+00:00"):
s = s[:-6] + "Z"
headers[header_name] = s.encode("utf-8")
else:
headers[header_name] = str(attr_value).encode("utf-8")
headers[header_name] = attribute_to_string(attr_value).encode("utf-8")

data = event.get_data()
datacontenttype = attributes.get(DATACONTENTTYPE_ATTR)
Expand Down
10 changes: 2 additions & 8 deletions src/cloudevents/core/bindings/rabbitmq.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
"""

from dataclasses import dataclass
from datetime import datetime
from typing import Any, Final

from dateutil.parser import isoparse
Expand All @@ -29,6 +28,7 @@
from cloudevents.core.bindings.common import (
DATACONTENTTYPE_ATTR,
TIME_ATTR,
attribute_to_string,
get_event_factory_for_version,
)
from cloudevents.core.formats.base import Format
Expand Down Expand Up @@ -97,13 +97,7 @@ def to_binary(event: BaseCloudEvent, event_format: Format) -> RabbitMQMessage:
content_type = str(attr_value)
else:
header_name = f"{CE_PREFIX}{attr_name}"
if isinstance(attr_value, datetime):
s = attr_value.isoformat()
if s.endswith("+00:00"):
s = s[:-6] + "Z"
headers[header_name] = s
else:
headers[header_name] = str(attr_value)
headers[header_name] = attribute_to_string(attr_value)

data = event.get_data()
datacontenttype = attributes.get(DATACONTENTTYPE_ATTR)
Expand Down
13 changes: 13 additions & 0 deletions tests/test_core/test_bindings/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -1139,3 +1139,16 @@ def test_convenience_with_explicit_format_override() -> None:

assert recovered.get_type() == event.get_type()
assert recovered.get_data() == event.get_data()


@pytest.mark.parametrize(
"value, expected",
[(True, "true"), (False, "false"), (b"", "AQI="), (7, "7")],
)
def test_to_binary_writes_canonical_attribute_strings(
value: Any, expected: str
) -> None:
"""Boolean and Binary extension values use the CloudEvents string forms"""
message = to_binary(create_event({"ext": value}), JSONFormat())

assert message.headers["ce-ext"] == expected
13 changes: 13 additions & 0 deletions tests/test_core/test_bindings/test_kafka.py
Original file line number Diff line number Diff line change
Expand Up @@ -848,3 +848,16 @@ def test_binary_rejects_invalid_utf8_in_cloudevent_headers(header: str) -> None:
)
with pytest.raises(UnicodeDecodeError):
from_binary(message, JSONFormat())


@pytest.mark.parametrize(
"value, expected",
[(True, "true"), (False, "false"), (b"", "AQI="), (7, "7")],
)
def test_to_binary_writes_canonical_attribute_strings(
value: Any, expected: str
) -> None:
"""Boolean and Binary extension values use the CloudEvents string forms"""
message = to_binary(create_event({"ext": value}), JSONFormat())

assert message.headers["ce_ext"] == expected.encode("utf-8")
15 changes: 14 additions & 1 deletion tests/test_core/test_bindings/test_rabbitmq.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def test_to_binary_boolean_extension_converted_to_string() -> None:
event = create_event(extra_attrs={"boolext": True})
message = to_binary(event, JSONFormat())

assert message.headers["ce-boolext"] == "True"
assert message.headers["ce-boolext"] == "true"
assert isinstance(message.headers["ce-boolext"], str)


Expand Down Expand Up @@ -789,3 +789,16 @@ def test_empty_headers_structured_mode() -> None:
event = from_structured(message, JSONFormat(), CloudEvent)

assert event.get_type() == "test"


@pytest.mark.parametrize(
"value, expected",
[(True, "true"), (False, "false"), (b"", "AQI="), (7, "7")],
)
def test_to_binary_writes_canonical_attribute_strings(
value: Any, expected: str
) -> None:
"""Boolean and Binary extension values use the CloudEvents string forms"""
message = to_binary(create_event({"ext": value}), JSONFormat())

assert message.headers["ce-ext"] == expected