code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
keys = pick_key(self.my_keys(owner_id, 'sig'), 'sig', alg=self.alg, kid=kid) if not keys: raise NoSuitableSigningKeys('kid={}'.format(kid)) return keys[0]
def pack_key(self, owner_id='', kid='')
Find a key to be used for signing the Json Web Token :param owner_id: Owner of the keys to chose from :param kid: Key ID :return: One key
8.452515
8.671718
0.974722
keys = self.key_jar.get_jwt_verify_keys(rj.jwt) return rj.verify_compact(token, keys)
def _verify(self, rj, token)
Verify a signed JSON Web Token :param rj: A :py:class:`cryptojwt.jws.JWS` instance :param token: The signed JSON Web Token :return: A verified message
9.384644
7.201982
1.303064
if self.iss: keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt, aud=self.iss) else: keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt) return rj.decrypt(token, keys=keys)
def _decrypt(self, rj, token)
Decrypt an encrypted JsonWebToken :param rj: :py:class:`cryptojwt.jwe.JWE` instance :param token: The encrypted JsonWebToken :return:
4.127586
4.048976
1.019415
_msg = msg_cls(**info) if not _msg.verify(**kwargs): raise VerificationError() return _msg
def verify_profile(msg_cls, info, **kwargs)
If a message type is known for this JSON document. Verify that the document complies with the message specifications. :param msg_cls: The message class. A :py:class:`oidcmsg.message.Message` instance :param info: The information in the JSON document as a dictionary :param kwargs: Extra keyword arguments used when doing the verification. :return: The verified message as a msg_cls instance.
4.879199
5.024755
0.971032
if not token: raise KeyError _jwe_header = _jws_header = None # Check if it's an encrypted JWT darg = {} if self.allowed_enc_encs: darg['enc'] = self.allowed_enc_encs if self.allowed_enc_algs: darg['alg'] = self.allowed_enc_algs try: _decryptor = jwe_factory(token, **darg) except (KeyError, HeaderError): _decryptor = None if _decryptor: # Yes, try to decode _info = self._decrypt(_decryptor, token) _jwe_header = _decryptor.jwt.headers # Try to find out if the information encrypted was a signed JWT try: _content_type = _decryptor.jwt.headers['cty'] except KeyError: _content_type = '' else: _content_type = 'jwt' _info = token # If I have reason to believe the information I have is a signed JWT if _content_type.lower() == 'jwt': # Check that is a signed JWT if self.allowed_sign_algs: _verifier = jws_factory(_info, alg=self.allowed_sign_algs) else: _verifier = jws_factory(_info) if _verifier: _info = self._verify(_verifier, _info) else: raise Exception() _jws_header = _verifier.jwt.headers else: # So, not a signed JWT try: # A JSON document ? _info = json.loads(_info) except JSONDecodeError: # Oh, no ! Not JSON return _info except TypeError: try: _info = as_unicode(_info) _info = json.loads(_info) except JSONDecodeError: # Oh, no ! Not JSON return _info # If I know what message class the info should be mapped into if self.msg_cls: _msg_cls = self.msg_cls else: try: # try to find a issuer specific message class _msg_cls = self.iss2msg_cls[_info['iss']] except KeyError: _msg_cls = None if _msg_cls: vp_args = {'skew': self.skew} if self.iss: vp_args['aud'] = self.iss _info = self.verify_profile(_msg_cls, _info, **vp_args) _info.jwe_header = _jwe_header _info.jws_header = _jws_header return _info else: return _info
def unpack(self, token)
Unpack a received signed or signed and encrypted Json Web Token :param token: The Json Web Token :return: If decryption and signature verification work the payload will be returned as a Message instance if possible.
3.357651
3.294251
1.019246
_jw = JWS(alg=alg) if _jw.is_jws(token): return _jw else: return None
def factory(token, alg='')
Instantiate an JWS instance if the token is a signed JWT. :param token: The token that might be a signed JWT :param alg: The expected signature algorithm :return: A JWS instance if the token was a signed JWT, otherwise None
5.50936
4.352625
1.265756
_headers = self._header _headers.update(kwargs) key, xargs, _alg = self.alg_keys(keys, 'sig', protected) if "typ" in self: xargs["typ"] = self["typ"] _headers.update(xargs) jwt = JWSig(**_headers) if _alg == "none": return jwt.pack(parts=[self.msg, ""]) # All other cases try: _signer = SIGNER_ALGS[_alg] except KeyError: raise UnknownAlgorithm(_alg) _input = jwt.pack(parts=[self.msg]) if isinstance(key, AsymmetricKey): sig = _signer.sign(_input.encode("utf-8"), key.private_key()) else: sig = _signer.sign(_input.encode("utf-8"), key.key) logger.debug("Signed message using key with kid=%s" % key.kid) return ".".join([_input, b64encode_item(sig).decode("utf-8")])
def sign_compact(self, keys=None, protected=None, **kwargs)
Produce a JWS using the JWS Compact Serialization :param keys: A dictionary of keys :param protected: The protected headers (a dictionary) :param kwargs: claims you want to add to the standard headers :return: A signed JSON Web Token
5.052679
5.033079
1.003894
return self.verify_compact_verbose(jws, keys, allow_none, sigalg)['msg']
def verify_compact(self, jws=None, keys=None, allow_none=False, sigalg=None)
Verify a JWT signature :param jws: A signed JSON Web Token :param keys: A list of keys that can possibly be used to verify the signature :param allow_none: If signature algorithm 'none' is allowed :param sigalg: Expected sigalg :return: Dictionary with 2 keys 'msg' required, 'key' optional
6.570881
7.724743
0.850628
if jws: jwt = JWSig().unpack(jws) if len(jwt) != 3: raise WrongNumberOfParts(len(jwt)) self.jwt = jwt elif not self.jwt: raise ValueError('Missing singed JWT') else: jwt = self.jwt try: _alg = jwt.headers["alg"] except KeyError: _alg = None else: if _alg is None or _alg.lower() == "none": if allow_none: self.msg = jwt.payload() return {'msg': self.msg} else: raise SignerAlgError("none not allowed") if "alg" in self and self['alg'] and _alg: if isinstance(self['alg'], list): if _alg not in self["alg"] : raise SignerAlgError( "Wrong signing algorithm, expected {} got {}".format( self['alg'], _alg)) elif _alg != self['alg']: raise SignerAlgError( "Wrong signing algorithm, expected {} got {}".format( self['alg'], _alg)) if sigalg and sigalg != _alg: raise SignerAlgError("Expected {0} got {1}".format( sigalg, jwt.headers["alg"])) self["alg"] = _alg if keys: _keys = self.pick_keys(keys) else: _keys = self.pick_keys(self._get_keys()) if not _keys: if "kid" in self: raise NoSuitableSigningKeys( "No key with kid: %s" % (self["kid"])) elif "kid" in self.jwt.headers: raise NoSuitableSigningKeys( "No key with kid: %s" % (self.jwt.headers["kid"])) else: raise NoSuitableSigningKeys("No key for algorithm: %s" % _alg) verifier = SIGNER_ALGS[_alg] for key in _keys: if isinstance(key, AsymmetricKey): _key = key.public_key() else: _key = key.key try: if not verifier.verify(jwt.sign_input(), jwt.signature(), _key): continue except (BadSignature, IndexError): pass except (ValueError, TypeError) as err: logger.warning('Exception "{}" caught'.format(err)) else: logger.debug( "Verified message using key with kid=%s" % key.kid) self.msg = jwt.payload() self.key = key return {'msg': self.msg, 'key': key} raise BadSignature()
def verify_compact_verbose(self, jws=None, keys=None, allow_none=False, sigalg=None)
Verify a JWT signature and return dict with validation results :param jws: A signed JSON Web Token :param keys: A list of keys that can possibly be used to verify the signature :param allow_none: If signature algorithm 'none' is allowed :param sigalg: Expected sigalg :return: Dictionary with 2 keys 'msg' required, 'key' optional. The value of 'msg' is the unpacked and verified message. The value of 'key' is the key used to verify the message
2.844672
2.780296
1.023155
def create_signature(protected, unprotected): protected_headers = protected or {} # always protect the signing alg header protected_headers.setdefault("alg", self.alg) _jws = JWS(self.msg, **protected_headers) encoded_header, payload, signature = _jws.sign_compact( protected=protected, keys=keys).split(".") signature_entry = {"signature": signature} if unprotected: signature_entry["header"] = unprotected if encoded_header: signature_entry["protected"] = encoded_header return signature_entry res = {"payload": b64e_enc_dec(self.msg, "utf-8", "ascii")} if headers is None: headers = [(dict(alg=self.alg), None)] if flatten and len( headers) == 1: # Flattened JWS JSON Serialization Syntax signature_entry = create_signature(*headers[0]) res.update(signature_entry) else: res["signatures"] = [] for protected, unprotected in headers: signature_entry = create_signature(protected, unprotected) res["signatures"].append(signature_entry) return json.dumps(res)
def sign_json(self, keys=None, headers=None, flatten=False)
Produce JWS using the JWS JSON Serialization :param keys: list of keys to use for signing the JWS :param headers: list of tuples (protected headers, unprotected headers) for each signature :return: A signed message using the JSON serialization format.
3.992627
3.608747
1.106375
json_ser_keys = {"payload", "signatures"} flattened_json_ser_keys = {"payload", "signature"} if not json_ser_keys.issubset( json_jws.keys()) and not flattened_json_ser_keys.issubset( json_jws.keys()): return False return True
def _is_json_serialized_jws(self, json_jws)
Check if we've got a JSON serialized signed JWT. :param json_jws: The message :return: True/False
3.251415
3.62325
0.897375
try: jwt = JWSig().unpack(jws) except Exception as err: logger.warning('Could not parse JWS: {}'.format(err)) return False if "alg" not in jwt.headers: return False if jwt.headers["alg"] is None: jwt.headers["alg"] = "none" if jwt.headers["alg"] not in SIGNER_ALGS: logger.debug("UnknownSignerAlg: %s" % jwt.headers["alg"]) return False self.jwt = jwt return True
def _is_compact_jws(self, jws)
Check if we've got a compact signed JWT :param jws: The message :return: True/False
3.603338
3.50829
1.027092
try: _use = USE[usage] except: raise ValueError('Unknown key usage') else: if not self.use or self.use == _use: if _use == 'sig': return self.get_key() else: return self.encryption_key(alg) raise WrongUsage("This key can't be used for {}".format(usage))
def appropriate_for(self, usage, alg='HS256')
Make sure there is a key instance present that can be used for the specified usage.
5.378983
4.943982
1.087986
if not self.key: self.deserialize() try: tsize = ALG2KEYLEN[alg] except KeyError: raise UnsupportedAlgorithm(alg) if tsize <= 32: # SHA256 _enc_key = sha256_digest(self.key)[:tsize] elif tsize <= 48: # SHA384 _enc_key = sha384_digest(self.key)[:tsize] elif tsize <= 64: # SHA512 _enc_key = sha512_digest(self.key)[:tsize] else: raise JWKException("No support for symmetric keys > 512 bits") logger.debug('Symmetric encryption key: {}'.format( as_unicode(b64e(_enc_key)))) return _enc_key
def encryption_key(self, alg, **kwargs)
Return an encryption key as per http://openid.net/specs/openid-connect-core-1_0.html#Encryption :param alg: encryption algorithm :param kwargs: :return: encryption key as byte string
2.7855
2.770537
1.005401
if not isinstance(key, rsa.RSAPrivateKey): raise TypeError( "The key must be an instance of rsa.RSAPrivateKey") sig = key.sign(msg, self.padding, self.hash) return sig
def sign(self, msg, key)
Create a signature over a message as defined in RFC7515 using an RSA key :param msg: the message. :type msg: bytes :returns: bytes, the signature of data. :rtype: bytes
3.32879
2.971962
1.120065
if not isinstance(key, rsa.RSAPublicKey): raise TypeError( "The public key must be an instance of RSAPublicKey") try: key.verify(signature, msg, self.padding, self.hash) except InvalidSignature as err: raise BadSignature(str(err)) except AttributeError: return False else: return True
def verify(self, msg, signature, key)
Verifies whether signature is a valid signature for message :param msg: the message :type msg: bytes :param signature: The signature to be verified :type signature: bytes :param key: The key :return: True is the signature is valid otherwise False
3.216663
3.064919
1.04951
try: _use = USE[usage] except KeyError: raise ValueError('Unknown key usage') else: if usage in ['sign', 'decrypt']: if not self.use or _use == self.use: if self.priv_key: return self.priv_key return None else: # has to be one of ['encrypt', 'verify'] if not self.use or _use == self.use: if self.pub_key: return self.pub_key return None
def appropriate_for(self, usage, **kwargs)
Make sure there is a key instance present that can be used for the specified usage. :param usage: Usage specification, one of [sign, verify, decrypt, encrypt] :param kwargs: Extra keyword arguments :return: Suitable key or None
3.86856
3.211443
1.204617
private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_size, backend=default_backend()) with open(filename, "wb") as keyfile: if passphrase: pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption( passphrase)) else: pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()) keyfile.write(pem) keyfile.close() return private_key
def generate_and_store_rsa_key(key_size=2048, filename='rsa.key', passphrase='')
Generate a private RSA key and store a PEM representation of it in a file. :param key_size: The size of the key, default 2048 bytes. :param filename: The name of the file to which the key should be written :param passphrase: If the PEM representation should be protected with a pass phrase. :return: A cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey instance
1.462842
1.529769
0.95625
with open(filename, "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) return public_key
def import_public_rsa_key_from_file(filename)
Read a public RSA 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.rsa.RSAPublicKey instance
1.690659
2.55251
0.662352
if not pem_data.startswith(PREFIX): pem_data = bytes('{}\n{}\n{}'.format(PREFIX, pem_data, POSTFIX), 'utf-8') else: pem_data = bytes(pem_data, 'utf-8') cert = x509.load_pem_x509_certificate(pem_data, default_backend()) return cert.public_key()
def import_rsa_key(pem_data)
Extract an RSA key from a PEM-encoded X.509 certificate :param pem_data: RSA key encoded in standard form :return: rsa.RSAPublicKey instance
2.358304
2.662138
0.885868
pn1 = key1.public_numbers() pn2 = key2.public_numbers() # Check if two RSA keys are in fact the same if pn1 == pn2: return True else: return False
def rsa_eq(key1, key2)
Only works for RSAPublic Keys :param key1: :param key2: :return:
3.598326
3.877238
0.928064
pub_key = import_rsa_key(txt) if isinstance(pub_key, rsa.RSAPublicKey): return [("rsa", pub_key)]
def x509_rsa_load(txt)
So I get the same output format as loads produces :param txt: :return:
4.067739
5.263881
0.772764
if isinstance(der_data, str): der_data = bytes(der_data, 'utf-8') return x509.load_der_x509_certificate(der_data, default_backend())
def der_cert(der_data)
Load a DER encoded certificate :param der_data: DER-encoded certificate :return: A cryptography.x509.certificate instance
1.779066
2.186212
0.813766
try: r = httpc('GET', url, allow_redirects=True, **get_args) if r.status_code == 200: cert = str(r.text) try: public_key = spec2key[cert] # If I've already seen it except KeyError: public_key = import_rsa_key(cert) spec2key[cert] = public_key if isinstance(public_key, rsa.RSAPublicKey): return {"rsa": public_key} else: raise Exception("HTTP Get error: %s" % r.status_code) except Exception as err: # not a RSA key logger.warning("Can't load key: %s" % err) return []
def load_x509_cert(url, httpc, spec2key, **get_args)
Get and transform a X509 cert into a key. :param url: Where the X509 cert can be found :param httpc: HTTP client to use for fetching :param spec2key: A dictionary over keys already seen :param get_args: Extra key word arguments to the HTTP GET request :return: List of 2-tuples (keytype, key)
3.196756
3.142534
1.017254
if pn1.n == pn2.n: if pn1.e == pn2.e: return True return False
def cmp_public_numbers(pn1, pn2)
Compare 2 sets of public numbers. These is a way to compare 2 public RSA keys. If the sets are the same then the keys are the same. :param pn1: The set of values belonging to the 1st key :param pn2: The set of values belonging to the 2nd key :return: True is the sets are the same otherwise False.
2.514285
3.077358
0.817027
if not cmp_public_numbers(pn1.public_numbers, pn2.public_numbers): return False for param in ['d', 'p', 'q']: if getattr(pn1, param) != getattr(pn2, param): return False return True
def cmp_private_numbers(pn1, pn2)
Compare 2 sets of private numbers. This is for comparing 2 private RSA keys. :param pn1: The set of values belonging to the 1st key :param pn2: The set of values belonging to the 2nd key :return: True is the sets are the same otherwise False.
2.676566
3.204027
0.835375
if isinstance(cert, str): der_cert = base64.b64decode(cert.encode('ascii')) else: der_cert = base64.b64decode(cert) return b64e(hashlib.sha1(der_cert).digest())
def x5t_calculation(cert)
base64url-encoded SHA-1 thumbprint (a.k.a. digest) of the DER encoding of an X.509 certificate. :param cert: DER encoded X.509 certificate :return: x5t value
2.27204
2.520802
0.901316
_key = rsa.generate_private_key(public_exponent=public_exponent, key_size=key_size, backend=default_backend()) _rk = RSAKey(priv_key=_key, use=use, kid=kid) if not kid: _rk.add_kid() return _rk
def new_rsa_key(key_size=2048, kid='', use='', public_exponent=65537)
Creates a new RSA key pair and wraps it in a :py:class:`cryptojwt.jwk.rsa.RSAKey` instance :param key_size: The size of the key :param kid: The key ID :param use: What the is supposed to be used for. 2 choices 'sig'/'enc' :param public_exponent: The value of the public exponent. :return: A :py:class:`cryptojwt.jwk.rsa.RSAKey` instance
2.90899
3.373754
0.862241
# first look for the public parts of a RSA key if self.n and self.e: try: numbers = {} # loop over all the parameters that define a RSA key for param in self.longs: item = getattr(self, param) if not item: continue else: try: val = int(deser(item)) except Exception: raise else: numbers[param] = val if 'd' in numbers: self.priv_key = rsa_construct_private(numbers) self.pub_key = self.priv_key.public_key() else: self.pub_key = rsa_construct_public(numbers) except ValueError as err: raise DeSerializationNotPossible("%s" % err) if self.x5c: _cert_chain = [] for der_data in self.x5c: _cert_chain.append(der_cert(base64.b64decode(der_data))) if self.x5t: # verify the cert thumbprint if isinstance(self.x5t, bytes): _x5t = self.x5t else: _x5t = self.x5t.encode('ascii') if _x5t != x5t_calculation(self.x5c[0]): raise DeSerializationNotPossible( "The thumbprint 'x5t' does not match the certificate.") if self.pub_key: if not rsa_eq(self.pub_key, _cert_chain[0].public_key()): raise ValueError( 'key described by components and key in x5c not equal') else: self.pub_key = _cert_chain[0].public_key() self._serialize(self.pub_key) if len(self.x5c) > 1: # verify chain pass if not self.priv_key and not self.pub_key: raise DeSerializationNotPossible()
def deserialize(self)
Based on a text based representation of an RSA key this method instantiates a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or RSAPublicKey instance
3.555617
3.463313
1.026652
if not self.priv_key and not self.pub_key: raise SerializationNotPossible() res = self.common() public_longs = list(set(self.public_members) & set(self.longs)) for param in public_longs: item = getattr(self, param) if item: res[param] = item if private: for param in self.longs: if not private and param in ["d", "p", "q", "dp", "dq", "di", "qi"]: continue item = getattr(self, param) if item: res[param] = item if self.x5c: res['x5c'] = [x.decode('utf-8') for x in self.x5c] return res
def serialize(self, private=False)
Given a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or RSAPublicKey instance construct the JWK representation. :param private: Should I do the private part or not :return: A JWK as a dictionary
3.588255
3.371494
1.064292
self._serialize(key) if isinstance(key, rsa.RSAPrivateKey): self.priv_key = key self.pub_key = key.public_key() else: self.pub_key = key return self
def load_key(self, key)
Load a RSA key. Try to serialize the key before binding it to this instance. :param key: An RSA key instance
3.480872
3.172585
1.097172
if not isinstance(key, ec.EllipticCurvePrivateKey): raise TypeError( "The private key must be an instance of " "ec.EllipticCurvePrivateKey") self._cross_check(key.public_key()) num_bits = key.curve.key_size num_bytes = (num_bits + 7) // 8 asn1sig = key.sign(msg, ec.ECDSA(self.hash_algorithm())) # Cryptography returns ASN.1-encoded signature data; decode as JWS # uses raw signatures (r||s) (r, s) = decode_dss_signature(asn1sig) return int_to_bytes(r, num_bytes) + int_to_bytes(s, num_bytes)
def sign(self, msg, key)
Create a signature over a message as defined in RFC7515 using an Elliptic curve key :param msg: The message :param key: An ec.EllipticCurvePrivateKey instance :return:
3.770258
3.804157
0.991089
if not isinstance(key, ec.EllipticCurvePublicKey): raise TypeError( "The public key must be an instance of " "ec.EllipticCurvePublicKey") self._cross_check(key) num_bits = key.curve.key_size num_bytes = (num_bits + 7) // 8 if len(sig) != 2 * num_bytes: raise ValueError('Invalid signature') try: # cryptography uses ASN.1-encoded signature data; split JWS # signature (r||s) and encode before verification (r, s) = self._split_raw_signature(sig) asn1sig = encode_dss_signature(r, s) key.verify(asn1sig, msg, ec.ECDSA(self.hash_algorithm())) except InvalidSignature as err: raise BadSignature(err) else: return True
def verify(self, msg, sig, 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
3.873288
3.897993
0.993662
if self.curve_name != pub_key.curve.name: raise ValueError( "The curve in private key {} and in algorithm {} don't " "match".format(pub_key.curve.name, self.curve_name))
def _cross_check(self, pub_key)
In Ecdsa, both the key and the algorithm define the curve. Therefore, we must cross check them to make sure they're the same. :param key: :raises: ValueError is the curves are not the same
4.014726
3.494124
1.148994
c_length = len(sig) // 2 r = int_from_bytes(sig[:c_length], byteorder='big') s = int_from_bytes(sig[c_length:], byteorder='big') return r, s
def _split_raw_signature(sig)
Split raw signature into components :param sig: The signature :return: A 2-tuple
2.694719
2.972116
0.906667
if func == 'HS256': return as_unicode(b64e(sha256_digest(msg)[:16])) elif func == 'HS384': return as_unicode(b64e(sha384_digest(msg)[:24])) elif func == 'HS512': return as_unicode(b64e(sha512_digest(msg)[:32]))
def left_hash(msg, func="HS256")
Calculate left hash as described in https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken for at_hash and in for c_hash :param msg: The message over which the hash should be calculated :param func: Which hash function that was used for the ID token
1.881977
2.095823
0.897966
if not alg or alg.lower() == "none": return "none" elif alg.startswith("RS") or alg.startswith("PS"): return "RSA" elif alg.startswith("HS") or alg.startswith("A"): return "oct" elif alg.startswith("ES") or alg.startswith("ECDH-ES"): return "EC" else: return None
def alg2keytype(alg)
Go from algorithm name to key type. :param alg: The algorithm name :return: The key type
2.47628
2.799667
0.884491
if algorithm == "RS256": return hashes.SHA256(), padding.PKCS1v15() elif algorithm == "RS384": return hashes.SHA384(), padding.PKCS1v15() elif algorithm == "RS512": return hashes.SHA512(), padding.PKCS1v15() elif algorithm == "PS256": return (hashes.SHA256(), padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH)) elif algorithm == "PS384": return (hashes.SHA384(), padding.PSS( mgf=padding.MGF1(hashes.SHA384()), salt_length=padding.PSS.MAX_LENGTH)) elif algorithm == "PS512": return (hashes.SHA512(), padding.PSS( mgf=padding.MGF1(hashes.SHA512()), salt_length=padding.PSS.MAX_LENGTH)) else: raise UnsupportedAlgorithm("Unknown algorithm: {}".format(algorithm))
def parse_rsa_algorithm(algorithm)
Parses a RSA algorithm and returns tuple (hash, padding). :param algorithm: string, RSA algorithm as defined at https://tools.ietf.org/html/rfc7518#section-3.1. :raises: UnsupportedAlgorithm: if the algorithm is not supported. :returns: (hash, padding) tuple.
1.324036
1.274183
1.039126
# Compute shared secret shared_key = key.exchange(ec.ECDH(), epk) # Derive the key # AlgorithmID || PartyUInfo || PartyVInfo || SuppPubInfo otherInfo = bytes(alg) + \ struct.pack("!I", len(apu)) + apu + \ struct.pack("!I", len(apv)) + apv + \ struct.pack("!I", dk_len) return concat_sha256(shared_key, dk_len, otherInfo)
def ecdh_derive_key(key, epk, apu, apv, alg, dk_len)
ECDH key derivation, as defined by JWA :param key : Elliptic curve private key :param epk : Elliptic curve public key :param apu : PartyUInfo :param apv : PartyVInfo :param alg : Algorithm identifier :param dk_len: Length of key to be derived, in bits :return: The derived key
3.762017
3.671627
1.024619
_msg = as_bytes(self.msg) _args = self._dict try: _args["kid"] = kwargs["kid"] except KeyError: pass if 'params' in kwargs: if 'apu' in kwargs['params']: _args['apu'] = kwargs['params']['apu'] if 'apv' in kwargs['params']: _args['apv'] = kwargs['params']['apv'] if 'epk' in kwargs['params']: _args['epk'] = kwargs['params']['epk'] jwe = JWEnc(**_args) ctxt, tag, cek = super(JWE_EC, self).enc_setup( self["enc"], _msg, auth_data=jwe.b64_encode_header(), key=cek, iv=iv) if 'encrypted_key' in kwargs: return jwe.pack(parts=[kwargs['encrypted_key'], iv, ctxt, tag]) return jwe.pack(parts=[iv, ctxt, tag])
def encrypt(self, key=None, iv="", cek="", **kwargs)
Produces a JWE as defined in RFC7516 using an Elliptic curve key :param key: *Not used>, only there to present the same API as JWE_RSA and JWE_SYM :param iv: Initialization vector :param cek: Content master key :param kwargs: Extra keyword arguments :return: An encrypted JWT
3.816313
3.764699
1.01371
_msg = as_bytes(self.msg) if "zip" in self: if self["zip"] == "DEF": _msg = zlib.compress(_msg) else: raise ParameterError("Zip has unknown value: %s" % self["zip"]) kwarg_cek = cek or None _enc = self["enc"] iv = self._generate_iv(_enc, iv) cek = self._generate_key(_enc, cek) self["cek"] = cek logger.debug("cek: %s, iv: %s" % ([c for c in cek], [c for c in iv])) _encrypt = RSAEncrypter(self.with_digest).encrypt _alg = self["alg"] if kwarg_cek: jwe_enc_key = '' elif _alg == "RSA-OAEP": jwe_enc_key = _encrypt(cek, key, 'pkcs1_oaep_padding') elif _alg == "RSA-OAEP-256": jwe_enc_key = _encrypt(cek, key, 'pkcs1_oaep_256_padding') elif _alg == "RSA1_5": jwe_enc_key = _encrypt(cek, key) else: raise NotSupportedAlgorithm(_alg) jwe = JWEnc(**self.headers()) try: _auth_data = kwargs['auth_data'] except KeyError: _auth_data = jwe.b64_encode_header() ctxt, tag, key = self.enc_setup(_enc, _msg, key=cek, iv=iv, auth_data=_auth_data) return jwe.pack(parts=[jwe_enc_key, iv, ctxt, tag])
def encrypt(self, key, iv="", cek="", **kwargs)
Produces a JWE as defined in RFC7516 using RSA algorithms :param key: RSA key :param iv: Initialization vector :param cek: Content master key :param kwargs: Extra keyword arguments :return: A signed payload
3.757559
3.689803
1.018363
if not isinstance(token, JWEnc): jwe = JWEnc().unpack(token) else: jwe = token self.jwt = jwe.encrypted_key() jek = jwe.encrypted_key() _decrypt = RSAEncrypter(self.with_digest).decrypt _alg = jwe.headers["alg"] if cek: pass elif _alg == "RSA-OAEP": cek = _decrypt(jek, key, 'pkcs1_oaep_padding') elif _alg == "RSA-OAEP-256": cek = _decrypt(jek, key, 'pkcs1_oaep_256_padding') elif _alg == "RSA1_5": cek = _decrypt(jek, key) else: raise NotSupportedAlgorithm(_alg) self["cek"] = cek enc = jwe.headers["enc"] if enc not in SUPPORTED["enc"]: raise NotSupportedAlgorithm(enc) auth_data = jwe.b64_protected_header() msg = self._decrypt(enc, cek, jwe.ciphertext(), auth_data=auth_data, iv=jwe.initialization_vector(), tag=jwe.authentication_tag()) if "zip" in jwe.headers and jwe.headers["zip"] == "DEF": msg = zlib.decompress(msg) return msg
def decrypt(self, token, key, cek=None)
Decrypts a JWT :param token: The JWT :param key: A key to use for decrypting :param cek: Ephemeral cipher key :return: The decrypted message
2.933282
3.074564
0.954048
_alg = self["alg"] # Find Usable Keys if keys: keys = self.pick_keys(keys, use="enc") else: keys = self.pick_keys(self._get_keys(), use="enc") if not keys: logger.error(KEY_ERR.format(_alg)) raise NoSuitableEncryptionKey(_alg) # Determine Encryption Class by Algorithm if _alg in ["RSA-OAEP", "RSA-OAEP-256", "RSA1_5"]: encrypter = JWE_RSA(self.msg, **self._dict) elif _alg.startswith("A") and _alg.endswith("KW"): encrypter = JWE_SYM(self.msg, **self._dict) else: # _alg.startswith("ECDH-ES"): encrypter = JWE_EC(**self._dict) cek, encrypted_key, iv, params, eprivk = encrypter.enc_setup( self.msg, key=keys[0], **self._dict) kwargs["encrypted_key"] = encrypted_key kwargs["params"] = params if cek: kwargs["cek"] = cek if iv: kwargs["iv"] = iv for key in keys: if isinstance(key, SYMKey): _key = key.key elif isinstance(key, ECKey): _key = key.public_key() else: # isinstance(key, RSAKey): _key = key.public_key() if key.kid: encrypter["kid"] = key.kid try: token = encrypter.encrypt(key=_key, **kwargs) self["cek"] = encrypter.cek if 'cek' in encrypter else None except TypeError as err: raise err else: logger.debug( "Encrypted message using key with kid={}".format(key.kid)) return token
def encrypt(self, keys=None, cek="", iv="", **kwargs)
Encrypt a payload :param keys: A set of possibly usable keys :param cek: Content master key :param iv: Initialization vector :param kwargs: Extra key word arguments :return: Encrypted message
3.39121
3.395632
0.998698
_data = as_bytes(data) _d = base64.urlsafe_b64decode(_data + b'==') # verify that it's base64url encoded and not just base64 # that is no '+' and '/' characters and not trailing "="s. if [e for e in [b'+', b'/', b'='] if e in _data]: raise ValueError("Not base64url encoded") return intarr2long(struct.unpack('%sB' % len(_d), _d))
def base64url_to_long(data)
Stricter then base64_to_long since it really checks that it's base64url encoded :param data: The base64 string :return:
5.290165
5.556289
0.952104
cb = b.rstrip(b"=") # shouldn't but there you are # Python's base64 functions ignore invalid characters, so we need to # check for them explicitly. if not _b64_re.match(cb): raise BadSyntax(cb, "base64-encoded data contains illegal characters") if cb == b: b = add_padding(b) return base64.urlsafe_b64decode(b)
def b64d(b)
Decode some base64-encoded bytes. Raises BadSyntax if the string contains invalid characters or padding. :param b: bytes
6.846935
6.508676
1.05197
if isinstance(val, str): _val = val.encode("utf-8") else: _val = val return base64_to_long(_val)
def deser(val)
Deserialize from a string representation of an long integer to the python representation of a long integer. :param val: The string representation of the long integer. :return: The long integer.
3.889523
4.777984
0.814051
res = self.serialize(private=True) res.update(self.extra_args) return res
def to_dict(self)
A wrapper for to_dict the makes sure that all the private information as well as extra arguments are included. This method should *not* be used for exporting information about the key. :return: A dictionary representation of the JSON Web key
10.289712
8.266839
1.244697
res = {"kty": self.kty} if self.use: res["use"] = self.use if self.kid: res["kid"] = self.kid if self.alg: res["alg"] = self.alg return res
def common(self)
Return the set of parameters that are common to all types of keys. :return: Dictionary
2.526089
2.687601
0.939905
for param in self.longs: item = getattr(self, param) if not item or isinstance(item, str): continue if isinstance(item, bytes): item = item.decode('utf-8') setattr(self, param, item) try: _ = base64url_to_long(item) except Exception: return False else: if [e for e in ['+', '/', '='] if e in item]: return False if self.kid: if not isinstance(self.kid, str): raise ValueError("kid of wrong value type") return True
def verify(self)
Verify that the information gathered from the on-the-wire representation is of the right type. This is supposed to be run before the info is deserialized. :return: True/False
4.310648
4.404638
0.978661
if members is None: members = self.required members.sort() ser = self.serialize() _se = [] for elem in members: try: _val = ser[elem] except KeyError: # should never happen with the required set pass else: if isinstance(_val, bytes): _val = as_unicode(_val) _se.append('"{}":{}'.format(elem, json.dumps(_val))) _json = '{{{}}}'.format(','.join(_se)) return b64e(DIGEST_HASH[hash_function](_json))
def thumbprint(self, hash_function, members=None)
Create a thumbprint of the key following the outline in https://tools.ietf.org/html/draft-jones-jose-jwk-thumbprint-01 :param hash_function: A hash function to use for hashing the information :param members: Which attributes of the Key instance that should be included when computing the hash value. If members is undefined then all the required attributes are used. :return: A base64 encode hash over a set of Key attributes
4.781652
4.677691
1.022225
dkm = b'' dk_bytes = int(ceil(dk_len / 8.0)) counter = 0 while len(dkm) < dk_bytes: counter += 1 counter_bytes = struct.pack("!I", counter) digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(counter_bytes) digest.update(secret) digest.update(other_info) dkm += digest.finalize() return dkm[:dk_bytes]
def concat_sha256(secret, dk_len, other_info)
The Concat KDF, using SHA256 as the hash function. Note: Does not validate that otherInfo meets the requirements of SP800-56A. :param secret: The shared secret value :param dk_len: Length of key to be derived, in bits :param other_info: Other info to be incorporated (see SP800-56A) :return: The derived key
2.201027
2.257271
0.975083
if not alg: alg = self["alg"] if alg == "none": return [] _k = self.alg2keytype(alg) if _k is None: logger.error("Unknown algorithm '%s'" % alg) raise ValueError('Unknown cryptography algorithm') logger.debug("Picking key by key type={0}".format(_k)) _kty = [_k.lower(), _k.upper(), _k.lower().encode("utf-8"), _k.upper().encode("utf-8")] _keys = [k for k in keys if k.kty in _kty] try: _kid = self["kid"] except KeyError: try: _kid = self.jwt.headers["kid"] except (AttributeError, KeyError): _kid = None logger.debug("Picking key based on alg={0}, kid={1} and use={2}".format( alg, _kid, use)) pkey = [] for _key in _keys: logger.debug( "Picked: kid:{}, use:{}, kty:{}".format( _key.kid, _key.use, _key.kty)) if _kid: if _kid != _key.kid: continue if use and _key.use and _key.use != use: continue if alg and _key.alg and _key.alg != alg: continue pkey.append(_key) return pkey
def pick_keys(self, keys, use="", alg="")
The assumption is that upper layer has made certain you only get keys you can use. :param alg: The crypto algorithm :param use: What the key should be used for :param keys: A list of JWK instances :return: A list of JWK instances that fulfill the requirements
2.772628
2.758021
1.005296
self._add_result = Sensor.float("add.result", "Last ?add result.", "", [-10000, 10000]) self._add_result.set_value(0, Sensor.UNREACHABLE) self._time_result = Sensor.timestamp("time.result", "Last ?time result.", "") self._time_result.set_value(0, Sensor.INACTIVE) self._eval_result = Sensor.string("eval.result", "Last ?eval result.", "") self._eval_result.set_value('', Sensor.UNKNOWN) self._fruit_result = Sensor.discrete("fruit.result", "Last ?pick-fruit result.", "", self.FRUIT) self._fruit_result.set_value('apple', Sensor.ERROR) self.add_sensor(self._add_result) self.add_sensor(self._time_result) self.add_sensor(self._eval_result) self.add_sensor(self._fruit_result)
def setup_sensors(self)
Setup some server sensors.
3.090622
2.974686
1.038974
r = x + y self._add_result.set_value(r) return ("ok", r)
def request_add(self, req, x, y)
Add two numbers
9.328113
9.090274
1.026164
r = time.time() self._time_result.set_value(r) return ("ok", r)
def request_time(self, req)
Return the current time in ms since the Unix Epoch.
11.162601
10.161813
1.098485
r = str(eval(expression)) self._eval_result.set_value(r) return ("ok", r)
def request_eval(self, req, expression)
Evaluate a Python expression.
7.876569
7.503796
1.049678
r = random.choice(self.FRUIT + [None]) if r is None: return ("fail", "No fruit.") delay = random.randrange(1,5) req.inform("Picking will take %d seconds" % delay) def pick_handler(): self._fruit_result.set_value(r) req.reply("ok", r) handle_timer = threading.Timer(delay, pick_handler) handle_timer.start() raise AsyncReply
def request_pick_fruit(self, req)
Pick a random fruit.
6.984055
6.649679
1.050284
sensor = self.get_sensor(sensor_name) ts, status, value = sensor.read() sensor.set_value(value, sensor.INACTIVE, ts) return('ok',)
def request_set_sensor_inactive(self, req, sensor_name)
Set sensor status to inactive
7.24809
7.360072
0.984785
sensor = self.get_sensor(sensor_name) ts, status, value = sensor.read() sensor.set_value(value, sensor.UNREACHABLE, ts) return('ok',)
def request_set_sensor_unreachable(self, req, sensor_name)
Set sensor status to unreachable
6.32173
6.241682
1.012825
# msg is a katcp.Message.request object reversed_args = msg.arguments[::-1] # req.make_reply() makes a katcp.Message.reply using the correct request # name and message ID return req.make_reply(*reversed_args)
def request_raw_reverse(self, req, msg)
A raw request handler to demonstrate the calling convention if @request decoraters are not used. Reverses the message arguments.
8.972035
8.581867
1.045464
new_future = tornado_Future() def _transform(f): assert f is future if f.exc_info() is not None: new_future.set_exc_info(f.exc_info()) else: try: new_future.set_result(transformation(f.result())) except Exception: # An exception here idicates that the transformation was unsuccesful new_future.set_exc_info(sys.exc_info()) future.add_done_callback(_transform) return new_future
def transform_future(transformation, future)
Returns a new future that will resolve with a transformed value Takes the resolution value of `future` and applies transformation(*future.result()) to it before setting the result of the new future with the transformed value. If future() resolves with an exception, it is passed through to the new future. Assumes `future` is a tornado Future.
3.31319
3.200621
1.035171
filter_re = re.compile(filter) found_sensors = [] none_strat = resource.normalize_strategy_parameters('none') sensor_dict = dict(sensor_items) for sensor_identifier in sorted(sensor_dict.keys()): sensor_obj = sensor_dict[sensor_identifier] search_name = (sensor_identifier if use_python_identifiers else sensor_obj.name) name_match = filter_re.search(search_name) # Only include sensors with strategies strat_match = not strategy or sensor_obj.sampling_strategy != none_strat if name_match and strat_match: if refresh: # First refresh the sensor reading yield sensor_obj.get_value() # Determine the sensorname prefix: # parent_name. except for aggs when in KATCPClientResourceContinaer prefix = "" if isinstance(parent_class, KATCPClientResourceContainer): if sensor_obj.name.startswith("agg_"): prefix = "" else: prefix = sensor_obj.parent_name + "." if not status or (sensor_obj.reading.status in status): # Only include sensors of the given status if tuple: # (sensor.name, sensor.value, sensor.value_seconds, sensor.type, sensor.units, sensor.update_seconds, sensor.status, strategy_and_params) found_sensors.append(( prefix+sensor_obj.name, sensor_obj.reading.value, sensor_obj.reading.timestamp, sensor_obj.type, sensor_obj.units, sensor_obj.reading.received_timestamp, sensor_obj.reading.status, sensor_obj.sampling_strategy )) else: found_sensors.append(resource.SensorResultTuple( object=sensor_obj, name=prefix+sensor_obj.name, python_identifier=sensor_identifier, description=sensor_obj.description, units=sensor_obj.units, type=sensor_obj.type, reading=sensor_obj.reading)) raise tornado.gen.Return(found_sensors)
def list_sensors(parent_class, sensor_items, filter, strategy, status, use_python_identifiers, tuple, refresh)
Helper for implementing :meth:`katcp.resource.KATCPResource.list_sensors` Parameters ---------- sensor_items : tuple of sensor-item tuples As would be returned the items() method of a dict containing KATCPSensor objects keyed by Python-identifiers. parent_class: KATCPClientResource or KATCPClientResourceContainer Is used for prefix calculation Rest of parameters as for :meth:`katcp.resource.KATCPResource.list_sensors`
3.877071
3.628012
1.068649
exit_event = exit_event or AsyncEvent() callback(False) # Initial condition, assume resource is not connected while not exit_event.is_set(): # Wait for resource to be synced yield until_any(resource.until_synced(), exit_event.until_set()) if exit_event.is_set(): break # If exit event is set we stop without calling callback else: callback(True) # Wait for resource to be un-synced yield until_any(resource.until_not_synced(), exit_event.until_set()) if exit_event.is_set(): break # If exit event is set we stop without calling callback else: callback(False)
def monitor_resource_sync_state(resource, callback, exit_event=None)
Coroutine that monitors a KATCPResource's sync state. Calls callback(True/False) whenever the resource becomes synced or unsynced. Will always do an initial callback(False) call. Exits without calling callback() if exit_event is set
3.333701
3.299946
1.010229
f = tornado_Future() try: use_mid = kwargs.get('use_mid') timeout = kwargs.get('timeout') mid = kwargs.get('mid') msg = Message.request(request, *args, mid=mid) except Exception: f.set_exc_info(sys.exc_info()) return f return transform_future(self.reply_wrapper, self.katcp_client.future_request(msg, timeout, use_mid))
def wrapped_request(self, request, *args, **kwargs)
Create and send a request to the server. This method implements a very small subset of the options possible to send an request. It is provided as a shortcut to sending a simple wrapped request. Parameters ---------- request : str The request to call. *args : list of objects Arguments to pass on to the request. Keyword Arguments ----------------- timeout : float or None, optional Timeout after this amount of seconds (keyword argument). mid : None or int, optional Message identifier to use for the request message. If None, use either auto-incrementing value or no mid depending on the KATCP protocol version (mid's were only introduced with KATCP v5) and the value of the `use_mid` argument. Defaults to None. use_mid : bool Use a mid for the request if True. Returns ------- future object that resolves with the :meth:`katcp.client.DeviceClient.future_request` response wrapped in self.reply_wrapper Example ------- :: wrapped_reply = yield ic.simple_request('help', 'sensor-list')
5.295326
3.609535
1.467038
return self._state.until_state(state, timeout=timeout)
def until_state(self, state, timeout=None)
Future that resolves when a certain client state is attained Parameters ---------- state : str Desired state, one of ("disconnected", "syncing", "synced") timeout: float Timeout for operation in seconds.
7.258297
14.462563
0.501868
# TODO (NM 2015-03-12) Some checking to prevent multiple calls to start() host, port = self.address ic = self._inspecting_client = self.inspecting_client_factory( host, port, self._ioloop_set_to) self.ioloop = ic.ioloop if self._preset_protocol_flags: ic.preset_protocol_flags(self._preset_protocol_flags) ic.katcp_client.auto_reconnect_delay = self.auto_reconnect_delay ic.set_state_callback(self._inspecting_client_state_callback) ic.request_factory = self._request_factory self._sensor_manager = KATCPClientResourceSensorsManager( ic, self.name, logger=self._logger) ic.handle_sensor_value() ic.sensor_factory = self._sensor_manager.sensor_factory # Steal some methods from _sensor_manager self.reapply_sampling_strategies = self._sensor_manager.reapply_sampling_strategies log_future_exceptions(self._logger, ic.connect())
def start(self)
Start the client and connect
6.583428
6.559311
1.003677
return ReplyWrappedInspectingClientAsync( host, port, ioloop=ioloop_set_to, auto_reconnect=self.auto_reconnect)
def inspecting_client_factory(self, host, port, ioloop_set_to)
Return an instance of :class:`ReplyWrappedInspectingClientAsync` or similar Provided to ease testing. Dynamically overriding this method after instantiation but before start() is called allows for deep brain surgery. See :class:`katcp.fake_clients.fake_inspecting_client_factory`
7.599838
3.78254
2.009189
not_synced_states = [state for state in self._state.valid_states if state != 'synced'] not_synced_futures = [self._state.until_state(state) for state in not_synced_states] return until_any(*not_synced_futures, timeout=timeout)
def until_not_synced(self, timeout=None)
Convenience method to wait (with Future) until client is not synced
3.946881
3.640045
1.084295
sensor_list = yield self.list_sensors(filter=filter) sensor_dict = {} for sens in sensor_list: # Set the strategy on each sensor try: sensor_name = sens.object.normalised_name yield self.set_sampling_strategy(sensor_name, strategy_and_parms) sensor_dict[sensor_name] = strategy_and_parms except Exception as exc: self._logger.exception( 'Unhandled exception trying to set sensor strategies {!r} for {} ({})' .format(strategy_and_parms, sens, exc)) sensor_dict[sensor_name] = None # Otherwise, depend on self._add_sensors() to handle it from the cache when the sensor appears\ raise tornado.gen.Return(sensor_dict)
def set_sampling_strategies(self, filter, strategy_and_parms)
Set a strategy for all sensors matching the filter, including unseen sensors The strategy should persist across sensor disconnect/reconnect. filter : str Filter for sensor names strategy_and_params : seq of str or str As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec. As str contains the same elements in space-separated form. Returns ------- done : tornado Future Resolves when done
5.412076
5.288043
1.023455
sensor_name = resource.escape_name(sensor_name) sensor_obj = dict.get(self._sensor, sensor_name) self._sensor_strategy_cache[sensor_name] = strategy_and_parms sensor_dict = {} self._logger.debug( 'Cached strategy {} for sensor {}' .format(strategy_and_parms, sensor_name)) if sensor_obj: # The sensor exists, so set the strategy and continue. Log errors, # but don't raise anything try: yield sensor_obj.set_sampling_strategy(strategy_and_parms) sensor_dict[sensor_name] = strategy_and_parms except Exception as exc: self._logger.exception( 'Unhandled exception trying to set sensor strategy {!r} for sensor {} ({})' .format(strategy_and_parms, sensor_name, exc)) sensor_dict[sensor_name] = str(exc) # Otherwise, depend on self._add_sensors() to handle it from the cache when the sensor appears raise tornado.gen.Return(sensor_dict)
def set_sampling_strategy(self, sensor_name, strategy_and_parms)
Set a strategy for a sensor even if it is not yet known. The strategy should persist across sensor disconnect/reconnect. sensor_name : str Name of the sensor strategy_and_params : seq of str or str As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec. As str contains the same elements in space-separated form. Returns ------- done : tornado Future Resolves when done
4.107545
4.201224
0.977702
sensor_name = resource.escape_name(sensor_name) # drop from both the internal cache, and the sensor manager's cache self._sensor_strategy_cache.pop(sensor_name, None) self._sensor_manager.drop_sampling_strategy(sensor_name)
def drop_sampling_strategy(self, sensor_name)
Drop the sampling strategy for the named sensor from the cache Calling :meth:`set_sampling_strategy` requires the requested strategy to be memorised so that it can automatically be reapplied. This method causes the strategy to be forgotten. There is no change to the current strategy. No error is raised if there is no strategy to drop. Parameters ---------- sensor_name : str Name of the sensor
5.170333
6.755823
0.765315
sensor_name = resource.escape_name(sensor_name) sensor_obj = dict.get(self._sensor, sensor_name) self._sensor_listener_cache[sensor_name].append(listener) sensor_dict = {} self._logger.debug( 'Cached listener {} for sensor {}' .format(listener, sensor_name)) if sensor_obj: # The sensor exists, so register the listener and continue. try: sensor_obj.register_listener(listener, reading=True) sensor_dict[sensor_name] = listener self._logger.debug( 'Registered listener {} for sensor {}' .format(listener, sensor_name)) except Exception as exc: self._logger.exception( 'Unhandled exception trying to set sensor listener {} for sensor {} ({})' .format(listener, sensor_name, exc)) sensor_dict[sensor_name] = str(exc) # Otherwise, depend on self._add_sensors() to handle it from the cache when the sensor appears raise tornado.gen.Return(sensor_dict)
def set_sensor_listener(self, sensor_name, listener)
Set a sensor listener for a sensor even if it is not yet known The listener registration should persist across sensor disconnect/reconnect. sensor_name : str Name of the sensor listener : callable Listening callable that will be registered on the named sensor when it becomes available. Callable as for :meth:`KATCPSensor.register_listener`
4.082339
4.066289
1.003947
# try for a direct match first, otherwise do full comparison if sensor_name in self._strategy_cache: return sensor_name else: escaped_name = resource.escape_name(sensor_name) for key in self._strategy_cache: escaped_key = resource.escape_name(key) if escaped_key == escaped_name: return key # no match return sensor_name
def _get_strategy_cache_key(self, sensor_name)
Lookup sensor name in cache, allowing names in escaped form The strategy cache uses the normal KATCP sensor names as the keys. In order to allow access using an escaped sensor name, this method tries to find the normal form of the name. Returns ------- key : str If there is a match, the cache key is returned. If no match, then the sensor_name is returned unchanged.
3.594167
3.47332
1.034793
cache_key = self._get_strategy_cache_key(sensor_name) cached = self._strategy_cache.get(cache_key) if not cached: return resource.normalize_strategy_parameters('none') else: return cached
def get_sampling_strategy(self, sensor_name)
Get the current sampling strategy for the named sensor Parameters ---------- sensor_name : str Name of the sensor (normal or escaped form) Returns ------- strategy : tuple of str contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec
5.779981
5.685621
1.016596
try: strategy_and_params = resource.normalize_strategy_parameters( strategy_and_params) self._strategy_cache[sensor_name] = strategy_and_params reply = yield self._inspecting_client.wrapped_request( 'sensor-sampling', sensor_name, *strategy_and_params) if not reply.succeeded: raise KATCPSensorError('Error setting strategy for sensor {0}: \n' '{1!s}'.format(sensor_name, reply)) sensor_strategy = (True, strategy_and_params) except Exception as e: self._logger.exception('Exception found!') sensor_strategy = (False, str(e)) raise tornado.gen.Return(sensor_strategy)
def set_sampling_strategy(self, sensor_name, strategy_and_params)
Set the sampling strategy for the named sensor Parameters ---------- sensor_name : str Name of the sensor strategy_and_params : seq of str or str As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec. As str contains the same elements in space-separated form. Returns ------- sensor_strategy : tuple (success, info) with success : bool True if setting succeeded for this sensor, else False info : tuple Normalibed sensor strategy and parameters as tuple if success == True else, sys.exc_info() tuple for the error that occured.
4.504522
3.962734
1.136721
cache_key = self._get_strategy_cache_key(sensor_name) self._strategy_cache.pop(cache_key, None)
def drop_sampling_strategy(self, sensor_name)
Drop the sampling strategy for the named sensor from the cache Calling :meth:`set_sampling_strategy` requires the sensor manager to memorise the requested strategy so that it can automatically be reapplied. If the client is no longer interested in the sensor, or knows the sensor may be removed from the server, then it can use this method to ensure the manager forgets about the strategy. This method will not change the current strategy. No error is raised if there is no strategy to drop. Parameters ---------- sensor_name : str Name of the sensor (normal or escaped form)
4.034231
6.006219
0.671676
check_sensor = self._inspecting_client.future_check_sensor for sensor_name, strategy in list(self._strategy_cache.items()): try: sensor_exists = yield check_sensor(sensor_name) if not sensor_exists: self._logger.warn('Did not set strategy for non-existing sensor {}' .format(sensor_name)) continue result = yield self.set_sampling_strategy(sensor_name, strategy) except KATCPSensorError as e: self._logger.error('Error reapplying strategy for sensor {0}: {1!s}' .format(sensor_name, e)) except Exception: self._logger.exception('Unhandled exception reapplying strategy for ' 'sensor {}'.format(sensor_name), exc_info=True)
def reapply_sampling_strategies(self)
Reapply all sensor strategies using cached values
3.77688
3.471109
1.08809
timeout = kwargs.pop('timeout', None) if timeout is None: timeout = self.timeout_hint kwargs['timeout'] = timeout return self._client.wrapped_request(self.name, *args, **kwargs)
def issue_request(self, *args, **kwargs)
Issue the wrapped request to the server. Parameters ---------- *args : list of objects Arguments to pass on to the request. Keyword Arguments ----------------- timeout : float or None, optional Timeout after this amount of seconds (keyword argument). mid : None or int, optional Message identifier to use for the request message. If None, use either auto-incrementing value or no mid depending on the KATCP protocol version (mid's were only introduced with KATCP v5) and the value of the `use_mid` argument. Defaults to None. use_mid : bool Use a mid for the request if True. Returns ------- future object that resolves with an :class:`katcp.resource.KATCPReply` instance
4.320929
4.877084
0.885966
futures_dict = {} for res_obj in self.clients: futures_dict[res_obj.name] = res_obj.set_sampling_strategies( filter, strategy_and_params) sensors_strategies = yield futures_dict raise tornado.gen.Return(sensors_strategies)
def set_sampling_strategies(self, filter, strategy_and_params)
Set sampling strategy for the sensors of all the group's clients. Only sensors that match the specified filter are considered. See the `KATCPResource.set_sampling_strategies` docstring for parameter definitions and more info. Returns ------- sensors_strategies : tornado Future Resolves with a dict with client names as keys and with the value as another dict. The value dict is similar to the return value described in the `KATCPResource.set_sampling_strategies` docstring.
4.236555
3.014909
1.405202
futures_dict = {} for res_obj in self.clients: futures_dict[res_obj.name] = res_obj.set_sampling_strategy( sensor_name, strategy_and_params) sensors_strategies = yield futures_dict raise tornado.gen.Return(sensors_strategies)
def set_sampling_strategy(self, sensor_name, strategy_and_params)
Set sampling strategy for the sensors of all the group's clients. Only sensors that match the specified filter are considered. See the `KATCPResource.set_sampling_strategies` docstring for parameter definitions and more info. Returns ------- sensors_strategies : tornado Future Resolves with a dict with client names as keys and with the value as another dict. The value dict is similar to the return value described in the `KATCPResource.set_sampling_strategies` docstring.
3.803136
3.013692
1.261952
if quorum is None: quorum = len(self.clients) elif quorum > 1: if not isinstance(quorum, int): raise TypeError('Quorum parameter %r must be an integer ' 'if outside range [0, 1]' % (quorum,)) elif isinstance(quorum, float): quorum = int(math.ceil(quorum * len(self.clients))) if timeout and max_grace_period: # Avoid having a grace period longer than or equal to timeout grace_period = min(max_grace_period, timeout / 2.) initial_timeout = timeout - grace_period else: grace_period = max_grace_period initial_timeout = timeout # Build dict of futures instead of list as this will be easier to debug futures = {} for client in self.clients: f = client.wait(sensor_name, condition_or_value, initial_timeout) futures[client.name] = f # No timeout required here as all futures will resolve after timeout initial_results = yield until_some(done_at_least=quorum, **futures) results = dict(initial_results) # Identify stragglers and let them all respond within grace period stragglers = {} for client in self.clients: if not results.get(client.name, False): f = client.wait(sensor_name, condition_or_value, grace_period) stragglers[client.name] = f rest_of_results = yield until_some(**stragglers) results.update(dict(rest_of_results)) class TestableDict(dict): def __bool__(self): return sum(self.values()) >= quorum # Was not handled automatrically by futurize, see # https://github.com/PythonCharmers/python-future/issues/282 if sys.version_info[0] == 2: __nonzero__ = __bool__ raise tornado.gen.Return(TestableDict(results))
def wait(self, sensor_name, condition_or_value, timeout=5.0, quorum=None, max_grace_period=1.0)
Wait for sensor present on all group clients to satisfy a condition. Parameters ---------- sensor_name : string The name of the sensor to check condition_or_value : obj or callable, or seq of objs or callables If obj, sensor.value is compared with obj. If callable, condition_or_value(reading) is called, and must return True if its condition is satisfied. Since the reading is passed in, the value, status, timestamp or received_timestamp attributes can all be used in the check. timeout : float or None The total timeout in seconds (None means wait forever) quorum : None or int or float The number of clients that are required to satisfy the condition, as either an explicit integer or a float between 0 and 1 indicating a fraction of the total number of clients, rounded up. If None, this means that all clients are required (the default). Be warned that a value of 1.0 (float) indicates all clients while a value of 1 (int) indicates a single client... max_grace_period : float or None After a quorum or initial timeout is reached, wait up to this long in an attempt to get the rest of the clients to satisfy condition as well (achieving effectively a full quorum if all clients behave) Returns ------- This command returns a tornado Future that resolves with True when a quorum of clients satisfy the sensor condition, or False if a quorum is not reached after a given timeout period (including a grace period). Raises ------ :class:`KATCPSensorError` If any of the sensors do not have a strategy set, or if the named sensor is not present
3.777385
3.785934
0.997742
return KATCPClientResource(res_spec, parent=self, logger=logger)
def client_resource_factory(self, res_spec, parent, logger)
Return an instance of :class:`KATCPClientResource` or similar Provided to ease testing. Overriding this method allows deep brain surgery. See :func:`katcp.fake_clients.fake_KATCP_client_resource_factory`
8.007259
5.662302
1.414135
group_configs = self._resources_spec.get('groups', {}) group_configs[group_name] = group_client_names self._resources_spec['groups'] = group_configs self._init_groups()
def add_group(self, group_name, group_client_names)
Add a new :class:`ClientGroup` to container groups member. Add the group named *group_name* with sequence of client names to the container groups member. From there it will be wrapped appropriately in the higher-level thread-safe container.
3.578304
4.331336
0.826143
ioloop = ioloop or tornado.ioloop.IOLoop.current() self.ioloop = ioloop for res in dict.values(self.children): res.set_ioloop(ioloop)
def set_ioloop(self, ioloop=None)
Set the tornado ioloop to use Defaults to tornado.ioloop.IOLoop.current() if set_ioloop() is not called or if ioloop=None. Must be called before start()
3.107394
3.958627
0.784967
return all([r.is_connected() for r in dict.values(self.children)])
def is_connected(self)
Indication of the connection state of all children
11.22712
7.107965
1.579513
futures = [r.until_synced(timeout) for r in dict.values(self.children)] yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError)
def until_synced(self, timeout=None)
Return a tornado Future; resolves when all subordinate clients are synced
7.648281
6.056131
1.262899
yield until_any(*[r.until_not_synced() for r in dict.values(self.children)], timeout=timeout)
def until_not_synced(self, timeout=None)
Return a tornado Future; resolves when any subordinate client is not synced
12.203305
10.025229
1.21726
return until_any(*[r.until_state(state) for r in dict.values(self.children)], timeout=timeout)
def until_any_child_in_state(self, state, timeout=None)
Return a tornado Future; resolves when any client is in specified state
9.178947
9.046895
1.014596
futures = [r.until_state(state, timeout=timeout) for r in dict.values(self.children)] yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError)
def until_all_children_in_state(self, state, timeout=None)
Return a tornado Future; resolves when all clients are in specified state
6.374424
5.73055
1.112358
result_list = yield self.list_sensors(filter=filter) sensor_dict = {} for result in result_list: sensor_name = result.object.normalised_name resource_name = result.object.parent_name if resource_name not in sensor_dict: sensor_dict[resource_name] = {} try: resource_obj = self.children[resource_name] yield resource_obj.set_sampling_strategy(sensor_name, strategy_and_parms) sensor_dict[resource_name][sensor_name] = strategy_and_parms self._logger.debug( 'Set sampling strategy on resource %s for %s' % (resource_name, sensor_name)) except Exception as exc: self._logger.error( 'Cannot set sampling strategy on resource %s for %s (%s)' % (resource_name, sensor_name, exc)) sensor_dict[resource_name][sensor_name] = None raise tornado.gen.Return(sensor_dict)
def set_sampling_strategies(self, filter, strategy_and_parms)
Set sampling strategies for filtered sensors - these sensors have to exsist
2.541878
2.519746
1.008783
res_spec = dict(res_spec) res_spec['name'] = res_name res = self.client_resource_factory( res_spec, parent=self, logger=self._logger) self.children[resource.escape_name(res_name)] = res; self._children_dirty = True res.set_ioloop(self.ioloop) res.start() return res
def add_child_resource_client(self, res_name, res_spec)
Add a resource client to the container and start the resource connection
4.134435
4.087295
1.011533
for child_name, child in dict.items(self.children): # Catch child exceptions when stopping so we make sure to stop all children # that want to listen. try: child.stop() except Exception: self._logger.exception('Exception stopping child {!r}' .format(child_name))
def stop(self)
Stop all child resources
6.934161
6.488183
1.068737
# skip signature i = 8 # yield chunks while i < len(b): data_len, = struct.unpack("!I", b[i:i+4]) type_ = b[i+4:i+8].decode("latin-1") yield Chunk(type_, b[i:i+data_len+12]) i += data_len + 12
def parse_chunks(b)
Parse PNG bytes into multiple chunks. :arg bytes b: The raw bytes of the PNG file. :return: A generator yielding :class:`Chunk`. :rtype: Iterator[Chunk]
3.140841
3.108436
1.010425
out = struct.pack("!I", len(chunk_data)) chunk_data = chunk_type.encode("latin-1") + chunk_data out += chunk_data + struct.pack("!I", binascii.crc32(chunk_data) & 0xffffffff) return out
def make_chunk(chunk_type, chunk_data)
Create a raw chunk by composing chunk type and data. It calculates chunk length and CRC for you. :arg str chunk_type: PNG chunk type. :arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**. :rtype: bytes
2.679699
2.703962
0.991027
# pylint: disable=redefined-builtin if type == "tEXt": data = key.encode("latin-1") + b"\0" + value.encode("latin-1") elif type == "zTXt": data = ( key.encode("latin-1") + struct.pack("!xb", compression_method) + zlib.compress(value.encode("latin-1")) ) elif type == "iTXt": data = ( key.encode("latin-1") + struct.pack("!xbb", compression_flag, compression_method) + lang.encode("latin-1") + b"\0" + translated_key.encode("utf-8") + b"\0" ) if compression_flag: data += zlib.compress(value.encode("utf-8")) else: data += value.encode("utf-8") else: raise TypeError("unknown type {!r}".format(type)) return Chunk(type, make_chunk(type, data))
def make_text_chunk( type="tEXt", key="Comment", value="", compression_flag=0, compression_method=0, lang="", translated_key="")
Create a text chunk with a key value pair. See https://www.w3.org/TR/PNG/#11textinfo for text chunk information. Usage: .. code:: python from apng import APNG, make_text_chunk im = APNG.open("file.png") png, control = im.frames[0] png.chunks.append(make_text_chunk("tEXt", "Comment", "some text")) im.save("file.png") :arg str type: Text chunk type: "tEXt", "zTXt", or "iTXt": tEXt uses Latin-1 characters. zTXt uses Latin-1 characters, compressed with zlib. iTXt uses UTF-8 characters. :arg str key: The key string, 1-79 characters. :arg str value: The text value. It would be encoded into :class:`bytes` and compressed if needed. :arg int compression_flag: The compression flag for iTXt. :arg int compression_method: The compression method for zTXt and iTXt. :arg str lang: The language tag for iTXt. :arg str translated_key: The translated keyword for iTXt. :rtype: Chunk
2.057444
1.966712
1.046134
if hasattr(file, "read"): return file.read() if hasattr(file, "read_bytes"): return file.read_bytes() with open(file, "rb") as f: return f.read()
def read_file(file)
Read ``file`` into ``bytes``. :arg file type: path-like or file-like :rtype: bytes
1.95735
1.936011
1.011022
if hasattr(file, "write_bytes"): file.write_bytes(b) elif hasattr(file, "write"): file.write(b) else: with open(file, "wb") as f: f.write(b)
def write_file(file, b)
Write ``b`` to file ``file``. :arg file type: path-like or file-like object. :arg bytes b: The content.
1.842604
1.90136
0.969098
if hasattr(file, "read"): return file if hasattr(file, "open"): return file.open(mode) return open(file, mode)
def open_file(file, mode)
Open a file. :arg file: file-like or path-like object. :arg str mode: ``mode`` argument for :func:`open`.
2.367348
2.996791
0.789961
import PIL.Image # pylint: disable=import-error with io.BytesIO() as dest: PIL.Image.open(fp).save(dest, "PNG", optimize=True) return dest.getvalue()
def file_to_png(fp)
Convert an image to PNG format with Pillow. :arg file-like fp: The image file. :rtype: bytes
2.904195
2.939399
0.988024
for type_, data in self.chunks: if type_ == "IHDR": self.hdr = data elif type_ == "IEND": self.end = data if self.hdr: # grab w, h info self.width, self.height = struct.unpack("!II", self.hdr[8:16])
def init(self)
Extract some info from chunks
3.604221
3.124681
1.153468