Skip to content
Draft
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
14 changes: 13 additions & 1 deletion src/cloudevents/core/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,20 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from typing import Literal
import re
from typing import Final, Literal

SpecVersion = Literal["1.0", "0.3"]
SPECVERSION_V1_0 = "1.0"
SPECVERSION_V0_3 = "0.3"

_ATTRIBUTE_NAME_PATTERN: Final[re.Pattern[str]] = re.compile(r"^[a-z0-9]+$")


def is_valid_attribute_name(name: str) -> bool:
"""
Return whether a name follows the CloudEvents attribute naming convention.

See https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#attribute-naming-convention
"""
return bool(_ATTRIBUTE_NAME_PATTERN.fullmatch(name))
5 changes: 2 additions & 3 deletions src/cloudevents/core/v03/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
# License for the specific language governing permissions and limitations
# under the License.

import re
import uuid
from collections import defaultdict
from datetime import datetime, timezone
Expand All @@ -27,7 +26,7 @@
InvalidAttributeValueError,
MissingRequiredAttributeError,
)
from cloudevents.core.spec import SPECVERSION_V0_3
from cloudevents.core.spec import SPECVERSION_V0_3, is_valid_attribute_name

REQUIRED_ATTRIBUTES: Final[list[str]] = ["id", "source", "type", "specversion"]
OPTIONAL_ATTRIBUTES: Final[list[str]] = [
Expand Down Expand Up @@ -274,7 +273,7 @@ def _validate_extension_attributes(
msg=f"Extension attribute name must be at least 1 character long but was '{extension_attribute}'",
)
)
if not re.match(r"^[a-z0-9]+$", extension_attribute):
if not is_valid_attribute_name(extension_attribute):
errors[extension_attribute].append(
CustomExtensionAttributeError(
attribute_name=extension_attribute,
Expand Down
5 changes: 2 additions & 3 deletions src/cloudevents/core/v1/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
# License for the specific language governing permissions and limitations
# under the License.

import re
import uuid
from collections import defaultdict
from datetime import datetime, timezone
Expand All @@ -27,7 +26,7 @@
InvalidAttributeValueError,
MissingRequiredAttributeError,
)
from cloudevents.core.spec import SPECVERSION_V1_0
from cloudevents.core.spec import SPECVERSION_V1_0, is_valid_attribute_name

REQUIRED_ATTRIBUTES: Final[list[str]] = ["id", "source", "type", "specversion"]
OPTIONAL_ATTRIBUTES: Final[list[str]] = [
Expand Down Expand Up @@ -259,7 +258,7 @@ def _validate_extension_attributes(
msg=f"Extension attribute name must be at least 1 character long but was '{extension_attribute}'",
)
)
if not re.match(r"^[a-z0-9]+$", extension_attribute):
if not is_valid_attribute_name(extension_attribute):
errors[extension_attribute].append(
CustomExtensionAttributeError(
attribute_name=extension_attribute,
Expand Down
4 changes: 4 additions & 0 deletions src/cloudevents/v1/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ class InvalidRequiredFields(GenericException):
pass


class InvalidAttributeName(GenericException):
pass


class InvalidStructuredJSON(GenericException):
pass

Expand Down
17 changes: 17 additions & 0 deletions src/cloudevents/v1/http/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import uuid

import cloudevents.v1.exceptions as cloud_exceptions
from cloudevents.core.spec import is_valid_attribute_name
from cloudevents.v1 import abstract
from cloudevents.v1.sdk.event import v03, v1

Expand All @@ -26,6 +27,19 @@
}


def _validate_attribute_name(name: str) -> None:

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.

Please add a link to the spec reference here to support this validation

"""
Validate names against the CloudEvents attribute naming convention.

See https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#attribute-naming-convention
"""
if not is_valid_attribute_name(name):
raise cloud_exceptions.InvalidAttributeName(
f"Invalid CloudEvent attribute name '{name}': "
"attribute names must only contain lowercase ASCII letters and digits"
)


class CloudEvent(abstract.CloudEvent):
"""
Python-friendly cloudevent class supporting v1 events
Expand Down Expand Up @@ -59,6 +73,8 @@ def __init__(self, attributes: typing.Mapping[str, str], data: typing.Any = None
:type data: typing.Any
"""
self._attributes = {k.lower(): v for k, v in attributes.items()}
for attribute_name in self._attributes:
_validate_attribute_name(attribute_name)
self.data = data
if "specversion" not in self._attributes:
self._attributes["specversion"] = "1.0"
Expand Down Expand Up @@ -88,6 +104,7 @@ def get_data(self) -> typing.Optional[typing.Any]:
return self.data

def __setitem__(self, key: str, value: typing.Any) -> None:
_validate_attribute_name(key)
self._attributes[key] = value

def __delitem__(self, key: str) -> None:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_core/test_v03/test_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,19 @@ def test_required_attributes_null_or_empty(
]
},
),
(
"example-extension",
{
"example-extension": [
str(
CustomExtensionAttributeError(
"example-extension",
"Extension attribute 'example-extension' should only contain lowercase letters and numbers",
)
)
]
},
),
],
)
def test_custom_extension(extension_name: str, expected_error: dict) -> None:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_core/test_v1/test_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,19 @@ def test_required_attributes_null_or_empty(
]
},
),
(
"example-extension",
{
"example-extension": [
str(
CustomExtensionAttributeError(
"example-extension",
"Extension attribute 'example-extension' should only contain lowercase letters and numbers",
)
)
]
},
),
],
)
def test_custom_extension(extension_name: str, expected_error: dict) -> None:
Expand Down
24 changes: 24 additions & 0 deletions tests/test_v1_compat/test_event_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import pytest

import cloudevents.v1.exceptions as cloud_exceptions
from cloudevents.v1.http import CloudEvent, from_http, to_binary, to_structured

test_data = json.dumps({"data-key": "val"})
Expand All @@ -32,6 +33,29 @@ def test_cloudevent_access_extensions(specversion):
assert event["ext1"] == "testval"


def test_cloudevent_rejects_invalid_extension_attribute_name():
with pytest.raises(cloud_exceptions.InvalidAttributeName) as exc:
CloudEvent(
{
"type": "com.example.string",
"source": "https://example.com/event-producer",
"example-extension": "testval",
},
test_data,
)

assert "example-extension" in str(exc.value)


def test_cloudevent_rejects_invalid_extension_attribute_setitem():
event = CloudEvent(test_attributes, test_data)

with pytest.raises(cloud_exceptions.InvalidAttributeName) as exc:
event["example-extension"] = "testval"

assert "example-extension" in str(exc.value)


@pytest.mark.parametrize("specversion", ["0.3", "1.0"])
def test_to_binary_extensions(specversion):
event = CloudEvent(test_attributes, test_data)
Expand Down