Skip to content

Better exception handling for missing keys and issuers #51

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

Merged
merged 7 commits into from
Jun 24, 2020
Merged
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
10 changes: 9 additions & 1 deletion src/cryptojwt/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,15 @@ class BadType(Invalid):


class MissingKey(JWKESTException):
""" No usable key """
"""No usable key"""


class KeyNotFound(KeyError):
"""Key not found"""


class IssuerNotFound(KeyError):
"""Issuer not found"""


class KeyIOError(Exception):
Expand Down
21 changes: 5 additions & 16 deletions src/cryptojwt/key_jar.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from requests import request

from .exception import UnknownKeyType, KeyIOError, UpdateFailed, IssuerNotFound
from .jwe.jwe import alg2keytype as jwe_alg2keytype
from .jws.utils import alg2keytype as jws_alg2keytype
from .key_bundle import KeyBundle
Expand All @@ -20,18 +21,6 @@
logger = logging.getLogger(__name__)


class KeyIOError(Exception):
pass


class UnknownKeyType(KeyIOError):
pass


class UpdateFailed(KeyIOError):
pass


class KeyJar(object):
""" A keyjar contains a number of KeyBundles sorted by owner/issuer """

Expand Down Expand Up @@ -252,7 +241,7 @@ def get_issuer_keys(self, issuer_id):
"""
_issuer = self._get_issuer(issuer_id)
if _issuer is None:
raise KeyError(issuer_id)
raise IssuerNotFound(issuer_id)
return _issuer.all_keys()

@deprecated_alias(issuer='issuer_id', owner='issuer_id')
Expand All @@ -273,7 +262,7 @@ def __getitem__(self, issuer_id=''):
"""
_issuer = self._get_issuer(issuer_id)
if _issuer is None:
raise KeyError(issuer_id)
raise IssuerNotFound(issuer_id)
return _issuer

@deprecated_alias(issuer='issuer_id', owner='issuer_id')
Expand Down Expand Up @@ -478,7 +467,7 @@ def _add_key(self, keys, issuer_id, use, key_type='', kid='',
_issuer = self._get_issuer(issuer_id)
if _issuer is None:
logger.error('Issuer "{}" not in keyjar'.format(issuer_id))
return keys
raise IssuerNotFound(issuer_id)

logger.debug('Key summary for {}: {}'.format(issuer_id, _issuer.key_summary()))

Expand Down Expand Up @@ -678,7 +667,7 @@ def key_summary(self, issuer_id):
if _issuer is not None:
return _issuer.key_summary()

raise KeyError('Unknown Issuer ID: "{}"'.format(issuer_id))
raise IssuerNotFound(issuer_id)

def update(self):
"""
Expand Down
6 changes: 3 additions & 3 deletions tests/test_04_key_jar.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import pytest

from cryptojwt.exception import JWKESTException
from cryptojwt.exception import JWKESTException, IssuerNotFound
from cryptojwt.jwe.jwenc import JWEnc
from cryptojwt.jws.jws import JWS
from cryptojwt.jws.jws import factory
Expand Down Expand Up @@ -799,8 +799,8 @@ def test_get_decrypt_keys():
keys = kj.get_jwt_decrypt_keys(jwt)
assert keys

keys = kj.get_jwt_decrypt_keys(jwt, aud='Bob')
assert keys
with pytest.raises(IssuerNotFound):
keys = kj.get_jwt_decrypt_keys(jwt, aud='Bob')


def test_update_keyjar():
Expand Down
27 changes: 27 additions & 0 deletions tests/test_09_jwt.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import os

import pytest

from cryptojwt.exception import JWKESTException, IssuerNotFound
from cryptojwt.jws.exception import NoSuitableSigningKeys
from cryptojwt.jwt import JWT
from cryptojwt.jwt import pick_key
from cryptojwt.key_bundle import KeyBundle
Expand Down Expand Up @@ -64,6 +68,29 @@ def test_jwt_pack_and_unpack():
assert set(info.keys()) == {'iat', 'iss', 'sub'}


def test_jwt_pack_and_unpack_unknown_issuer():
alice = JWT(key_jar=ALICE_KEY_JAR, iss=ALICE, sign_alg='RS256')
payload = {'sub': 'sub'}
_jwt = alice.pack(payload=payload)

kj = KeyJar()
bob = JWT(key_jar=kj, iss=BOB, allowed_sign_algs=["RS256"])
with pytest.raises(IssuerNotFound):
info = bob.unpack(_jwt)


def test_jwt_pack_and_unpack_unknown_key():
alice = JWT(key_jar=ALICE_KEY_JAR, iss=ALICE, sign_alg='RS256')
payload = {'sub': 'sub'}
_jwt = alice.pack(payload=payload)

kj = KeyJar()
kj.add_kb(ALICE, KeyBundle())
bob = JWT(key_jar=kj, iss=BOB, allowed_sign_algs=["RS256"])
with pytest.raises(NoSuitableSigningKeys):
info = bob.unpack(_jwt)


def test_jwt_pack_and_unpack_with_lifetime():
alice = JWT(key_jar=ALICE_KEY_JAR, iss=ALICE, lifetime=600)
payload = {'sub': 'sub'}
Expand Down