Skip to content

Commit

Permalink
Update protected_header type from bytes to dict.
Browse files Browse the repository at this point in the history
  • Loading branch information
dajiaji committed Apr 26, 2021
1 parent b75654d commit 9297958
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
9 changes: 7 additions & 2 deletions cwt/recipient.py
Expand Up @@ -11,7 +11,7 @@ class Recipient(CBORProcessor):

def __init__(
self,
protected: Dict[int, Any] = {},
protected: Union[bytes, Dict[int, Any]] = {},
unprotected: Dict[int, Any] = {},
ciphertext: bytes = b"",
recipients: List[Any] = [],
Expand All @@ -27,7 +27,12 @@ def __init__(
raise ValueError("ciphertext should be zero-length bytes.")
if len(recipients) != 0:
raise ValueError("recipients should be absent.")
self._protected = protected
if protected == b"":
self._protected = {}
elif isinstance(protected, bytes):
self._protected = self._loads(protected)
else:
self._protected = protected
self._unprotected = unprotected
self._ciphertext = ciphertext

Expand Down
16 changes: 13 additions & 3 deletions tests/test_recipient.py
Expand Up @@ -6,6 +6,7 @@
"""
Tests for Recipient.
"""
import cbor2
import pytest

from cwt import Recipient, cose_key
Expand Down Expand Up @@ -40,9 +41,13 @@ def test_recipient_constructor(self):

def test_recipient_constructor_with_args(self):
child = Recipient(unprotected={1: -6, 4: b"our-secret"})
r = Recipient(unprotected={1: -1, 4: b"our-secret"}, recipients=[child])
assert isinstance(r, Recipient)
assert r.protected == {}
r = Recipient(
protected={"foo": "bar"},
unprotected={1: -1, 4: b"our-secret"},
recipients=[child],
)
assert isinstance(r.protected, dict)
assert r.protected["foo"] == "bar"
assert isinstance(r.unprotected, dict)
assert r.kid == b"our-secret"
assert r.alg == -1
Expand All @@ -55,6 +60,11 @@ def test_recipient_constructor_with_args(self):
assert isinstance(res[3][0], list)
assert len(res[3][0]) == 3

def test_recipient_constructor_with_protected_bytes(self):
r = Recipient(protected=cbor2.dumps({"foo": "bar"}))
assert isinstance(r.protected, dict)
assert r.protected["foo"] == "bar"

def test_recipient_constructor_with_empty_recipients(self):
r = Recipient(unprotected={1: -6, 4: b"our-secret"}, recipients=[])
assert isinstance(r, Recipient)
Expand Down

0 comments on commit 9297958

Please sign in to comment.