Skip to content

Commit

Permalink
Merge pull request #113 from dajiaji/divide-cwt-options
Browse files Browse the repository at this point in the history
Divide CWT options into independent parameters.
  • Loading branch information
dajiaji committed Jun 2, 2021
2 parents 340375f + eb91d76 commit d39c1ac
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 35 deletions.
50 changes: 23 additions & 27 deletions cwt/cwt.py
Expand Up @@ -12,8 +12,8 @@
from .exceptions import DecodeError, VerifyError
from .recipient_interface import RecipientInterface

_CWT_DEFAULT_EXPIRES_IN = 3600 # 1 hour
_CWT_DEFAULT_LEEWAY = 60 # 1 min
CWT_DEFAULT_EXPIRES_IN = 3600 # 1 hour
CWT_DEFAULT_LEEWAY = 60 # 1 min


class CWT(CBORProcessor):
Expand All @@ -26,46 +26,42 @@ class CWT(CBORProcessor):

CBOR_TAG = 61

def __init__(self, options: Optional[Dict[str, Any]] = None):
def __init__(
self, expires_in: int = CWT_DEFAULT_EXPIRES_IN, leeway: int = CWT_DEFAULT_LEEWAY
):
"""
Constructor.
Args:
options (Optional[Dict[str, Any]]): Options for the initial
configuration of CWT. At this time, ``expires_in`` (default
value: ``3600`` ) and ``leaway`` (default value: ``60``) are
only supported. See also :func:`expires_in <cwt.CWT.expires_in>`,
:func:`leeway <cwt.CWT.leeway>`.
expires_in(int): The default lifetime in seconds of CWT
(default value: ``3600``).
leeway(int): The default leeway in seconds for validating
``exp`` and ``nbf`` (default value: ``60``).
Examples:
>>> from cwt import CWT, COSEKey
>>> ctx = CWT({"expires_in": 3600*24, "leeway": 10})
>>> key = COSEKey.from_symmetric_key(alg="HS255")
>>> ctx = CWT(expires_in=3600*24, leeway=10)
>>> key = COSEKey.from_symmetric_key(alg="HS256")
>>> token = ctx.encode(
... {"iss": "coaps://as.example", "sub": "dajiaji", "cti": "123"},
... key,
... )
"""
self._expires_in = _CWT_DEFAULT_EXPIRES_IN
self._leeway = _CWT_DEFAULT_LEEWAY
if not isinstance(expires_in, int):
raise ValueError("expires_in should be int.")
if expires_in <= 0:
raise ValueError("expires_in should be positive number.")
self._expires_in = expires_in

if not isinstance(leeway, int):
raise ValueError("leeway should be int.")
if leeway <= 0:
raise ValueError("leeway should be positive number.")
self._leeway = leeway

self._cose = COSE(kid_auto_inclusion=True, alg_auto_inclusion=True)
self._claim_names: Dict[str, int] = {}
if not options:
return

if "expires_in" in options:
if not isinstance(options["expires_in"], int):
raise ValueError("expires_in should be int.")
self._expires_in = options["expires_in"]
if self._expires_in <= 0:
raise ValueError("expires_in should be positive number.")
if "leeway" in options:
if not isinstance(options["leeway"], int):
raise ValueError("leeway should be int.")
self._leeway = options["leeway"]
if self._leeway <= 0:
raise ValueError("leeway should be positive number.")

@property
def expires_in(self) -> int:
Expand Down
29 changes: 21 additions & 8 deletions tests/test_cwt.py
Expand Up @@ -36,27 +36,40 @@ def test_cwt_constructor_without_args(self):
assert ctx.leeway == 60

def test_cwt_constructor_with_expires_in(self):
ctx = CWT(options={"expires_in": 7200})
ctx = CWT(expires_in=7200)
assert isinstance(ctx, CWT)
assert ctx.expires_in == 7200

def test_cwt_constructor_with_leeway(self):
ctx = CWT(options={"leeway": 10})
ctx = CWT(leeway=10)
assert isinstance(ctx, CWT)
assert ctx.leeway == 10

@pytest.mark.parametrize(
"invalid",
[
{"expires_in": "xxx"},
{"expires_in": -1},
{"leeway": "xxx"},
{"leeway": -1},
"xxx",
0,
-1,
],
)
def test_cwt_constructor_with_invalid_args(self, invalid):
def test_cwt_constructor_with_invalid_expires_in(self, invalid):
with pytest.raises(ValueError) as err:
CWT(options=invalid)
CWT(expires_in=invalid)
pytest.fail("CWT() should fail.")
assert "should be" in str(err.value)

@pytest.mark.parametrize(
"invalid",
[
"xxx",
0,
-1,
],
)
def test_cwt_constructor_with_invalid_leeway(self, invalid):
with pytest.raises(ValueError) as err:
CWT(leeway=invalid)
pytest.fail("CWT() should fail.")
assert "should be" in str(err.value)

Expand Down

0 comments on commit d39c1ac

Please sign in to comment.