INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Get the curves supported by OpenSSL.
def _load_elliptic_curves(cls, lib): """ Get the curves supported by OpenSSL. :param lib: The OpenSSL library binding object. :return: A :py:type:`set` of ``cls`` instances giving the names of the elliptic curves the underlying library supports. """ num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0) builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves) # The return value on this call should be num_curves again. We # could check it to make sure but if it *isn't* then.. what could # we do? Abort the whole process, I suppose...? -exarkun lib.EC_get_builtin_curves(builtin_curves, num_curves) return set( cls.from_nid(lib, c.nid) for c in builtin_curves)
Get cache and return the curves supported by OpenSSL.
def _get_elliptic_curves(cls, lib): """ Get, cache, and return the curves supported by OpenSSL. :param lib: The OpenSSL library binding object. :return: A :py:type:`set` of ``cls`` instances giving the names of the elliptic curves the underlying library supports. """ if cls._curves is None: cls._curves = cls._load_elliptic_curves(lib) return cls._curves
Instantiate a new: py: class: _EllipticCurve associated with the given OpenSSL NID.
def from_nid(cls, lib, nid): """ Instantiate a new :py:class:`_EllipticCurve` associated with the given OpenSSL NID. :param lib: The OpenSSL library binding object. :param nid: The OpenSSL NID the resulting curve object will represent. This must be a curve NID (and not, for example, a hash NID) or subsequent operations will fail in unpredictable ways. :type nid: :py:class:`int` :return: The curve object. """ return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
Create a new OpenSSL EC_KEY structure initialized to use this curve.
def _to_EC_KEY(self): """ Create a new OpenSSL EC_KEY structure initialized to use this curve. The structure is automatically garbage collected when the Python object is garbage collected. """ key = self._lib.EC_KEY_new_by_curve_name(self._nid) return _ffi.gc(key, _lib.EC_KEY_free)
Return the DER encoding of this name.
def der(self): """ Return the DER encoding of this name. :return: The DER encoded form of this name. :rtype: :py:class:`bytes` """ result_buffer = _ffi.new('unsigned char**') encode_result = _lib.i2d_X509_NAME(self._name, result_buffer) _openssl_assert(encode_result >= 0) string_result = _ffi.buffer(result_buffer[0], encode_result)[:] _lib.OPENSSL_free(result_buffer[0]) return string_result
Returns the components of this name as a sequence of 2 - tuples.
def get_components(self): """ Returns the components of this name, as a sequence of 2-tuples. :return: The components of this name. :rtype: :py:class:`list` of ``name, value`` tuples. """ result = [] for i in range(_lib.X509_NAME_entry_count(self._name)): ent = _lib.X509_NAME_get_entry(self._name, i) fname = _lib.X509_NAME_ENTRY_get_object(ent) fval = _lib.X509_NAME_ENTRY_get_data(ent) nid = _lib.OBJ_obj2nid(fname) name = _lib.OBJ_nid2sn(nid) # ffi.string does not handle strings containing NULL bytes # (which may have been generated by old, broken software) value = _ffi.buffer(_lib.ASN1_STRING_data(fval), _lib.ASN1_STRING_length(fval))[:] result.append((_ffi.string(name), value)) return result
Returns the short type name of this X. 509 extension.
def get_short_name(self): """ Returns the short type name of this X.509 extension. The result is a byte string such as :py:const:`b"basicConstraints"`. :return: The short type name. :rtype: :py:data:`bytes` .. versionadded:: 0.12 """ obj = _lib.X509_EXTENSION_get_object(self._extension) nid = _lib.OBJ_obj2nid(obj) return _ffi.string(_lib.OBJ_nid2sn(nid))
Returns the data of the X509 extension encoded as ASN. 1.
def get_data(self): """ Returns the data of the X509 extension, encoded as ASN.1. :return: The ASN.1 encoded data of this X509 extension. :rtype: :py:data:`bytes` .. versionadded:: 0.12 """ octet_result = _lib.X509_EXTENSION_get_data(self._extension) string_result = _ffi.cast('ASN1_STRING*', octet_result) char_result = _lib.ASN1_STRING_data(string_result) result_length = _lib.ASN1_STRING_length(string_result) return _ffi.buffer(char_result, result_length)[:]
Export as a cryptography certificate signing request.
def to_cryptography(self): """ Export as a ``cryptography`` certificate signing request. :rtype: ``cryptography.x509.CertificateSigningRequest`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import ( _CertificateSigningRequest ) backend = _get_backend() return _CertificateSigningRequest(backend, self._req)
Construct based on a cryptography * crypto_req *.
def from_cryptography(cls, crypto_req): """ Construct based on a ``cryptography`` *crypto_req*. :param crypto_req: A ``cryptography`` X.509 certificate signing request :type crypto_req: ``cryptography.x509.CertificateSigningRequest`` :rtype: X509Req .. versionadded:: 17.1.0 """ if not isinstance(crypto_req, x509.CertificateSigningRequest): raise TypeError("Must be a certificate signing request") req = cls() req._req = crypto_req._x509_req return req
Set the public key of the certificate signing request.
def set_pubkey(self, pkey): """ Set the public key of the certificate signing request. :param pkey: The public key to use. :type pkey: :py:class:`PKey` :return: ``None`` """ set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey) _openssl_assert(set_result == 1)
Get the public key of the certificate signing request.
def get_pubkey(self): """ Get the public key of the certificate signing request. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.X509_REQ_get_pubkey(self._req) _openssl_assert(pkey._pkey != _ffi.NULL) pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
Set the version subfield ( RFC 2459 section 4. 1. 2. 1 ) of the certificate request.
def set_version(self, version): """ Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate request. :param int version: The version number. :return: ``None`` """ set_result = _lib.X509_REQ_set_version(self._req, version) _openssl_assert(set_result == 1)
Return the subject of this certificate signing request.
def get_subject(self): """ Return the subject of this certificate signing request. This creates a new :class:`X509Name` that wraps the underlying subject name field on the certificate signing request. Modifying it will modify the underlying signing request, and will have the effect of modifying any other :class:`X509Name` that refers to this subject. :return: The subject of this certificate signing request. :rtype: :class:`X509Name` """ name = X509Name.__new__(X509Name) name._name = _lib.X509_REQ_get_subject_name(self._req) _openssl_assert(name._name != _ffi.NULL) # The name is owned by the X509Req structure. As long as the X509Name # Python object is alive, keep the X509Req Python object alive. name._owner = self return name
Add extensions to the certificate signing request.
def add_extensions(self, extensions): """ Add extensions to the certificate signing request. :param extensions: The X.509 extensions to add. :type extensions: iterable of :py:class:`X509Extension` :return: ``None`` """ stack = _lib.sk_X509_EXTENSION_new_null() _openssl_assert(stack != _ffi.NULL) stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free) for ext in extensions: if not isinstance(ext, X509Extension): raise ValueError("One of the elements is not an X509Extension") # TODO push can fail (here and elsewhere) _lib.sk_X509_EXTENSION_push(stack, ext._extension) add_result = _lib.X509_REQ_add_extensions(self._req, stack) _openssl_assert(add_result == 1)
Get X. 509 extensions in the certificate signing request.
def get_extensions(self): """ Get X.509 extensions in the certificate signing request. :return: The X.509 extensions in this request. :rtype: :py:class:`list` of :py:class:`X509Extension` objects. .. versionadded:: 0.15 """ exts = [] native_exts_obj = _lib.X509_REQ_get_extensions(self._req) for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)): ext = X509Extension.__new__(X509Extension) ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i) exts.append(ext) return exts
Verifies the signature on this certificate signing request.
def verify(self, pkey): """ Verifies the signature on this certificate signing request. :param PKey key: A public key. :return: ``True`` if the signature is correct. :rtype: bool :raises OpenSSL.crypto.Error: If the signature is invalid or there is a problem verifying the signature. """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") result = _lib.X509_REQ_verify(self._req, pkey._pkey) if result <= 0: _raise_current_error() return result
Export as a cryptography certificate.
def to_cryptography(self): """ Export as a ``cryptography`` certificate. :rtype: ``cryptography.x509.Certificate`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import _Certificate backend = _get_backend() return _Certificate(backend, self._x509)
Construct based on a cryptography * crypto_cert *.
def from_cryptography(cls, crypto_cert): """ Construct based on a ``cryptography`` *crypto_cert*. :param crypto_key: A ``cryptography`` X.509 certificate. :type crypto_key: ``cryptography.x509.Certificate`` :rtype: X509 .. versionadded:: 17.1.0 """ if not isinstance(crypto_cert, x509.Certificate): raise TypeError("Must be a certificate") cert = cls() cert._x509 = crypto_cert._x509 return cert
Set the version number of the certificate. Note that the version value is zero - based eg. a value of 0 is V1.
def set_version(self, version): """ Set the version number of the certificate. Note that the version value is zero-based, eg. a value of 0 is V1. :param version: The version number of the certificate. :type version: :py:class:`int` :return: ``None`` """ if not isinstance(version, int): raise TypeError("version must be an integer") _lib.X509_set_version(self._x509, version)
Get the public key of the certificate.
def get_pubkey(self): """ Get the public key of the certificate. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.X509_get_pubkey(self._x509) if pkey._pkey == _ffi.NULL: _raise_current_error() pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
Set the public key of the certificate.
def set_pubkey(self, pkey): """ Set the public key of the certificate. :param pkey: The public key. :type pkey: :py:class:`PKey` :return: :py:data:`None` """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey) _openssl_assert(set_result == 1)
Sign the certificate with this key and digest type.
def sign(self, pkey, digest): """ Sign the certificate with this key and digest type. :param pkey: The key to sign with. :type pkey: :py:class:`PKey` :param digest: The name of the message digest to use. :type digest: :py:class:`bytes` :return: :py:data:`None` """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") if pkey._only_public: raise ValueError("Key only has public part") if not pkey._initialized: raise ValueError("Key is uninitialized") evp_md = _lib.EVP_get_digestbyname(_byte_string(digest)) if evp_md == _ffi.NULL: raise ValueError("No such digest method") sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md) _openssl_assert(sign_result > 0)
Return the signature algorithm used in the certificate.
def get_signature_algorithm(self): """ Return the signature algorithm used in the certificate. :return: The name of the algorithm. :rtype: :py:class:`bytes` :raises ValueError: If the signature algorithm is undefined. .. versionadded:: 0.13 """ algor = _lib.X509_get0_tbs_sigalg(self._x509) nid = _lib.OBJ_obj2nid(algor.algorithm) if nid == _lib.NID_undef: raise ValueError("Undefined signature algorithm") return _ffi.string(_lib.OBJ_nid2ln(nid))
Return the digest of the X509 object.
def digest(self, digest_name): """ Return the digest of the X509 object. :param digest_name: The name of the digest algorithm to use. :type digest_name: :py:class:`bytes` :return: The digest of the object, formatted as :py:const:`b":"`-delimited hex pairs. :rtype: :py:class:`bytes` """ digest = _lib.EVP_get_digestbyname(_byte_string(digest_name)) if digest == _ffi.NULL: raise ValueError("No such digest method") result_buffer = _ffi.new("unsigned char[]", _lib.EVP_MAX_MD_SIZE) result_length = _ffi.new("unsigned int[]", 1) result_length[0] = len(result_buffer) digest_result = _lib.X509_digest( self._x509, digest, result_buffer, result_length) _openssl_assert(digest_result == 1) return b":".join([ b16encode(ch).upper() for ch in _ffi.buffer(result_buffer, result_length[0])])
Set the serial number of the certificate.
def set_serial_number(self, serial): """ Set the serial number of the certificate. :param serial: The new serial number. :type serial: :py:class:`int` :return: :py:data`None` """ if not isinstance(serial, _integer_types): raise TypeError("serial must be an integer") hex_serial = hex(serial)[2:] if not isinstance(hex_serial, bytes): hex_serial = hex_serial.encode('ascii') bignum_serial = _ffi.new("BIGNUM**") # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like # it. If bignum is still NULL after this call, then the return value # is actually the result. I hope. -exarkun small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial) if bignum_serial[0] == _ffi.NULL: set_result = _lib.ASN1_INTEGER_set( _lib.X509_get_serialNumber(self._x509), small_serial) if set_result: # TODO Not tested _raise_current_error() else: asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL) _lib.BN_free(bignum_serial[0]) if asn1_serial == _ffi.NULL: # TODO Not tested _raise_current_error() asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free) set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial) _openssl_assert(set_result == 1)
Return the serial number of this certificate.
def get_serial_number(self): """ Return the serial number of this certificate. :return: The serial number. :rtype: int """ asn1_serial = _lib.X509_get_serialNumber(self._x509) bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL) try: hex_serial = _lib.BN_bn2hex(bignum_serial) try: hexstring_serial = _ffi.string(hex_serial) serial = int(hexstring_serial, 16) return serial finally: _lib.OPENSSL_free(hex_serial) finally: _lib.BN_free(bignum_serial)
Adjust the time stamp on which the certificate stops being valid.
def gmtime_adj_notAfter(self, amount): """ Adjust the time stamp on which the certificate stops being valid. :param int amount: The number of seconds by which to adjust the timestamp. :return: ``None`` """ if not isinstance(amount, int): raise TypeError("amount must be an integer") notAfter = _lib.X509_get_notAfter(self._x509) _lib.X509_gmtime_adj(notAfter, amount)
Adjust the timestamp on which the certificate starts being valid.
def gmtime_adj_notBefore(self, amount): """ Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None`` """ if not isinstance(amount, int): raise TypeError("amount must be an integer") notBefore = _lib.X509_get_notBefore(self._x509) _lib.X509_gmtime_adj(notBefore, amount)
Check whether the certificate has expired.
def has_expired(self): """ Check whether the certificate has expired. :return: ``True`` if the certificate has expired, ``False`` otherwise. :rtype: bool """ time_string = _native(self.get_notAfter()) not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ") return not_after < datetime.datetime.utcnow()
Return the issuer of this certificate.
def get_issuer(self): """ Return the issuer of this certificate. This creates a new :class:`X509Name` that wraps the underlying issuer name field on the certificate. Modifying it will modify the underlying certificate, and will have the effect of modifying any other :class:`X509Name` that refers to this issuer. :return: The issuer of this certificate. :rtype: :class:`X509Name` """ name = self._get_name(_lib.X509_get_issuer_name) self._issuer_invalidator.add(name) return name
Set the issuer of this certificate.
def set_issuer(self, issuer): """ Set the issuer of this certificate. :param issuer: The issuer. :type issuer: :py:class:`X509Name` :return: ``None`` """ self._set_name(_lib.X509_set_issuer_name, issuer) self._issuer_invalidator.clear()
Return the subject of this certificate.
def get_subject(self): """ Return the subject of this certificate. This creates a new :class:`X509Name` that wraps the underlying subject name field on the certificate. Modifying it will modify the underlying certificate, and will have the effect of modifying any other :class:`X509Name` that refers to this subject. :return: The subject of this certificate. :rtype: :class:`X509Name` """ name = self._get_name(_lib.X509_get_subject_name) self._subject_invalidator.add(name) return name
Set the subject of this certificate.
def set_subject(self, subject): """ Set the subject of this certificate. :param subject: The subject. :type subject: :py:class:`X509Name` :return: ``None`` """ self._set_name(_lib.X509_set_subject_name, subject) self._subject_invalidator.clear()
Add extensions to the certificate.
def add_extensions(self, extensions): """ Add extensions to the certificate. :param extensions: The extensions to add. :type extensions: An iterable of :py:class:`X509Extension` objects. :return: ``None`` """ for ext in extensions: if not isinstance(ext, X509Extension): raise ValueError("One of the elements is not an X509Extension") add_result = _lib.X509_add_ext(self._x509, ext._extension, -1) if not add_result: _raise_current_error()
Get a specific extension of the certificate by index.
def get_extension(self, index): """ Get a specific extension of the certificate by index. Extensions on a certificate are kept in order. The index parameter selects which extension will be returned. :param int index: The index of the extension to retrieve. :return: The extension at the specified index. :rtype: :py:class:`X509Extension` :raises IndexError: If the extension index was out of bounds. .. versionadded:: 0.12 """ ext = X509Extension.__new__(X509Extension) ext._extension = _lib.X509_get_ext(self._x509, index) if ext._extension == _ffi.NULL: raise IndexError("extension index out of bounds") extension = _lib.X509_EXTENSION_dup(ext._extension) ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free) return ext
Adds a trusted certificate to this store.
def add_cert(self, cert): """ Adds a trusted certificate to this store. Adding a certificate with this method adds this certificate as a *trusted* certificate. :param X509 cert: The certificate to add to this store. :raises TypeError: If the certificate is not an :class:`X509`. :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your certificate. :return: ``None`` if the certificate was added successfully. """ if not isinstance(cert, X509): raise TypeError() # As of OpenSSL 1.1.0i adding the same cert to the store more than # once doesn't cause an error. Accordingly, this code now silences # the error for OpenSSL < 1.1.0i as well. if _lib.X509_STORE_add_cert(self._store, cert._x509) == 0: code = _lib.ERR_peek_error() err_reason = _lib.ERR_GET_REASON(code) _openssl_assert( err_reason == _lib.X509_R_CERT_ALREADY_IN_HASH_TABLE ) _lib.ERR_clear_error()
Add a certificate revocation list to this store.
def add_crl(self, crl): """ Add a certificate revocation list to this store. The certificate revocation lists added to a store will only be used if the associated flags are configured to check certificate revocation lists. .. versionadded:: 16.1.0 :param CRL crl: The certificate revocation list to add to this store. :return: ``None`` if the certificate revocation list was added successfully. """ _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
Set the time against which the certificates are verified.
def set_time(self, vfy_time): """ Set the time against which the certificates are verified. Normally the current time is used. .. note:: For example, you can determine if a certificate was valid at a given time. .. versionadded:: 17.0.0 :param datetime vfy_time: The verification time to set on this store. :return: ``None`` if the verification time was successfully set. """ param = _lib.X509_VERIFY_PARAM_new() param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free) _lib.X509_VERIFY_PARAM_set_time(param, int(vfy_time.strftime('%s'))) _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
Set up the store context for a subsequent verification operation.
def _init(self): """ Set up the store context for a subsequent verification operation. Calling this method more than once without first calling :meth:`_cleanup` will leak memory. """ ret = _lib.X509_STORE_CTX_init( self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL ) if ret <= 0: _raise_current_error()
Convert an OpenSSL native context error failure into a Python exception.
def _exception_from_context(self): """ Convert an OpenSSL native context error failure into a Python exception. When a call to native OpenSSL X509_verify_cert fails, additional information about the failure can be obtained from the store context. """ errors = [ _lib.X509_STORE_CTX_get_error(self._store_ctx), _lib.X509_STORE_CTX_get_error_depth(self._store_ctx), _native(_ffi.string(_lib.X509_verify_cert_error_string( _lib.X509_STORE_CTX_get_error(self._store_ctx)))), ] # A context error should always be associated with a certificate, so we # expect this call to never return :class:`None`. _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx) _cert = _lib.X509_dup(_x509) pycert = X509._from_raw_x509_ptr(_cert) return X509StoreContextError(errors, pycert)
Verify a certificate in a context.
def verify_certificate(self): """ Verify a certificate in a context. .. versionadded:: 0.15 :raises X509StoreContextError: If an error occurred when validating a certificate in the context. Sets ``certificate`` attribute to indicate which certificate caused the error. """ # Always re-initialize the store context in case # :meth:`verify_certificate` is called multiple times. # # :meth:`_init` is called in :meth:`__init__` so _cleanup is called # before _init to ensure memory is not leaked. self._cleanup() self._init() ret = _lib.X509_verify_cert(self._store_ctx) self._cleanup() if ret <= 0: raise self._exception_from_context()
Set the serial number.
def set_serial(self, hex_str): """ Set the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :param bytes hex_str: The new serial number. :return: ``None`` """ bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free) bignum_ptr = _ffi.new("BIGNUM**") bignum_ptr[0] = bignum_serial bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str) if not bn_result: raise ValueError("bad hex string") asn1_serial = _ffi.gc( _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL), _lib.ASN1_INTEGER_free) _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Get the serial number.
def get_serial(self): """ Get the serial number. The serial number is formatted as a hexadecimal number encoded in ASCII. :return: The serial number. :rtype: bytes """ bio = _new_mem_buf() asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked) _openssl_assert(asn1_int != _ffi.NULL) result = _lib.i2a_ASN1_INTEGER(bio, asn1_int) _openssl_assert(result >= 0) return _bio_to_string(bio)
Set the reason of this revocation.
def set_reason(self, reason): """ Set the reason of this revocation. If :data:`reason` is ``None``, delete the reason instead. :param reason: The reason string. :type reason: :class:`bytes` or :class:`NoneType` :return: ``None`` .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons which you might pass to this method. """ if reason is None: self._delete_reason() elif not isinstance(reason, bytes): raise TypeError("reason must be None or a byte string") else: reason = reason.lower().replace(b' ', b'') reason_code = [r.lower() for r in self._crl_reasons].index(reason) new_reason_ext = _lib.ASN1_ENUMERATED_new() _openssl_assert(new_reason_ext != _ffi.NULL) new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free) set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code) _openssl_assert(set_result != _ffi.NULL) self._delete_reason() add_result = _lib.X509_REVOKED_add1_ext_i2d( self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0) _openssl_assert(add_result == 1)
Get the reason of this revocation.
def get_reason(self): """ Get the reason of this revocation. :return: The reason, or ``None`` if there is none. :rtype: bytes or NoneType .. seealso:: :meth:`all_reasons`, which gives you a list of all supported reasons this method might return. """ for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)): ext = _lib.X509_REVOKED_get_ext(self._revoked, i) obj = _lib.X509_EXTENSION_get_object(ext) if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason: bio = _new_mem_buf() print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0) if not print_result: print_result = _lib.M_ASN1_OCTET_STRING_print( bio, _lib.X509_EXTENSION_get_data(ext) ) _openssl_assert(print_result != 0) return _bio_to_string(bio)
Set the revocation timestamp.
def set_rev_date(self, when): """ Set the revocation timestamp. :param bytes when: The timestamp of the revocation, as ASN.1 TIME. :return: ``None`` """ dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked) return _set_asn1_time(dt, when)
Export as a cryptography CRL.
def to_cryptography(self): """ Export as a ``cryptography`` CRL. :rtype: ``cryptography.x509.CertificateRevocationList`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import ( _CertificateRevocationList ) backend = _get_backend() return _CertificateRevocationList(backend, self._crl)
Construct based on a cryptography * crypto_crl *.
def from_cryptography(cls, crypto_crl): """ Construct based on a ``cryptography`` *crypto_crl*. :param crypto_crl: A ``cryptography`` certificate revocation list :type crypto_crl: ``cryptography.x509.CertificateRevocationList`` :rtype: CRL .. versionadded:: 17.1.0 """ if not isinstance(crypto_crl, x509.CertificateRevocationList): raise TypeError("Must be a certificate revocation list") crl = cls() crl._crl = crypto_crl._x509_crl return crl
Return the revocations in this certificate revocation list.
def get_revoked(self): """ Return the revocations in this certificate revocation list. These revocations will be provided by value, not by reference. That means it's okay to mutate them: it won't affect this CRL. :return: The revocations in this CRL. :rtype: :class:`tuple` of :class:`Revocation` """ results = [] revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl) for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)): revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i) revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked) pyrev = Revoked.__new__(Revoked) pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free) results.append(pyrev) if results: return tuple(results)
Add a revoked ( by value not reference ) to the CRL structure
def add_revoked(self, revoked): """ Add a revoked (by value not reference) to the CRL structure This revocation will be added by value, not by reference. That means it's okay to mutate it after adding: it won't affect this CRL. :param Revoked revoked: The new revocation. :return: ``None`` """ copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked) _openssl_assert(copy != _ffi.NULL) add_result = _lib.X509_CRL_add0_revoked(self._crl, copy) _openssl_assert(add_result != 0)
Get the CRL s issuer.
def get_issuer(self): """ Get the CRL's issuer. .. versionadded:: 16.1.0 :rtype: X509Name """ _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl)) _openssl_assert(_issuer != _ffi.NULL) _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free) issuer = X509Name.__new__(X509Name) issuer._name = _issuer return issuer
Sign the CRL.
def sign(self, issuer_cert, issuer_key, digest): """ Sign the CRL. Signing a CRL enables clients to associate the CRL itself with an issuer. Before a CRL is meaningful to other OpenSSL functions, it must be signed by an issuer. This method implicitly sets the issuer's name based on the issuer certificate and private key used to sign the CRL. .. versionadded:: 16.1.0 :param X509 issuer_cert: The issuer's certificate. :param PKey issuer_key: The issuer's private key. :param bytes digest: The digest method to sign the CRL with. """ digest_obj = _lib.EVP_get_digestbyname(digest) _openssl_assert(digest_obj != _ffi.NULL) _lib.X509_CRL_set_issuer_name( self._crl, _lib.X509_get_subject_name(issuer_cert._x509)) _lib.X509_CRL_sort(self._crl) result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj) _openssl_assert(result != 0)
Export the CRL as a string.
def export(self, cert, key, type=FILETYPE_PEM, days=100, digest=_UNSPECIFIED): """ Export the CRL as a string. :param X509 cert: The certificate used to sign the CRL. :param PKey key: The key used to sign the CRL. :param int type: The export format, either :data:`FILETYPE_PEM`, :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`. :param int days: The number of days until the next update of this CRL. :param bytes digest: The name of the message digest to use (eg ``b"sha256"``). :rtype: bytes """ if not isinstance(cert, X509): raise TypeError("cert must be an X509 instance") if not isinstance(key, PKey): raise TypeError("key must be a PKey instance") if not isinstance(type, int): raise TypeError("type must be an integer") if digest is _UNSPECIFIED: raise TypeError("digest must be provided") digest_obj = _lib.EVP_get_digestbyname(digest) if digest_obj == _ffi.NULL: raise ValueError("No such digest method") bio = _lib.BIO_new(_lib.BIO_s_mem()) _openssl_assert(bio != _ffi.NULL) # A scratch time object to give different values to different CRL # fields sometime = _lib.ASN1_TIME_new() _openssl_assert(sometime != _ffi.NULL) _lib.X509_gmtime_adj(sometime, 0) _lib.X509_CRL_set_lastUpdate(self._crl, sometime) _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60) _lib.X509_CRL_set_nextUpdate(self._crl, sometime) _lib.X509_CRL_set_issuer_name( self._crl, _lib.X509_get_subject_name(cert._x509) ) sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj) if not sign_result: _raise_current_error() return dump_crl(type, self)
Returns the type name of the PKCS7 structure
def get_type_name(self): """ Returns the type name of the PKCS7 structure :return: A string with the typename """ nid = _lib.OBJ_obj2nid(self._pkcs7.type) string_type = _lib.OBJ_nid2sn(nid) return _ffi.string(string_type)
Set the certificate in the PKCS #12 structure.
def set_certificate(self, cert): """ Set the certificate in the PKCS #12 structure. :param cert: The new certificate, or :py:const:`None` to unset it. :type cert: :py:class:`X509` or :py:const:`None` :return: ``None`` """ if not isinstance(cert, X509): raise TypeError("cert must be an X509 instance") self._cert = cert
Set the certificate portion of the PKCS #12 structure.
def set_privatekey(self, pkey): """ Set the certificate portion of the PKCS #12 structure. :param pkey: The new private key, or :py:const:`None` to unset it. :type pkey: :py:class:`PKey` or :py:const:`None` :return: ``None`` """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") self._pkey = pkey
Replace or set the CA certificates within the PKCS12 object.
def set_ca_certificates(self, cacerts): """ Replace or set the CA certificates within the PKCS12 object. :param cacerts: The new CA certificates, or :py:const:`None` to unset them. :type cacerts: An iterable of :py:class:`X509` or :py:const:`None` :return: ``None`` """ if cacerts is None: self._cacerts = None else: cacerts = list(cacerts) for cert in cacerts: if not isinstance(cert, X509): raise TypeError( "iterable must only contain X509 instances" ) self._cacerts = cacerts
Set the friendly name in the PKCS #12 structure.
def set_friendlyname(self, name): """ Set the friendly name in the PKCS #12 structure. :param name: The new friendly name, or :py:const:`None` to unset. :type name: :py:class:`bytes` or :py:const:`None` :return: ``None`` """ if name is None: self._friendlyname = None elif not isinstance(name, bytes): raise TypeError( "name must be a byte string or None (not %r)" % (name,) ) self._friendlyname = name
Dump a PKCS12 object as a string.
def export(self, passphrase=None, iter=2048, maciter=1): """ Dump a PKCS12 object as a string. For more information, see the :c:func:`PKCS12_create` man page. :param passphrase: The passphrase used to encrypt the structure. Unlike some other passphrase arguments, this *must* be a string, not a callback. :type passphrase: :py:data:`bytes` :param iter: Number of times to repeat the encryption step. :type iter: :py:data:`int` :param maciter: Number of times to repeat the MAC step. :type maciter: :py:data:`int` :return: The string representation of the PKCS #12 structure. :rtype: """ passphrase = _text_to_bytes_and_warn("passphrase", passphrase) if self._cacerts is None: cacerts = _ffi.NULL else: cacerts = _lib.sk_X509_new_null() cacerts = _ffi.gc(cacerts, _lib.sk_X509_free) for cert in self._cacerts: _lib.sk_X509_push(cacerts, cert._x509) if passphrase is None: passphrase = _ffi.NULL friendlyname = self._friendlyname if friendlyname is None: friendlyname = _ffi.NULL if self._pkey is None: pkey = _ffi.NULL else: pkey = self._pkey._pkey if self._cert is None: cert = _ffi.NULL else: cert = self._cert._x509 pkcs12 = _lib.PKCS12_create( passphrase, friendlyname, pkey, cert, cacerts, _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC, _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC, iter, maciter, 0) if pkcs12 == _ffi.NULL: _raise_current_error() pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free) bio = _new_mem_buf() _lib.i2d_PKCS12_bio(bio, pkcs12) return _bio_to_string(bio)
Sign the certificate request with this key and digest type.
def sign(self, pkey, digest): """ Sign the certificate request with this key and digest type. :param pkey: The private key to sign with. :type pkey: :py:class:`PKey` :param digest: The message digest to use. :type digest: :py:class:`bytes` :return: ``None`` """ if pkey._only_public: raise ValueError("Key has only public part") if not pkey._initialized: raise ValueError("Key is uninitialized") digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest)) if digest_obj == _ffi.NULL: raise ValueError("No such digest method") sign_result = _lib.NETSCAPE_SPKI_sign( self._spki, pkey._pkey, digest_obj ) _openssl_assert(sign_result > 0)
Verifies a signature on a certificate request.
def verify(self, key): """ Verifies a signature on a certificate request. :param PKey key: The public key that signature is supposedly from. :return: ``True`` if the signature is correct. :rtype: bool :raises OpenSSL.crypto.Error: If the signature is invalid, or there was a problem verifying the signature. """ answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey) if answer <= 0: _raise_current_error() return True
Generate a base64 encoded representation of this SPKI object.
def b64_encode(self): """ Generate a base64 encoded representation of this SPKI object. :return: The base64 encoded string. :rtype: :py:class:`bytes` """ encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki) result = _ffi.string(encoded) _lib.OPENSSL_free(encoded) return result
Get the public key of this certificate.
def get_pubkey(self): """ Get the public key of this certificate. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki) _openssl_assert(pkey._pkey != _ffi.NULL) pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
Set the public key of the certificate
def set_pubkey(self, pkey): """ Set the public key of the certificate :param pkey: The public key :return: ``None`` """ set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey) _openssl_assert(set_result == 1)
Convert an OpenSSL library failure into a Python exception.
def exception_from_error_queue(exception_type): """ Convert an OpenSSL library failure into a Python exception. When a call to the native OpenSSL library fails, this is usually signalled by the return value, and an error code is stored in an error queue associated with the current thread. The err library provides functions to obtain these error codes and textual error messages. """ errors = [] while True: error = lib.ERR_get_error() if error == 0: break errors.append(( text(lib.ERR_lib_error_string(error)), text(lib.ERR_func_error_string(error)), text(lib.ERR_reason_error_string(error)))) raise exception_type(errors)
Convert: py: class: bytes or: py: class: unicode to the native: py: class: str type using UTF - 8 encoding if conversion is necessary.
def native(s): """ Convert :py:class:`bytes` or :py:class:`unicode` to the native :py:class:`str` type, using UTF-8 encoding if conversion is necessary. :raise UnicodeError: The input string is not UTF-8 decodeable. :raise TypeError: The input is neither :py:class:`bytes` nor :py:class:`unicode`. """ if not isinstance(s, (binary_type, text_type)): raise TypeError("%r is neither bytes nor unicode" % s) if PY3: if isinstance(s, binary_type): return s.decode("utf-8") else: if isinstance(s, text_type): return s.encode("utf-8") return s
Convert a Python string to a: py: class: bytes string identifying the same path and which can be passed into an OpenSSL API accepting a filename.
def path_string(s): """ Convert a Python string to a :py:class:`bytes` string identifying the same path and which can be passed into an OpenSSL API accepting a filename. :param s: An instance of :py:class:`bytes` or :py:class:`unicode`. :return: An instance of :py:class:`bytes`. """ if isinstance(s, binary_type): return s elif isinstance(s, text_type): return s.encode(sys.getfilesystemencoding()) else: raise TypeError("Path must be represented as bytes or unicode string")
If obj is text emit a warning that it should be bytes instead and try to convert it to bytes automatically.
def text_to_bytes_and_warn(label, obj): """ If ``obj`` is text, emit a warning that it should be bytes instead and try to convert it to bytes automatically. :param str label: The name of the parameter from which ``obj`` was taken (so a developer can easily find the source of the problem and correct it). :return: If ``obj`` is the text string type, a ``bytes`` object giving the UTF-8 encoding of that text is returned. Otherwise, ``obj`` itself is returned. """ if isinstance(obj, text_type): warnings.warn( _TEXT_WARNING.format(label), category=DeprecationWarning, stacklevel=3 ) return obj.encode('utf-8') return obj
Mix bytes from * string * into the PRNG state.
def add(buffer, entropy): """ Mix bytes from *string* into the PRNG state. The *entropy* argument is (the lower bound of) an estimate of how much randomness is contained in *string*, measured in bytes. For more information, see e.g. :rfc:`1750`. This function is only relevant if you are forking Python processes and need to reseed the CSPRNG after fork. :param buffer: Buffer with random data. :param entropy: The entropy (in bytes) measurement of the buffer. :return: :obj:`None` """ if not isinstance(buffer, bytes): raise TypeError("buffer must be a byte string") if not isinstance(entropy, int): raise TypeError("entropy must be an integer") _lib.RAND_add(buffer, len(buffer), entropy)
This is the other part of the shutdown () workaround. Since servers create new sockets we have to infect them with our magic.: )
def accept(self): """ This is the other part of the shutdown() workaround. Since servers create new sockets, we have to infect them with our magic. :) """ c, a = self.__dict__["conn"].accept() return (SSLWrapper(c), a)
We need to use socket. _fileobject Because SSL. Connection doesn t have a dup. Not exactly sure WHY this is but this is backed up by comments in socket. py and SSL/ connection. c
def setup(self): """ We need to use socket._fileobject Because SSL.Connection doesn't have a 'dup'. Not exactly sure WHY this is, but this is backed up by comments in socket.py and SSL/connection.c """ self.connection = self.request # for doPOST self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
Run an SNI - enabled server which selects between a few certificates in a C { dict } based on the handshake request it receives from a client.
def main(): """ Run an SNI-enabled server which selects between a few certificates in a C{dict} based on the handshake request it receives from a client. """ port = socket() port.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) port.bind(('', 8443)) port.listen(3) print('Accepting...', end="") stdout.flush() server, addr = port.accept() print('accepted', addr) server_context = Context(TLSv1_METHOD) server_context.set_tlsext_servername_callback(pick_certificate) server_ssl = Connection(server_context, server) server_ssl.set_accept_state() server_ssl.do_handshake() server.close()
Internal helper to provide color names.
def _print_token_factory(col): """Internal helper to provide color names.""" def _helper(msg): style = style_from_dict({ Token.Color: col, }) tokens = [ (Token.Color, msg) ] print_tokens(tokens, style=style) def _helper_no_terminal(msg): # workaround if we have no terminal print(msg) if sys.stdout.isatty(): return _helper else: return _helper_no_terminal
Return extra config options to be passed to the TrelloIssue class
def get_service_metadata(self): """ Return extra config options to be passed to the TrelloIssue class """ return { 'import_labels_as_tags': self.config.get('import_labels_as_tags', False, asbool), 'label_template': self.config.get('label_template', DEFAULT_LABEL_TEMPLATE), }
Returns a list of dicts representing issues from a remote service.
def issues(self): """ Returns a list of dicts representing issues from a remote service. """ for board in self.get_boards(): for lst in self.get_lists(board['id']): listextra = dict(boardname=board['name'], listname=lst['name']) for card in self.get_cards(lst['id']): issue = self.get_issue_for_record(card, extra=listextra) issue.update_extra({"annotations": self.annotations(card)}) yield issue
A wrapper around get_comments that build the taskwarrior annotations.
def annotations(self, card_json): """ A wrapper around get_comments that build the taskwarrior annotations. """ comments = self.get_comments(card_json['id']) annotations = self.build_annotations( ((c['memberCreator']['username'], c['data']['text']) for c in comments), card_json["shortUrl"]) return annotations
Get the list of boards to pull cards from. If the user gave a value to trello. include_boards use that otherwise ask the Trello API for the user s boards.
def get_boards(self): """ Get the list of boards to pull cards from. If the user gave a value to trello.include_boards use that, otherwise ask the Trello API for the user's boards. """ if 'include_boards' in self.config: for boardid in self.config.get('include_boards', to_type=aslist): # Get the board name yield self.api_request( "/1/boards/{id}".format(id=boardid), fields='name') else: boards = self.api_request("/1/members/me/boards", fields='name') for board in boards: yield board
Returns a list of the filtered lists for the given board This filters the trello lists according to the configuration values of trello. include_lists and trello. exclude_lists.
def get_lists(self, board): """ Returns a list of the filtered lists for the given board This filters the trello lists according to the configuration values of trello.include_lists and trello.exclude_lists. """ lists = self.api_request( "/1/boards/{board_id}/lists/open".format(board_id=board), fields='name') include_lists = self.config.get('include_lists', to_type=aslist) if include_lists: lists = [l for l in lists if l['name'] in include_lists] exclude_lists = self.config.get('exclude_lists', to_type=aslist) if exclude_lists: lists = [l for l in lists if l['name'] not in exclude_lists] return lists
Returns an iterator for the cards in a given list filtered according to configuration values of trello. only_if_assigned and trello. also_unassigned
def get_cards(self, list_id): """ Returns an iterator for the cards in a given list, filtered according to configuration values of trello.only_if_assigned and trello.also_unassigned """ params = {'fields': 'name,idShort,shortLink,shortUrl,url,labels,due'} member = self.config.get('only_if_assigned', None) unassigned = self.config.get('also_unassigned', False, asbool) if member is not None: params['members'] = 'true' params['member_fields'] = 'username' cards = self.api_request( "/1/lists/{list_id}/cards/open".format(list_id=list_id), **params) for card in cards: if (member is None or member in [m['username'] for m in card['members']] or (unassigned and not card['members'])): yield card
Returns an iterator for the comments on a certain card.
def get_comments(self, card_id): """ Returns an iterator for the comments on a certain card. """ params = {'filter': 'commentCard', 'memberCreator_fields': 'username'} comments = self.api_request( "/1/cards/{card_id}/actions".format(card_id=card_id), **params) for comment in comments: assert comment['type'] == 'commentCard' yield comment
Make a trello API request. This takes an absolute url ( without protocol and host ) and a list of argumnets and return a GET request with the key and token from the configuration
def api_request(self, url, **params): """ Make a trello API request. This takes an absolute url (without protocol and host) and a list of argumnets and return a GET request with the key and token from the configuration """ params['key'] = self.config.get('api_key'), params['token'] = self.config.get('token'), url = "https://api.trello.com" + url return self.json_response(requests.get(url, params=params))
Grab all the issues
def get_issues(self, repo, keys): """ Grab all the issues """ key1, key2 = keys key3 = key1[:-1] # Just the singular form of key1 url = self.base_url + "/api/0/" + repo + "/" + key1 response = self.session.get(url, params=dict(status='Open')) if not bool(response): error = response.json() code = error['error_code'] if code == 'ETRACKERDISABLED': return [] else: raise IOError('Failed to talk to %r %r' % (url, error)) issues = [] for result in response.json()[key2]: idx = six.text_type(result['id']) result['html_url'] = "/".join([self.base_url, repo, key3, idx]) issues.append((repo, result)) return issues
Approach:
def get_issue_generator(self, user_id, project_id, project_name): """ Approach: 1. Get user ID from bugwarriorrc file 2. Get list of tickets from /user-tasks for a given project 3. For each ticket/task returned from #2, get ticket/task info and check if logged-in user is primary (look at `is_owner` and `user_id`) """ user_tasks_data = self.call_api( "/projects/" + six.text_type(project_id) + "/user-tasks") for key, task in enumerate(user_tasks_data): assigned_task = self.get_task_dict(project_id, key, task) if assigned_task: log.debug( " Adding '" + assigned_task['description'] + "' to task list.") yield assigned_task
Build the full url to the API endpoint
def _api_url(self, path, **context): """ Build the full url to the API endpoint """ if self.host == 'github.com': baseurl = "https://api.github.com" else: baseurl = "https://{}/api/v3".format(self.host) return baseurl + path.format(**context)
Run a generic issue/ PR query
def get_query(self, query): """Run a generic issue/PR query""" url = self._api_url( "/search/issues?q={query}&per_page=100", query=query) return self._getter(url, subkey='items')
Pagination utility. Obnoxious.
def _getter(self, url, subkey=None): """ Pagination utility. Obnoxious. """ kwargs = {} if 'basic' in self.auth: kwargs['auth'] = self.auth['basic'] results = [] link = dict(next=url) while 'next' in link: response = self.session.get(link['next'], **kwargs) # Warn about the mis-leading 404 error code. See: # https://github.com/ralphbean/bugwarrior/issues/374 if response.status_code == 404 and 'token' in self.auth: log.warn("A '404' from github may indicate an auth " "failure. Make sure both that your token is correct " "and that it has 'public_repo' and not 'public " "access' rights.") json_res = self.json_response(response) if subkey is not None: json_res = json_res[subkey] results += json_res link = self._link_field_to_dict(response.headers.get('link', None)) return results
Utility for ripping apart github s Link header field. It s kind of ugly.
def _link_field_to_dict(field): """ Utility for ripping apart github's Link header field. It's kind of ugly. """ if not field: return dict() return dict([ ( part.split('; ')[1][5:-1], part.split('; ')[0][1:-1], ) for part in field.split(', ') ])
Grab all the issues
def get_owned_repo_issues(self, tag): """ Grab all the issues """ issues = {} for issue in self.client.get_issues(*tag.split('/')): issues[issue['url']] = (tag, issue) return issues
Grab all issues matching a github query
def get_query(self, query): """ Grab all issues matching a github query """ issues = {} for issue in self.client.get_query(query): url = issue['html_url'] try: repo = self.get_repository_from_issue(issue) except ValueError as e: log.critical(e) else: issues[url] = (repo, issue) return issues
Grab all the pull requests
def _reqs(self, tag): """ Grab all the pull requests """ return [ (tag, i) for i in self.client.get_pulls(*tag.split('/')) ]
This worker function is separated out from the main: func: aggregate_issues func only so that we can use multiprocessing on it for speed reasons.
def _aggregate_issues(conf, main_section, target, queue, service_name): """ This worker function is separated out from the main :func:`aggregate_issues` func only so that we can use multiprocessing on it for speed reasons. """ start = time.time() try: service = get_service(service_name)(conf, main_section, target) issue_count = 0 for issue in service.issues(): queue.put(issue) issue_count += 1 except SystemExit as e: log.critical(str(e)) queue.put((SERVICE_FINISHED_ERROR, (target, e))) except BaseException as e: if hasattr(e, 'request') and e.request: # Exceptions raised by requests library have the HTTP request # object stored as attribute. The request can have hooks attached # to it, and we need to remove them, as there can be unpickleable # methods. There is no one left to call these hooks anyway. e.request.hooks = {} log.exception("Worker for [%s] failed: %s" % (target, e)) queue.put((SERVICE_FINISHED_ERROR, (target, e))) else: queue.put((SERVICE_FINISHED_OK, (target, issue_count, ))) finally: duration = time.time() - start log.info("Done with [%s] in %fs" % (target, duration))
Return all issues from every target.
def aggregate_issues(conf, main_section, debug): """ Return all issues from every target. """ log.info("Starting to aggregate remote issues.") # Create and call service objects for every target in the config targets = aslist(conf.get(main_section, 'targets')) queue = multiprocessing.Queue() log.info("Spawning %i workers." % len(targets)) processes = [] if debug: for target in targets: _aggregate_issues( conf, main_section, target, queue, conf.get(target, 'service') ) else: for target in targets: proc = multiprocessing.Process( target=_aggregate_issues, args=(conf, main_section, target, queue, conf.get(target, 'service')) ) proc.start() processes.append(proc) # Sleep for 1 second here to try and avoid a race condition where # all N workers start up and ask the gpg-agent process for # information at the same time. This causes gpg-agent to fumble # and tell some of our workers some incomplete things. time.sleep(1) currently_running = len(targets) while currently_running > 0: issue = queue.get(True) if isinstance(issue, tuple): completion_type, args = issue if completion_type == SERVICE_FINISHED_ERROR: target, e = args log.info("Terminating workers") for process in processes: process.terminate() raise RuntimeError( "critical error in target '{}'".format(target)) currently_running -= 1 continue yield issue log.info("Done aggregating remote issues.")
Return a main config value or default if it does not exist.
def _get_config_or_default(self, key, default, as_type=lambda x: x): """Return a main config value, or default if it does not exist.""" if self.main_config.has_option(self.main_section, key): return as_type(self.main_config.get(self.main_section, key)) return default
Get any defined templates for configuration values.
def get_templates(self): """ Get any defined templates for configuration values. Users can override the value of any Taskwarrior field using this feature on a per-key basis. The key should be the name of the field to you would like to configure the value of, followed by '_template', and the value should be a Jinja template generating the field's value. As context variables, all fields on the taskwarrior record are available. For example, to prefix the returned project name for tickets returned by a service with 'workproject_', you could add an entry reading: project_template = workproject_{{project}} Or, if you'd simply like to override the returned project name for all tickets incoming from a specific service, you could add an entry like: project_template = myprojectname The above would cause all issues to recieve a project name of 'myprojectname', regardless of what the project name of the generated issue was. """ templates = {} for key in six.iterkeys(Task.FIELDS): template_key = '%s_template' % key if template_key in self.config: templates[key] = self.config.get(template_key) return templates
Validate generic options for a particular target
def validate_config(cls, service_config, target): """ Validate generic options for a particular target """ if service_config.has_option(target, 'only_if_assigned'): die("[%s] has an 'only_if_assigned' option. Should be " "'%s.only_if_assigned'." % (target, cls.CONFIG_PREFIX)) if service_config.has_option(target, 'also_unassigned'): die("[%s] has an 'also_unassigned' option. Should be " "'%s.also_unassigned'." % (target, cls.CONFIG_PREFIX)) if service_config.has_option(target, 'default_priority'): die("[%s] has a 'default_priority' option. Should be " "'%s.default_priority'." % (target, cls.CONFIG_PREFIX)) if service_config.has_option(target, 'add_tags'): die("[%s] has an 'add_tags' option. Should be " "'%s.add_tags'." % (target, cls.CONFIG_PREFIX))
Return true if the issue in question should be included
def include(self, issue): """ Return true if the issue in question should be included """ only_if_assigned = self.config.get('only_if_assigned', None) if only_if_assigned: owner = self.get_owner(issue) include_owners = [only_if_assigned] if self.config.get('also_unassigned', None, asbool): include_owners.append(None) return owner in include_owners only_if_author = self.config.get('only_if_author', None) if only_if_author: return self.get_author(issue) == only_if_author return True
Make a RST - compatible table
def make_table(grid): """ Make a RST-compatible table From http://stackoverflow.com/a/12539081 """ cell_width = 2 + max( reduce( lambda x, y: x+y, [[len(item) for item in row] for row in grid], [] ) ) num_cols = len(grid[0]) rst = table_div(num_cols, cell_width, 0) header_flag = 1 for row in grid: rst = rst + '| ' + '| '.join( [normalize_cell(x, cell_width-1) for x in row] ) + '|\n' rst = rst + table_div(num_cols, cell_width, header_flag) header_flag = 0 return rst
Retrieve the sensitive password for a service by:
def get_service_password(service, username, oracle=None, interactive=False): """ Retrieve the sensitive password for a service by: * retrieving password from a secure store (@oracle:use_keyring, default) * asking the password from the user (@oracle:ask_password, interactive) * executing a command and use the output as password (@oracle:eval:<command>) Note that the keyring may or may not be locked which requires that the user provides a password (interactive mode). :param service: Service name, may be key into secure store (as string). :param username: Username for the service (as string). :param oracle: Hint which password oracle strategy to use. :return: Retrieved password (as string) .. seealso:: https://bitbucket.org/kang/python-keyring-lib """ import getpass password = None if not oracle or oracle == "@oracle:use_keyring": keyring = get_keyring() password = keyring.get_password(service, username) if interactive and password is None: # -- LEARNING MODE: Password is not stored in keyring yet. oracle = "@oracle:ask_password" password = get_service_password(service, username, oracle, interactive=True) if password: keyring.set_password(service, username, password) elif interactive and oracle == "@oracle:ask_password": prompt = "%s password: " % service password = getpass.getpass(prompt) elif oracle.startswith('@oracle:eval:'): command = oracle[13:] return oracle_eval(command) if password is None: die("MISSING PASSWORD: oracle='%s', interactive=%s for service=%s" % (oracle, interactive, service)) return password
Retrieve password from the given command
def oracle_eval(command): """ Retrieve password from the given command """ p = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() if p.returncode == 0: return p.stdout.readline().strip().decode('utf-8') else: die( "Error retrieving password: `{command}` returned '{error}'".format( command=command, error=p.stderr.read().strip()))