Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix detach&attach not to create new COSEMessage instance #447

Merged
merged 9 commits into from Oct 17, 2023
22 changes: 9 additions & 13 deletions cwt/cose_message.py
Expand Up @@ -103,13 +103,7 @@ def __init__(self, type: COSETypes, msg: List[Any]):
def __eq__(self: COSEMessage, other: object) -> bool:
if not isinstance(other, COSEMessage):
return NotImplemented
return (
self._type == other._type
and self._protected == other._protected
and self._unprotected == other._unprotected
and self._payload == other._payload
and self._other_fields == other._other_fields
)
return self._type == other._type and self._msg == other._msg

def __ne__(self: COSEMessage, other: object) -> bool:
return not self.__eq__(other)
Expand Down Expand Up @@ -309,16 +303,17 @@ def detach_payload(self: Self) -> Tuple[COSEMessage, bytes]:
Detach a payload from the COSE message

Returns:
Tuple[COSEMessage, bytes]: A byte string of the encoded COSE or a
cbor2.CBORTag object, and a byte string of the detached payload.
Tuple[COSEMessage, bytes]: The COSE message (self),
and a byte string of the detached payload.
Raises:
ValueError: The payload does not exist.
"""

if not isinstance(self._payload, bytes):
if self._msg[2] is None:
raise ValueError("The payload does not exist.")

return COSEMessage(self._type, [self._msg[0], self._msg[1], None, *self._msg[3:]]), self._payload
self._msg[2] = None
return self, self._payload

def attach_payload(self: Self, payload: bytes) -> COSEMessage:
"""
Expand All @@ -332,7 +327,8 @@ def attach_payload(self: Self, payload: bytes) -> COSEMessage:
ValueError: The payload already exist.
"""

if self._payload is not None:
if self._msg[2] is not None:
raise ValueError("The payload already exist.")
self._payload = payload

return COSEMessage(self._type, [self._msg[0], self._msg[1], payload, *self._msg[3:]])
return self
1 change: 1 addition & 0 deletions tests/test_cose_message.py
Expand Up @@ -502,6 +502,7 @@ def test_cose_message_detach_and_attach(self):

detached_content_cose_message, detached_payload = ecdsa_cose_sign1_example.detach_payload()
assert expected_detached_cose_message == detached_content_cose_message
assert expected_detached_cose_message.dumps() == detached_content_cose_message.dumps()
assert expected_payload == detached_payload

reverted_cose_message = detached_content_cose_message.attach_payload(detached_payload)
Expand Down