code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if text.startswith("0"): base = 16 if text.startswith("0x") else 8 else: base = 10 try: return int(text, base) except (ValueError, TypeError): raise InvalidArgument(text)
def from_yang(self, text: str) -> Optional[int]
Override the superclass method.
3.332372
3.092169
1.077681
# create input structure if 'structure' in self.inputs: self.inputs.structure.export(folder.get_abs_path(self._DEFAULT_COORDS_FILE_NAME), fileformat="xyz") # create cp2k input file inp = Cp2kInput(self.inputs.parameters.get_dict()) inp.add_keyword("GLOBAL/PR...
def prepare_for_submission(self, folder)
Create the input files from the input nodes passed to this instance of the `CalcJob`. :param folder: an `aiida.common.folders.Folder` to temporarily write files on disk :return: `aiida.common.datastructures.CalcInfo` instance
2.374986
2.334998
1.017125
if len(kwpath) == 1: params[kwpath[0]] = value elif kwpath[0] not in params.keys(): new_subsection = {} params[kwpath[0]] = new_subsection self._add_keyword_low(kwpath[1:], value, new_subsection) else: self._add_keyword_low(kwp...
def _add_keyword_low(self, kwpath, value, params)
Adds keyword
1.885959
1.885017
1.0005
for key, val in sorted(params.items()): if key.upper() != key: raise InputValidationError("keyword '%s' not upper case" % key) if key.startswith('@') or key.startswith('$'): raise InputValidationError("CP2K preprocessor not supported") ...
def _render_section(self, output, params, indent=0)
It takes a dictionary and recurses through. For key-value pair it checks whether the value is a dictionary and prepends the key with & It passes the valued to the same function, increasing the indentation If the value is a list, I assume that this is something the user wants to ...
2.576964
2.424704
1.062796
cursor = connections[router.db_for_read(models[0])].cursor() cursor.execute(query, params) rows = cursor.fetchall() for row in rows: row_iter = iter(row) yield [model_class(**dict((a, next(row_iter)) for a in model_to_fields[model_class])) ...
def multi_raw(query, params, models, model_to_fields)
Scoop multiple model instances out of the DB at once, given a query that returns all fields of each. Return an iterable of sequences of model instances parallel to the ``models`` sequence of classes. For example:: [(<User such-and-such>, <Watch such-and-such>), ...]
3.063291
3.773238
0.811847
server_relative = ('%s?s=%s' % (reverse('tidings.unsubscribe', args=[self.pk]), self.secret)) return 'https://%s%s' % (Site.objects.get_current().domain, server_relative)
def unsubscribe_url(self)
Return the absolute URL to visit to delete me.
5.624005
4.990369
1.126972
Watch.objects.filter(email=user.email).update(email=None, user=user)
def claim_watches(user)
Attach any anonymous watches having a user's email to that user. Call this from your user registration process if you like.
6.268571
6.116328
1.024891
key = kwargs.pop('key', lambda a: a) reverse = kwargs.pop('reverse', False) min_or_max = max if reverse else min rows = [iter(iterable) for iterable in iterables if iterable] next_values = {} by_key = [] def gather_next_value(row, index): try: next_value = next(row...
def collate(*iterables, **kwargs)
Return an iterable ordered collation of the already-sorted items from each of ``iterables``, compared by kwarg ``key``. If ``reverse=True`` is passed, iterables must return their results in descending order rather than ascending.
2.319694
2.270504
1.021664
if isinstance(data, string_types): # Return a CRC32 value identical across Python versions and platforms # by stripping the sign bit as on # http://docs.python.org/library/zlib.html. return crc32(data.encode('utf-8')) & 0xffffffff else: return int(data)
def hash_to_unsigned(data)
If ``data`` is a string or unicode string, return an unsigned 4-byte int hash of it. If ``data`` is already an int that fits those parameters, return it verbatim. If ``data`` is an int outside that range, behavior is undefined at the moment. We rely on the ``PositiveIntegerField`` on :class:`~tidin...
5.803123
5.783436
1.003404
template = loader.get_template(template_path) context = Context(vars) for u, w in users_and_watches: context['user'] = u # Arbitrary single watch for compatibility with 0.1 # TODO: remove. context['watch'] = w[0] context['watches'] = w yield EmailMessag...
def emails_with_users_and_watches( subject, template_path, vars, users_and_watches, from_email=settings.TIDINGS_FROM_ADDRESS, **extra_kwargs)
Return iterable of EmailMessages with user and watch values substituted. A convenience function for generating emails by repeatedly rendering a Django template with the given ``vars`` plus a ``user`` and ``watches`` key for each pair in ``users_and_watches`` :arg template_path: path to template file ...
3.456722
3.629393
0.952424
path = getattr(settings, setting_name, None) if path: try: return import_string(path) except ImportError: raise ImproperlyConfigured('%s: No such path.' % path) else: return fallback
def import_from_setting(setting_name, fallback)
Return the resolution of an import path stored in a Django setting. :arg setting_name: The name of the setting holding the import path :arg fallback: An alternate object to use if the setting is empty or doesn't exist Raise ImproperlyConfigured if a path is given that can't be resolved.
3.391834
3.561337
0.952405
from aiida.engine import ExitCode from aiida.common import NotExistent try: out_folder = self.retrieved except NotExistent: return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER self._parse_stdout(out_folder) try: structure = sel...
def parse(self, **kwargs)
Receives in input a dictionary of retrieved nodes. Does all the logic here.
2.576245
2.556347
1.007784
fname = self.node.load_process_class()._DEFAULT_OUTPUT_FILE # pylint: disable=protected-access if fname not in out_folder._repository.list_object_names(): # pylint: disable=protected-access raise OutputParsingError("Cp2k output file not retrieved") result_dict = {'exceede...
def _parse_stdout(self, out_folder)
CP2K output parser
3.358644
3.13741
1.070515
kpoints = [] labels = [] bands_s1 = [] bands_s2 = [] known_kpoints = {} pattern = re.compile(".*?Nr.*?Spin.*?K-Point.*?", re.DOTALL) selected_lines = lines[n_start:] for current_line, line in enumerate(selected_lines): splitted = line...
def _parse_bands(lines, n_start)
Parse band structure from cp2k output
3.011166
2.942184
1.023446
fname = self.node.load_process_class()._DEFAULT_RESTART_FILE_NAME # pylint: disable=protected-access if fname not in out_folder._repository.list_object_names(): # pylint: disable=protected-access raise Exception # not every run type produces a trajectory # read restart f...
def _parse_trajectory(self, out_folder)
CP2K trajectory parser
2.872838
2.754361
1.043014
ext = getattr(settings, 'TIDINGS_TEMPLATE_EXTENSION', 'html') # Grab the watch and secret; complain if either is wrong: try: watch = Watch.objects.get(pk=watch_id) # 's' is for 'secret' but saves wrapping in mails secret = request.GET.get('s') if secret != watch.secret:...
def unsubscribe(request, watch_id)
Unsubscribe from (i.e. delete) the watch of ID ``watch_id``. Expects an ``s`` querystring parameter matching the watch's secret. GET will result in a confirmation page (or a failure page if the secret is wrong). POST will actually delete the watch (again, if the secret is correct). Uses these tem...
4.128608
3.618794
1.14088
def ensure_user_has_email(user, cluster_email): # Some of these cases shouldn't happen, but we're tolerant. if not getattr(user, 'email', ''): user = EmailUser(cluster_email) return user # TODO: Do this instead with clever SQL that somehow returns just the ...
def _unique_by_email(users_and_watches)
Given a sequence of (User/EmailUser, [Watch, ...]) pairs clustered by email address (which is never ''), yield from each cluster a single pair like this:: (User/EmailUser, [Watch, Watch, ...]). The User/Email is that of... (1) the first incoming pair where the User has an email and is not ...
4.833209
4.466372
1.082133
if delay: # Tasks don't receive the `self` arg implicitly. self._fire_task.apply_async( args=(self,), kwargs={'exclude': exclude}, serializer='pickle') else: self._fire_task(self, exclude=exclude)
def fire(self, exclude=None, delay=True)
Notify everyone watching the event. We are explicit about sending notifications; we don't just key off creation signals, because the receiver of a ``post_save`` signal has no idea what just changed, so it doesn't know which notifications to send. Also, we could easily send mail accident...
5.760839
5.89357
0.977479
connection = mail.get_connection(fail_silently=True) # Warning: fail_silently swallows errors thrown by the generators, too. connection.open() for m in self._mails(self._users_watching(exclude=exclude)): connection.send_messages([m])
def _fire_task(self, exclude=None)
Build and send the emails as a celery task.
8.716096
7.472419
1.166436
for k in iterkeys(filters): if k not in cls.filters: # Mirror "unexpected keyword argument" message: raise TypeError("%s got an unsupported filter type '%s'" % (cls.__name__, k))
def _validate_filters(cls, filters)
Raise a TypeError if ``filters`` contains any keys inappropriate to this event class.
7.962244
7.452926
1.068338
# If we have trouble distinguishing subsets and such, we could store a # number_of_filters on the Watch. cls._validate_filters(filters) if isinstance(user_or_email, string_types): user_condition = Q(email=user_or_email) elif user_or_email.is_authenticated: ...
def _watches_belonging_to_user(cls, user_or_email, object_id=None, **filters)
Return a QuerySet of watches having the given user or email, having (only) the given filters, and having the event_type and content_type attrs of the class. Matched Watches may be either confirmed and unconfirmed. They may include duplicates if the get-then-create race condition in ...
4.765862
4.884731
0.975665
return cls._watches_belonging_to_user(user_or_email_, object_id=object_id, **filters).exists()
def is_notifying(cls, user_or_email_, object_id=None, **filters)
Return whether the user/email is watching this event (either active or inactive watches), conditional on meeting the criteria in ``filters``. Count only watches that match the given filters exactly--not ones which match merely a superset of them. This lets callers distinguish between ...
5.046373
4.788548
1.053842
# A test-for-existence-then-create race condition exists here, but it # doesn't matter: de-duplication on fire() and deletion of all matches # on stop_notifying() nullify its effects. try: # Pick 1 if >1 are returned: watch = cls._watches_belonging_to_use...
def notify(cls, user_or_email_, object_id=None, **filters)
Start notifying the given user or email address when this event occurs and meets the criteria given in ``filters``. Return the created (or the existing matching) Watch so you can call :meth:`~tidings.models.Watch.activate()` on it if you're so inclined. Implementations in subclasses ma...
4.999435
4.371515
1.143639
return super(InstanceEvent, cls).notify(user_or_email, object_id=instance.pk)
def notify(cls, user_or_email, instance)
Create, save, and return a watch which fires when something happens to ``instance``.
6.448715
6.641132
0.971027
super(InstanceEvent, cls).stop_notifying(user_or_email, object_id=instance.pk)
def stop_notifying(cls, user_or_email, instance)
Delete the watch created by notify.
5.999866
5.429719
1.105005
return super(InstanceEvent, cls).is_notifying(user_or_email, object_id=instance.pk)
def is_notifying(cls, user_or_email, instance)
Check if the watch created by notify exists.
5.810083
5.094923
1.140367
return self._users_watching_by_filter(object_id=self.instance.pk, **kwargs)
def _users_watching(self, **kwargs)
Return users watching this instance.
8.32948
7.074586
1.177381
if not self._crypter: return b'' try: plaintext = self._crypter.decrypt(self._ciphertext, **self._decrypt_params) return plaintext except Exception as e: exc_info = sys.exc_info() six.reraise( ValueError('Invali...
def decrypt(self)
Decrypt decrypts the secret and returns the plaintext. Calling decrypt() may incur side effects such as a call to a remote service for decryption.
3.432196
3.421018
1.003267
if not iv: raise ValueError('Missing Nonce') return self.key.encrypt(iv, msg, auth_data)
def encrypt(self, msg, iv='', auth_data=None)
Encrypts and authenticates the data provided as well as authenticating the associated_data. :param msg: The message to be encrypted :param iv: MUST be present, at least 96-bit long :param auth_data: Associated data :return: The cipher text bytes with the 16 byte tag appended.
7.998465
9.712939
0.823485
if not iv: raise ValueError('Missing Nonce') return self.key.decrypt(iv, cipher_text+tag, auth_data)
def decrypt(self, cipher_text, iv='', auth_data=None, tag=b'')
Decrypts the data and authenticates the associated_data (if provided). :param cipher_text: The data to decrypt including tag :param iv: Initialization Vector :param auth_data: Associated data :param tag: Authentication tag :return: The original plaintext
7.074733
9.0806
0.779104
iv = self._generate_iv(enc_alg, iv) if enc_alg in ["A192GCM", "A128GCM", "A256GCM"]: aes = AES_GCMEncrypter(key=key) ctx, tag = split_ctx_and_tag(aes.encrypt(msg, iv, auth_data)) elif enc_alg in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]: a...
def enc_setup(self, enc_alg, msg, auth_data=b'', key=None, iv="")
Encrypt JWE content. :param enc_alg: The JWE "enc" value specifying the encryption algorithm :param msg: The plain text message :param auth_data: Additional authenticated data :param key: Key (CEK) :return: Tuple (ciphertext, tag), both as bytes
2.367037
2.413227
0.98086
if enc in ["A128GCM", "A192GCM", "A256GCM"]: aes = AES_GCMEncrypter(key=key) elif enc in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]: aes = AES_CBCEncrypter(key=key) else: raise Exception("Unsupported encryption algorithm %s" % enc) t...
def _decrypt(enc, key, ctxt, iv, tag, auth_data=b'')
Decrypt JWE content. :param enc: The JWE "enc" value specifying the encryption algorithm :param key: Key (CEK) :param iv : Initialization vector :param auth_data: Additional authenticated data (AAD) :param ctxt : Ciphertext :param tag: Authentication tag :return:...
1.920214
1.912379
1.004097
hasher = hashes.Hash(self.hash_algorithm(), backend=default_backend()) hasher.update(msg) digest = hasher.finalize() sig = key.sign( digest, padding.PSS( mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_...
def sign(self, msg, key)
Create a signature over a message :param msg: The message :param key: The key :return: A signature
1.760473
2.043518
0.861491
try: key.verify(signature, msg, padding.PSS(mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH), self.hash_algorithm()) except InvalidSignature as err: raise BadSign...
def verify(self, msg, signature, key)
Verify a message signature :param msg: The message :param sig: A signature :param key: A ec.EllipticCurvePublicKey to use for the verification. :raises: BadSignature if the signature can't be verified. :return: True
2.485387
2.630635
0.944786
_msg = as_bytes(self.msg) _args = self._dict try: _args["kid"] = kwargs["kid"] except KeyError: pass jwe = JWEnc(**_args) # If no iv and cek are given generate them iv = self._generate_iv(self["enc"], iv) cek = self._gen...
def encrypt(self, key, iv="", cek="", **kwargs)
Produces a JWE as defined in RFC7516 using symmetric keys :param key: Shared symmetric key :param iv: Initialization vector :param cek: Content master key :param kwargs: Extra keyword arguments, just ignore for now. :return:
6.126093
6.250346
0.980121
ecpn = ec.EllipticCurvePublicNumbers(num['x'], num['y'], NIST2SEC[as_unicode(num['crv'])]()) return ecpn.public_key(default_backend())
def ec_construct_public(num)
Given a set of values on public attributes build a elliptic curve public key instance. :param num: A dictionary with public attributes and their values :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey instance.
7.495883
7.448659
1.00634
pub_ecpn = ec.EllipticCurvePublicNumbers(num['x'], num['y'], NIST2SEC[as_unicode(num['crv'])]()) priv_ecpn = ec.EllipticCurvePrivateNumbers(num['d'], pub_ecpn) return priv_ecpn.private_key(default_backend())
def ec_construct_private(num)
Given a set of values on public and private attributes build a elliptic curve private key instance. :param num: A dictionary with public and private attributes and their values :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey instance.
4.944014
5.015231
0.9858
with open(filename, "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=passphrase, backend=default_backend()) return private_key
def import_private_key_from_file(filename, passphrase=None)
Read a private Elliptic Curve key from a PEM file. :param filename: The name of the file :param passphrase: A pass phrase to use to unpack the PEM file. :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey instance
1.73572
2.283231
0.760203
if isinstance(self.x, (str, bytes)): _x = deser(self.x) else: raise ValueError('"x" MUST be a string') if isinstance(self.y, (str, bytes)): _y = deser(self.y) else: raise ValueError('"y" MUST be a string') if self.d: ...
def deserialize(self)
Starting with information gathered from the on-the-wire representation of an elliptic curve key (a JWK) initiate an cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey or EllipticCurvePrivateKey instance. So we have to get from having:: { "kty":"EC", ...
2.669589
2.051059
1.301566
if self.priv_key: self._serialize(self.priv_key) else: self._serialize(self.pub_key) res = self.common() res.update({ "crv": self.crv, "x": self.x, "y": self.y }) if private and self.d: re...
def serialize(self, private=False)
Go from a cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey or EllipticCurvePublicKey instance to a JWK representation. :param private: Whether we should include the private attributes or not. :return: A JWK as a dictionary
3.118153
3.152856
0.988993
self._serialize(key) if isinstance(key, ec.EllipticCurvePrivateKey): self.priv_key = key self.pub_key = key.public_key() else: self.pub_key = key return self
def load_key(self, key)
Load an Elliptic curve key :param key: An elliptic curve key instance, private or public. :return: Reference to this instance
3.484919
3.212251
1.084884
try: size = spec['size'] except KeyError: size = 2048 kb = KeyBundle(keytype="RSA") if 'use' in spec: for use in harmonize_usage(spec["use"]): _key = new_rsa_key(use=use, key_size=size) kb.append(_key) else: _key = new_rsa_key(key_size=s...
def rsa_init(spec)
Initiates a :py:class:`oidcmsg.keybundle.KeyBundle` instance containing newly minted RSA keys according to a spec. Example of specification:: {'size':2048, 'use': ['enc', 'sig'] } Using the spec above 2 RSA keys would be minted, one for encryption and one for signing. ...
3.580727
2.863155
1.250623
kb = KeyBundle(keytype="EC") if 'use' in spec: for use in spec["use"]: eck = new_ec_key(crv=spec['crv'], use=use) kb.append(eck) else: eck = new_ec_key(crv=spec['crv']) kb.append(eck) return kb
def ec_init(spec)
Initiate a key bundle with an elliptic curve key. :param spec: Key specifics of the form:: {"type": "EC", "crv": "P-256", "use": ["sig"]} :return: A KeyBundle instance
3.856128
2.983623
1.292431
usage = harmonize_usage(usage) if typ.lower() == "jwks": kb = KeyBundle(source=filename, fileformat="jwks", keyusage=usage) elif typ.lower() == 'der': kb = KeyBundle(source=filename, fileformat="der", keyusage=usage) else: raise UnknownKeyType("Unsupported key type") r...
def keybundle_from_local_file(filename, typ, usage)
Create a KeyBundle based on the content in a local file :param filename: Name of the file :param typ: Type of content :param usage: What the key should be used for :return: The created KeyBundle
3.779077
4.448425
0.849531
keys = [] for kb in kbl: keys.extend([k.serialize(private) for k in kb.keys() if k.kty != 'oct' and not k.inactive_since]) res = {"keys": keys} try: f = open(target, 'w') except IOError: (head, tail) = os.path.split(target) os.makedirs(head...
def dump_jwks(kbl, target, private=False)
Write a JWK to a file. Will ignore symmetric keys !! :param kbl: List of KeyBundles :param target: Name of the file to which everything should be written :param private: Should also the private parts be exported
3.208036
3.204661
1.001053
kid = 0 tot_kb = KeyBundle() for spec in key_conf: typ = spec["type"].upper() if typ == "RSA": if "key" in spec: error_to_catch = (OSError, IOError, DeSerializationNotPossible) try: kb =...
def build_key_bundle(key_conf, kid_template="")
Builds a :py:class:`oidcmsg.key_bundle.KeyBundle` instance based on a key specification. An example of such a specification:: keys = [ {"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]}, {"type": "EC", "crv": "P-256", "use": ["sig"], "kid": "ec.1"}, {"...
3.740525
3.584463
1.043538
_l = _cmp(kd1['type'], kd2['type']) if _l: return _l if kd1['type'] == 'EC': _l = _cmp(kd1['crv'], kd2['crv']) if _l: return _l _l = _cmp(kd1['type'], kd2['type']) if _l: return _l _l = _cmp(kd1['use'][0], kd2['use'][0]) if _l: retu...
def sort_func(kd1, kd2)
Compares 2 key descriptions :param kd1: First key description :param kd2: Second key description :return: -1,0,1 depending on whether kd1 le,eq or gt then kd2
1.816988
1.854367
0.979843
_int = [] # First make sure all defs only reference one usage for kd in key_def: if len(kd['use']) > 1: for _use in kd['use']: _kd = kd.copy() _kd['use'] = _use _int.append(_kd) else: _int.append(kd) _int.sort(...
def order_key_defs(key_def)
Sort a set of key definitions. A key definition that defines more then one usage type are splitted into as many definitions as the number of usage types specified. One key definition per usage type. :param key_def: A set of key definitions :return: The set of definitions as a sorted list
4.269741
3.932526
1.08575
keys = key_bundle.get() diff = {} # My own sorted copy key_defs = order_key_defs(key_defs)[:] used = [] for key in keys: match = False for kd in key_defs: if key.use not in kd['use']: continue if key.kty != kd['type']: ...
def key_diff(key_bundle, key_defs)
Creates a difference dictionary with keys that should added and keys that should be deleted from a Key Bundle to get it updated to a state that mirrors What is in the key_defs specification. :param key_bundle: The original KeyBundle :param key_defs: A set of key definitions :return: A dictionary wi...
3.35395
3.255303
1.030304
try: _add = diff['add'] except KeyError: pass else: key_bundle.extend(_add) try: _del = diff['del'] except KeyError: pass else: _now = time.time() for k in _del: k.inactive_since = _now
def update_key_bundle(key_bundle, diff)
Apply a diff specification to a KeyBundle. The keys that are to be added are added. The keys that should be deleted are marked as inactive. :param key_bundle: The original KeyBundle :param diff: The difference specification :return: An updated key_bundle
3.17608
3.036461
1.045981
key_spec = [] for key in kb.get(): _spec = {'type': key.kty, 'use':[key.use]} if key.kty == 'EC': _spec['crv'] = key.crv key_spec.append(_spec) diff = {'del': kb.get()} _kb = build_key_bundle(key_spec) diff['add'] = _kb.keys() update_key_bundle(kb, dif...
def key_rollover(kb)
A nifty function that lets you do a key rollover that encompasses creating a completely new set of keys. One new per every old one. With the same specifications as the old one. All the old ones are marked as inactive. :param kb: :return:
4.619861
4.561673
1.012756
for inst in keys: typ = inst["kty"] try: _usage = harmonize_usage(inst['use']) except KeyError: _usage = [''] else: del inst['use'] flag = 0 for _use in _usage: for _...
def do_keys(self, keys)
Go from JWK description to binary keys :param keys: :return:
4.547682
4.109363
1.106663
_info = json.loads(open(filename).read()) if 'keys' in _info: self.do_keys(_info["keys"]) else: self.do_keys([_info]) self.last_updated = time.time()
def do_local_jwk(self, filename)
Load a JWKS from a local file :param filename:
3.688111
4.152516
0.888163
_bkey = import_private_rsa_key_from_file(filename) if keytype.lower() != 'rsa': raise NotImplemented('No support for DER decoding of that key type') if not keyusage: keyusage = ["enc", "sig"] else: keyusage = harmonize_usage(keyusage) ...
def do_local_der(self, filename, keytype, keyusage=None, kid='')
Load a DER encoded file amd create a key from it. :param filename: :param keytype: Presently only 'rsa' supported :param keyusage: encryption ('enc') or signing ('sig') or both
4.272693
4.669602
0.915001
if self.verify_ssl: args = {"verify": self.verify_ssl} else: args = {} try: logging.debug('KeyBundle fetch keys from: {}'.format(self.source)) r = self.httpc('GET', self.source, **args) except Exception as err: logger....
def do_remote(self)
Load a JWKS from a webpage :return: True or False if load was successful
3.652983
3.339961
1.09372
# Check if the content type is the right one. try: if response.headers["Content-Type"] != 'application/json': logger.warning('Wrong Content_type ({})'.format( response.headers["Content-Type"])) except KeyError: pass lo...
def _parse_remote_response(self, response)
Parse JWKS from the HTTP response. Should be overriden by subclasses for adding support of e.g. signed JWKS. :param response: HTTP response from the 'jwks_uri' endpoint :return: response parsed as JSON
4.119063
3.693604
1.115188
res = True # An update was successful if self.source: _keys = self._keys # just in case # reread everything self._keys = [] try: if self.remote is False: if self.fileformat in ["jwks", "jwk"]: ...
def update(self)
Reload the keys if necessary This is a forced update, will happen even if cache time has not elapsed. Replaced keys will be marked as inactive and not removed.
5.295059
4.599444
1.151239
self._uptodate() _typs = [typ.lower(), typ.upper()] if typ: _keys = [k for k in self._keys if k.kty in _typs] else: _keys = self._keys if only_active: return [k for k in _keys if not k.inactive_since] else: return...
def get(self, typ="", only_active=True)
Return a list of keys. Either all keys or only keys of a specific type :param typ: Type of key (rsa, ec, oct, ..) :return: If typ is undefined all the keys as a dictionary otherwise the appropriate keys in a list
3.776907
3.583304
1.054029
_typs = [typ.lower(), typ.upper()] self._keys = [k for k in self._keys if not k.kty in _typs]
def remove_keys_by_type(self, typ)
Remove keys that are of a specific type. :param typ: Type of key (rsa, ec, oct, ..)
5.081658
5.699463
0.891603
self._uptodate() keys = list() for k in self._keys: if private: key = k.serialize(private) else: key = k.serialize() for k, v in key.items(): key[k] = as_unicode(v) keys.append(key) ...
def jwks(self, private=False)
Create a JWKS as a JSON document :param private: Whether private key information should be included. :return: A JWKS JSON representation of the keys in this bundle
3.76744
3.470186
1.085659
for key in self._keys: if key.kid == kid: return key # Try updating since there might have been an update to the key file self.update() for key in self._keys: if key.kid == kid: return key return None
def get_key_with_kid(self, kid)
Return the key that has a specific key ID (kid) :param kid: The Key ID :return: The key or None
3.665838
3.759259
0.975149
self._uptodate() return [key.kid for key in self._keys if key.kid != ""]
def kids(self)
Return a list of key IDs. Note that this list may be shorter then the list of keys. The reason might be that there are some keys with no key ID. :return: A list of all the key IDs that exists in this bundle
11.280932
9.92121
1.137052
k = self.get_key_with_kid(kid) k.inactive_since = time.time()
def mark_as_inactive(self, kid)
Mark a specific key as inactive based on the keys KeyID :param kid: The Key Identifier
6.081429
6.483853
0.937934
if when: now = when else: now = time.time() if not isinstance(after, float): try: after = float(after) except TypeError: raise _kl = [] for k in self._keys: if k.inactive_since ...
def remove_outdated(self, after, when=0)
Remove keys that should not be available any more. Outdated means that the key was marked as inactive at a time that was longer ago then what is given in 'after'. :param after: The length of time the key will remain in the KeyBundle before it should be removed. :param when: ...
3.555563
3.512596
1.012232
kb = KeyBundle() kb._keys = self._keys[:] kb.cache_time = self.cache_time kb.verify_ssl = self.verify_ssl if self.source: kb.source = self.source kb.fileformat = self.fileformat kb.keytype = self.keytype kb.keyusage = self...
def copy(self)
Make deep copy of this KeyBundle :return: The copy
4.312537
4.174925
1.032962
if isinstance(token, str): try: token = token.encode("utf-8") except UnicodeDecodeError: pass part = split_token(token) self.b64part = part self.part = [b64d(p) for p in part] self.headers = json.loads(as_unicode(s...
def unpack(self, token, **kwargs)
Unpacks a JWT into its parts and base64 decodes the parts individually :param token: The JWT :param kwargs: A possible empty set of claims to verify the header against.
3.973441
3.739454
1.062572
if not headers: if self.headers: headers = self.headers else: headers = {'alg': 'none'} logging.debug('JWT header: {}'.format(headers)) if not parts: return ".".join([a.decode() for a in self.b64part]) self.p...
def pack(self, parts=None, headers=None)
Packs components into a JWT :param parts: List of parts to pack :param headers: The JWT headers :return:
4.244497
4.075251
1.04153
_msg = as_unicode(self.part[1]) # If not JSON web token assume JSON if "cty" in self.headers and self.headers["cty"].lower() != "jwt": pass else: try: _msg = json.loads(_msg) except ValueError: pass re...
def payload(self)
Picks out the payload from the different parts of the signed/encrypted JSON Web Token. If the content type is said to be 'jwt' deserialize the payload into a Python object otherwise return as-is. :return: The payload
6.95435
5.446902
1.276753
if isinstance(val, list): if self.headers[key] in val: return True else: return False else: if self.headers[key] == val: return True else: return False
def verify_header(self, key, val)
Check that a particular header claim is present and has a specific value :param key: The claim :param val: The value of the claim :raises: KeyError if the claim is not present in the header :return: True if the claim exists in the header and has the prescribed value
2.356021
2.127734
1.107291
for key, val in kwargs.items(): try: _ok = self.verify_header(key, val) except KeyError: if check_presence: return False else: pass else: if not _ok: ...
def verify_headers(self, check_presence=True, **kwargs)
Check that a set of particular header claim are present and has specific values :param kwargs: The claim/value sets as a dictionary :return: True if the claim that appears in the header has the prescribed values. If a claim is not present in the header and check_presence...
2.821946
2.994569
0.942355
h = hmac.HMAC(key, self.algorithm(), default_backend()) h.update(msg) return h.finalize()
def sign(self, msg, key)
Create a signature over a message as defined in RFC7515 using a symmetric key :param msg: The message :param key: The key :return: A signature
3.624155
4.986012
0.726864
try: h = hmac.HMAC(key, self.algorithm(), default_backend()) h.update(msg) h.verify(sig) return True except: return False
def verify(self, msg, sig, key)
Verifies whether sig is the correct message authentication code of data. :param msg: The data :param sig: The message authentication code to verify against data. :param key: The key to use :return: Returns true if the mac was valid otherwise it will raise an Exception.
3.039654
3.0439
0.998605
parser = argparse.ArgumentParser(description='JSON Web Key (JWK) Generator') parser.add_argument('--kty', dest='kty', metavar='type', help='Key type', required=True) parser.add_argument('--size', ...
def main()
Main function
1.901134
1.902822
0.999113
provided = frozenset(jwk_dict.keys()) if private is not None and private: required = EC_PUBLIC_REQUIRED | EC_PRIVATE_REQUIRED else: required = EC_PUBLIC_REQUIRED return ensure_params('EC', provided, required)
def ensure_ec_params(jwk_dict, private)
Ensure all required EC parameters are present in dictionary
4.289735
4.100015
1.046273
provided = frozenset(jwk_dict.keys()) if private is not None and private: required = RSA_PUBLIC_REQUIRED | RSA_PRIVATE_REQUIRED else: required = RSA_PUBLIC_REQUIRED return ensure_params('RSA', provided, required)
def ensure_rsa_params(jwk_dict, private)
Ensure all required RSA parameters are present in dictionary
4.474551
4.195601
1.066486
if not required <= provided: missing = required - provided raise MissingValue('Missing properties for kty={}, {}'.format(kty, str(list(missing))))
def ensure_params(kty, provided, required)
Ensure all required parameters are present in dictionary
8.07702
7.602066
1.062477
if isinstance(key, rsa.RSAPublicKey) or isinstance(key, rsa.RSAPrivateKey): kspec = RSAKey(use=use, kid=kid).load_key(key) elif isinstance(key, str): kspec = SYMKey(key=key, use=use, kid=kid) elif isinstance(key, ec.EllipticCurvePublicKey): kspec = ECKey(use=use, kid=kid).load_k...
def jwk_wrap(key, use="", kid="")
Instantiate a Key instance with the given key :param key: The keys to wrap :param use: What the key are expected to be use for :param kid: A key id :return: The Key instance
2.358998
2.5124
0.938942
if keyjar is None: keyjar = KeyJar() tot_kb = build_key_bundle(key_conf, kid_template) keyjar.add_kb(owner, tot_kb) return keyjar
def build_keyjar(key_conf, kid_template="", keyjar=None, owner='')
Builds a :py:class:`oidcmsg.key_jar.KeyJar` instance or adds keys to an existing KeyJar based on a key specification. An example of such a specification:: keys = [ {"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]}, {"type": "EC", "crv": "P-256", "use": ["sig"...
3.471442
4.560318
0.761228
for iss, kbl in keyjar.items(): for kb in kbl: kb.update()
def update_keyjar(keyjar)
Go through the whole key jar, key bundle by key bundle and update them one by one. :param keyjar: The key jar to update
9.122293
12.39145
0.736176
try: kbl = keyjar[issuer] except KeyError: return '' else: key_list = [] for kb in kbl: for key in kb.keys(): if key.inactive_since: key_list.append( '*{}:{}:{}'.format(key.kty, key.use, key.kid)) ...
def key_summary(keyjar, issuer)
Return a text representation of the keyjar. :param keyjar: A :py:class:`oidcmsg.key_jar.KeyJar` instance :param issuer: Which key owner that we are looking at :return: A text representation of the keys
2.980742
2.90664
1.025494
if not url: raise KeyError("No url given") if "/localhost:" in url or "/localhost/" in url: kb = self.keybundle_cls(source=url, verify_ssl=False, httpc=self.httpc, **kwargs) else: kb = self.keybundle_cls(source=ur...
def add_url(self, issuer, url, **kwargs)
Add a set of keys by url. This method will create a :py:class:`oidcmsg.key_bundle.KeyBundle` instance with the url as source specification. If no file format is given it's assumed that what's on the other side is a JWKS. :param issuer: Who issued the keys :param url: Wh...
3.866093
2.992986
1.291718
if issuer not in self.issuer_keys: self.issuer_keys[issuer] = [] if usage is None: self.issuer_keys[issuer].append( self.keybundle_cls([{"kty": "oct", "key": key}])) else: for use in usage: self.issuer_keys[issuer].app...
def add_symmetric(self, issuer, key, usage=None)
Add a symmetric key. This is done by wrapping it in a key bundle cloak since KeyJar does not handle keys directly but only through key bundles. :param issuer: Owner of the key :param key: The key :param usage: What the key can be used for signing/signature ...
2.445776
2.409992
1.014848
try: self.issuer_keys[issuer].append(kb) except KeyError: self.issuer_keys[issuer] = [kb]
def add_kb(self, issuer, kb)
Add a key bundle and bind it to an identifier :param issuer: Owner of the keys in the key bundle :param kb: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance
2.678459
2.755965
0.971877
if key_use in ["dec", "enc"]: use = "enc" else: use = "sig" _kj = None if owner != "": try: _kj = self.issuer_keys[owner] except KeyError: if owner.endswith("/"): try: ...
def get(self, key_use, key_type="", owner="", kid=None, **kwargs)
Get all keys that matches a set of search criteria :param key_use: A key useful for this usage (enc, dec, sig, ver) :param key_type: Type of key (rsa, ec, oct, ..) :param owner: Who is the owner of the keys, "" == me (default) :param kid: A Key Identifier :return: A possibly emp...
3.071672
2.938896
1.045179
return self.get("sig", key_type, owner, kid, **kwargs)
def get_signing_key(self, key_type="", owner="", kid=None, **kwargs)
Shortcut to use for signing keys only. :param key_type: Type of key (rsa, ec, oct, ..) :param owner: Who is the owner of the keys, "" == me (default) :param kid: A Key Identifier :param kwargs: Extra key word arguments :return: A possibly empty list of keys
6.502878
9.433654
0.689328
if usage in ["sig", "ver"]: ktype = jws_alg2keytype(alg) else: ktype = jwe_alg2keytype(alg) return self.get(usage, ktype, issuer)
def keys_by_alg_and_usage(self, issuer, alg, usage)
Find all keys that can be used for a specific crypto algorithm and usage by key owner. :param issuer: Key owner :param alg: a crypto algorithm :param usage: What the key should be used for :return: A possibly empty list of keys
4.700485
6.713624
0.700141
res = [] for kbl in self.issuer_keys[issuer]: res.extend(kbl.keys()) return res
def get_issuer_keys(self, issuer)
Get all the keys that belong to an entity. :param issuer: The entity ID :return: A possibly empty list of keys
5.433113
6.759787
0.80374
for owner in self.issuer_keys.keys(): if owner.startswith(url): return owner raise KeyError("No keys for '{}' in this keyjar".format(url))
def match_owner(self, url)
Finds the first entity, with keys in the key jar, with an identifier that matches the given URL. The match is a leading substring match. :param url: A URL :return: An issue entity ID that exists in the Key jar
9.267327
8.152917
1.136689
logger.debug("Initiating key bundle for issuer: %s" % issuer) if replace or issuer not in self.issuer_keys: self.issuer_keys[issuer] = [] if jwks_uri: self.add_url(issuer, jwks_uri) elif jwks: # jwks should only be considered if no jwks_uri...
def load_keys(self, issuer, jwks_uri='', jwks=None, replace=False)
Fetch keys from another server :param jwks_uri: A URL pointing to a site that will return a JWKS :param jwks: A dictionary representation of a JWKS :param issuer: The provider URL :param replace: If all previously gathered keys from this provider should be replace. :...
3.722389
3.975529
0.936326
try: for kb in self.issuer_keys[issuer]: if kb.source == source: return kb except KeyError: return None return None
def find(self, source, issuer)
Find a key bundle based on the source of the keys :param source: A source url :param issuer: The issuer of keys :return: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance or None
4.497743
3.828118
1.174923
keys = [] for kb in self.issuer_keys[issuer]: keys.extend([k.serialize(private) for k in kb.keys() if k.inactive_since == 0]) return {"keys": keys}
def export_jwks(self, private=False, issuer="")
Produces a dictionary that later can be easily mapped into a JSON string representing a JWKS. :param private: Whether it should be the private keys or the public :param issuer: The entity ID. :return: A dictionary with one key: 'keys'
6.606859
7.568307
0.872964
return json.dumps(self.export_jwks(private, issuer))
def export_jwks_as_json(self, private=False, issuer="")
Export a JWKS as a JSON document. :param private: Whether it should be the private keys or the public :param issuer: The entity ID. :return: A JSON representation of a JWKS
4.544883
6.689253
0.679431
try: _keys = jwks["keys"] except KeyError: raise ValueError('Not a proper JWKS') else: try: self.issuer_keys[issuer].append( self.keybundle_cls(_keys, verify_ssl=self.verify_ssl)) except KeyError: ...
def import_jwks(self, jwks, issuer)
Imports all the keys that are represented in a JWKS :param jwks: Dictionary representation of a JWKS :param issuer: Who 'owns' the JWKS
3.033484
3.201476
0.947527
return self.import_jwks(json.loads(jwks), issuer)
def import_jwks_as_json(self, jwks, issuer)
Imports all the keys that are represented in a JWKS expressed as a JSON object :param jwks: JSON representation of a JWKS :param issuer: Who 'owns' the JWKS
4.050263
6.583095
0.615252
for iss in list(self.owners()): _kbl = [] for kb in self.issuer_keys[iss]: kb.remove_outdated(self.remove_after, when=when) if len(kb): _kbl.append(kb) if _kbl: self.issuer_keys[iss] = _kbl ...
def remove_outdated(self, when=0)
Goes through the complete list of issuers and for each of them removes outdated keys. Outdated keys are keys that has been marked as inactive at a time that is longer ago then some set number of seconds (when). If when=0 the the base time is set to now. The number of seconds a ca...
4.452516
4.402082
1.011457
try: _key_type = jwe_alg2keytype(jwt.headers['alg']) except KeyError: _key_type = '' try: _kid = jwt.headers['kid'] except KeyError: logger.info('Missing kid') _kid = '' keys = self.get(key_use='enc', owner='...
def get_jwt_decrypt_keys(self, jwt, **kwargs)
Get decryption keys from this keyjar based on information carried in a JWE. These keys should be usable to decrypt an encrypted JWT. :param jwt: A cryptojwt.jwt.JWT instance :param kwargs: Other key word arguments :return: list of usable keys
3.840777
3.613256
1.062969
try: allow_missing_kid = kwargs['allow_missing_kid'] except KeyError: allow_missing_kid = False try: _key_type = jws_alg2keytype(jwt.headers['alg']) except KeyError: _key_type = '' try: _kid = jwt.headers['ki...
def get_jwt_verify_keys(self, jwt, **kwargs)
Get keys from this key jar based on information in a JWS. These keys should be usable to verify the signed JWT. :param jwt: A cryptojwt.jwt.JWT instance :param kwargs: Other key word arguments :return: list of usable keys
4.153517
3.978692
1.04394
kj = KeyJar() for issuer in self.owners(): kj[issuer] = [kb.copy() for kb in self[issuer]] kj.verify_ssl = self.verify_ssl return kj
def copy(self)
Make deep copy of this key jar. :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
6.476182
5.252692
1.232926
res = [] if not key_type: if use == 'sig': key_type = jws_alg2keytype(alg) else: key_type = jwe_alg2keytype(alg) for key in keys: if key.use and key.use != use: continue if key.kty == key_type: if key.kid and kid: ...
def pick_key(keys, use, alg='', key_type='', kid='')
Based on given criteria pick out the keys that fulfill them from a given set of keys. :param keys: List of keys. These are :py:class:`cryptojwt.jwk.JWK` instances. :param use: What the key is going to be used for 'sig'/'enc' :param alg: crypto algorithm :param key_type: Type of key 'rsa'/'e...
2.284404
2.345074
0.974129
argv = {'iss': self.iss, 'iat': utc_time_sans_frac()} if self.lifetime: argv['exp'] = argv['iat'] + self.lifetime _aud = self.put_together_aud(recv, aud) if _aud: argv['aud'] = _aud return argv
def pack_init(self, recv, aud)
Gather initial information for the payload. :return: A dictionary with claims and values
5.393167
5.59275
0.964314