Skip to content

Commit 8714a99

Browse files
committed
Added an argument to the dump method. Useful when dumping part of tree of objects.
1 parent 836d3de commit 8714a99

File tree

3 files changed

+77
-55
lines changed

3 files changed

+77
-55
lines changed

src/cryptojwt/key_bundle.py

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import time
77
from datetime import datetime
88
from functools import cmp_to_key
9+
from typing import Optional
910

1011
import requests
1112

@@ -24,7 +25,6 @@
2425
from .jwk.jwk import dump_jwk
2526
from .jwk.jwk import import_jwk
2627
from .jwk.rsa import RSAKey
27-
from .jwk.rsa import import_private_rsa_key_from_file
2828
from .jwk.rsa import new_rsa_key
2929
from .utils import as_unicode
3030

@@ -153,18 +153,18 @@ class KeyBundle:
153153
"""The Key Bundle"""
154154

155155
def __init__(
156-
self,
157-
keys=None,
158-
source="",
159-
cache_time=300,
160-
ignore_errors_period=0,
161-
fileformat="jwks",
162-
keytype="RSA",
163-
keyusage=None,
164-
kid="",
165-
ignore_invalid_keys=True,
166-
httpc=None,
167-
httpc_params=None,
156+
self,
157+
keys=None,
158+
source="",
159+
cache_time=300,
160+
ignore_errors_period=0,
161+
fileformat="jwks",
162+
keytype="RSA",
163+
keyusage=None,
164+
kid="",
165+
ignore_invalid_keys=True,
166+
httpc=None,
167+
httpc_params=None,
168168
):
169169
"""
170170
Contains a set of keys that have a common origin.
@@ -751,7 +751,7 @@ def difference(self, bundle):
751751

752752
return [k for k in self._keys if k not in bundle]
753753

754-
def dump(self):
754+
def dump(self, cutoff: Optional[list] = None):
755755
_keys = []
756756
for _k in self._keys:
757757
_ser = _k.to_dict()
@@ -1246,3 +1246,19 @@ def init_key(filename, type, kid="", **kwargs):
12461246
_new_key = key_gen(type, kid=kid, **kwargs)
12471247
dump_jwk(filename, _new_key)
12481248
return _new_key
1249+
1250+
1251+
def key_by_alg(alg: str):
1252+
if alg.startswith("RS"):
1253+
return key_gen("RSA", alg="RS256")
1254+
elif alg.startswith("ES"):
1255+
if alg == "ES256":
1256+
return key_gen("EC", crv="P-256")
1257+
elif alg == "ES384":
1258+
return key_gen("EC", crv="P-384")
1259+
elif alg == "ES512":
1260+
return key_gen("EC", crv="P-521")
1261+
elif alg.startswith("HS"):
1262+
return key_gen("sym")
1263+
1264+
raise ValueError("Don't know who to create a key to use with '{}'".format(alg))

src/cryptojwt/key_issuer.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import json
22
import logging
33
import os
4+
from typing import Optional
45

56
from requests import request
67

@@ -350,16 +351,18 @@ def __len__(self):
350351
nr += len(kb)
351352
return nr
352353

353-
def dump(self, exclude=None):
354+
def dump(self, exclude=None, cutoff: Optional[list]=None) -> dict:
354355
"""
355356
Returns the content as a dictionary.
356357
358+
:param exclude: Issuer that should not be include in the dump
359+
:param cutoff: List of attribute name for objects that should be ignored.
357360
:return: A dictionary
358361
"""
359362

360363
_bundles = []
361364
for kb in self._bundles:
362-
_bundles.append(kb.dump())
365+
_bundles.append(kb.dump(cutoff=cutoff))
363366

364367
info = {
365368
"name": self.name,

src/cryptojwt/key_jar.py

Lines changed: 42 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,13 @@ class KeyJar(object):
2525
""" A keyjar contains a number of KeyBundles sorted by owner/issuer """
2626

2727
def __init__(
28-
self,
29-
ca_certs=None,
30-
verify_ssl=True,
31-
keybundle_cls=KeyBundle,
32-
remove_after=3600,
33-
httpc=None,
34-
httpc_params=None,
35-
storage=None,
28+
self,
29+
ca_certs=None,
30+
verify_ssl=True,
31+
keybundle_cls=KeyBundle,
32+
remove_after=3600,
33+
httpc=None,
34+
httpc_params=None,
3635
):
3736
"""
3837
KeyJar init function
@@ -43,15 +42,9 @@ def __init__(
4342
:param remove_after: How long keys marked as inactive will remain in the key Jar.
4443
:param httpc: A HTTP client to use. Default is Requests request.
4544
:param httpc_params: HTTP request parameters
46-
:param storage: An instance that can store information. It basically look like dictionary.
4745
:return: Keyjar instance
4846
"""
49-
50-
if storage is None:
51-
self._issuers = {}
52-
else:
53-
self._issuers = storage
54-
47+
self._issuers = {}
5548
self.spec2key = {}
5649
self.ca_certs = ca_certs
5750
self.keybundle_cls = keybundle_cls
@@ -386,7 +379,7 @@ def export_jwks(self, private=False, issuer_id="", usage=None):
386379
k.serialize(private)
387380
for k in kb.keys()
388381
if k.inactive_since == 0
389-
and (usage is None or (hasattr(k, "use") and k.use == usage))
382+
and (usage is None or (hasattr(k, "use") and k.use == usage))
390383
]
391384
)
392385
return {"keys": keys}
@@ -472,14 +465,14 @@ def remove_outdated(self, when=0):
472465

473466
@deprecated_alias(issuer="issuer_id", owner="issuer_id")
474467
def _add_key(
475-
self,
476-
keys,
477-
issuer_id,
478-
use,
479-
key_type="",
480-
kid="",
481-
no_kid_issuer=None,
482-
allow_missing_kid=False,
468+
self,
469+
keys,
470+
issuer_id,
471+
use,
472+
key_type="",
473+
kid="",
474+
no_kid_issuer=None,
475+
allow_missing_kid=False,
483476
):
484477

485478
_issuer = self._get_issuer(issuer_id)
@@ -617,8 +610,6 @@ def copy(self):
617610
"""
618611
Make deep copy of the content of this key jar.
619612
620-
Note that if this key jar uses an external storage module the copy will not.
621-
622613
:return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
623614
"""
624615

@@ -635,10 +626,12 @@ def copy(self):
635626
def __len__(self):
636627
return len(self._issuers)
637628

638-
def dump(self, exclude=None):
629+
def dump(self, exclude: Optional[bool] = None, cutoff: Optional[list] = None) -> dict:
639630
"""
640631
Returns the key jar content as dictionary
641632
633+
:param cutoff: list of attribute names that should be ignored when dumping.
634+
:type cutoff: list
642635
:return: A dictionary
643636
"""
644637

@@ -654,11 +647,21 @@ def dump(self, exclude=None):
654647
for _id, _issuer in self._issuers.items():
655648
if exclude and _issuer.name in exclude:
656649
continue
657-
_issuers[_id] = _issuer.dump()
650+
_issuers[_id] = _issuer.dump(cutoff=cutoff)
658651
info["issuers"] = _issuers
659652

660653
return info
661654

655+
def dumps(self, exclude=None):
656+
"""
657+
Returns a JSON representation of the key jar
658+
659+
:param exclude: Exclude these issuers
660+
:return: A string
661+
"""
662+
_dict = self.dump(exclude=exclude)
663+
return json.dumps(_dict)
664+
662665
def load(self, info):
663666
"""
664667
@@ -675,6 +678,9 @@ def load(self, info):
675678
self._issuers[_issuer_id] = KeyIssuer().load(_issuer_desc)
676679
return self
677680

681+
def loads(self, string):
682+
return self.load(json.loads(string))
683+
678684
@deprecated_alias(issuer="issuer_id", owner="issuer_id")
679685
def key_summary(self, issuer_id):
680686
_issuer = self._get_issuer(issuer_id)
@@ -705,7 +711,7 @@ def rotate_keys(self, key_conf, kid_template="", issuer_id=""):
705711
# =============================================================================
706712

707713

708-
def build_keyjar(key_conf, kid_template="", keyjar=None, issuer_id="", storage=None):
714+
def build_keyjar(key_conf, kid_template="", keyjar=None, issuer_id=""):
709715
"""
710716
Builds a :py:class:`oidcmsg.key_jar.KeyJar` instance or adds keys to
711717
an existing KeyJar based on a key specification.
@@ -744,7 +750,6 @@ def build_keyjar(key_conf, kid_template="", keyjar=None, issuer_id="", storage=N
744750
kid_template is given then the built-in function add_kid() will be used.
745751
:param keyjar: If an KeyJar instance the new keys are added to this key jar.
746752
:param issuer_id: The default owner of the keys in the key jar.
747-
:param storage: A Storage instance.
748753
:return: A KeyJar instance
749754
"""
750755

@@ -753,7 +758,7 @@ def build_keyjar(key_conf, kid_template="", keyjar=None, issuer_id="", storage=N
753758
return None
754759

755760
if keyjar is None:
756-
keyjar = KeyJar(storage=storage)
761+
keyjar = KeyJar()
757762

758763
keyjar[issuer_id] = _issuer
759764

@@ -762,12 +767,11 @@ def build_keyjar(key_conf, kid_template="", keyjar=None, issuer_id="", storage=N
762767

763768
@deprecated_alias(issuer="issuer_id", owner="issuer_id")
764769
def init_key_jar(
765-
public_path="",
766-
private_path="",
767-
key_defs="",
768-
issuer_id="",
769-
read_only=True,
770-
storage=None,
770+
public_path="",
771+
private_path="",
772+
key_defs="",
773+
issuer_id="",
774+
read_only=True,
771775
):
772776
"""
773777
A number of cases here:
@@ -805,7 +809,6 @@ def init_key_jar(
805809
:param key_defs: A definition of what keys should be created if they are not already available
806810
:param issuer_id: The owner of the keys
807811
:param read_only: This function should not attempt to write anything to a file system.
808-
:param storage: A Storage instance.
809812
:return: An instantiated :py:class;`oidcmsg.key_jar.KeyJar` instance
810813
"""
811814

@@ -819,7 +822,7 @@ def init_key_jar(
819822
if _issuer is None:
820823
raise ValueError("Could not find any keys")
821824

822-
keyjar = KeyJar(storage=storage)
825+
keyjar = KeyJar()
823826
keyjar[issuer_id] = _issuer
824827
return keyjar
825828

0 commit comments

Comments
 (0)