diff options
| author | Alex Gaynor <alex.gaynor@gmail.com> | 2023-03-24 17:23:13 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-03-24 21:23:13 +0000 |
| commit | 7e62312797cc018891fa4ffcfd9485fafacd3dfe (patch) | |
| tree | 7db5681b512155c2a91d1c65f9067dfc42753f0d | |
| parent | 7e19ff0229a0a8d9263e126a01b11299221a0741 (diff) | |
| download | cryptography-7e62312797cc018891fa4ffcfd9485fafacd3dfe.tar.gz | |
Upgrade to pyo3 0.18 (#6935)
* Upgrade to pyo3 0.16
* Upgrade to pyo3 0.17
* Upgrade to pyo3 0.18
| -rw-r--r-- | MANIFEST.in | 2 | ||||
| -rw-r--r-- | setup.py | 2 | ||||
| -rw-r--r-- | src/rust/Cargo.lock | 90 | ||||
| -rw-r--r-- | src/rust/Cargo.toml | 2 | ||||
| -rw-r--r-- | src/rust/src/asn1.rs | 4 | ||||
| -rw-r--r-- | src/rust/src/backend/x25519.rs | 42 | ||||
| -rw-r--r-- | src/rust/src/error.rs | 23 | ||||
| -rw-r--r-- | src/rust/src/lib.rs | 3 | ||||
| -rw-r--r-- | src/rust/src/oid.rs | 10 | ||||
| -rw-r--r-- | src/rust/src/pkcs7.rs | 2 | ||||
| -rw-r--r-- | src/rust/src/x509/certificate.rs | 22 | ||||
| -rw-r--r-- | src/rust/src/x509/common.rs | 26 | ||||
| -rw-r--r-- | src/rust/src/x509/crl.rs | 79 | ||||
| -rw-r--r-- | src/rust/src/x509/csr.rs | 15 | ||||
| -rw-r--r-- | src/rust/src/x509/extensions.rs | 2 | ||||
| -rw-r--r-- | src/rust/src/x509/ocsp_req.rs | 6 | ||||
| -rw-r--r-- | src/rust/src/x509/ocsp_resp.rs | 39 | ||||
| -rw-r--r-- | src/rust/src/x509/sct.rs | 43 | ||||
| -rw-r--r-- | src/rust/src/x509/sign.rs | 26 | ||||
| -rw-r--r-- | tests/hazmat/primitives/test_pkcs7.py | 2 |
20 files changed, 196 insertions, 244 deletions
diff --git a/MANIFEST.in b/MANIFEST.in index c17103312..2417dd9d3 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -16,6 +16,8 @@ prune docs/_build recursive-include tests *.py exclude vectors recursive-exclude vectors * +exclude src/rust/target +recursive-exclude src/rust/target * recursive-exclude .github * @@ -55,7 +55,7 @@ try: features=( [] if platform.python_implementation() == "PyPy" - else ["pyo3/abi3-py36"] + else ["pyo3/abi3-py37"] ), rust_version=">=1.56.0", ) diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 72a8c60a8..2aabfbb66 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -209,24 +209,10 @@ dependencies = [ [[package]] name = "indoc" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47741a8bc60fb26eb8d6e0238bbb26d8575ff623fdc97b1a2c00c050b9684ed8" -dependencies = [ - "indoc-impl", - "proc-macro-hack", -] - -[[package]] -name = "indoc-impl" -version = "0.3.6" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce046d161f000fffde5f432a0d034d0341dc152643b2598ed5bfce44c4f3a8f0" +checksum = "e7906a9fababaeacb774f72410e497a1d18de916322e33797bb2cd29baa23c9e" dependencies = [ - "proc-macro-hack", - "proc-macro2", - "quote", - "syn", "unindent", ] @@ -283,6 +269,15 @@ dependencies = [ ] [[package]] +name = "memoffset" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1" +dependencies = [ + "autocfg", +] + +[[package]] name = "num-integer" version = "0.1.45" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -395,25 +390,6 @@ dependencies = [ ] [[package]] -name = "paste" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45ca20c77d80be666aef2b45486da86238fabe33e38306bd3118fe4af33fa880" -dependencies = [ - "paste-impl", - "proc-macro-hack", -] - -[[package]] -name = "paste-impl" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a7db200b97ef370c8e6de0088252f7e0dfff7d047a28528e47456c0fc98b6" -dependencies = [ - "proc-macro-hack", -] - -[[package]] name = "pem" version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -453,12 +429,6 @@ dependencies = [ ] [[package]] -name = "proc-macro-hack" -version = "0.5.20+deprecated" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" - -[[package]] name = "proc-macro2" version = "1.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -469,35 +439,48 @@ dependencies = [ [[package]] name = "pyo3" -version = "0.15.2" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d41d50a7271e08c7c8a54cd24af5d62f73ee3a6f6a314215281ebdec421d5752" +checksum = "06a3d8e8a46ab2738109347433cb7b96dffda2e4a218b03ef27090238886b147" dependencies = [ "cfg-if", "indoc", "libc", + "memoffset", "parking_lot", - "paste", "pyo3-build-config", + "pyo3-ffi", "pyo3-macros", "unindent", ] [[package]] name = "pyo3-build-config" -version = "0.15.2" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "779239fc40b8e18bc8416d3a37d280ca9b9fb04bda54b98037bb6748595c2410" +checksum = "75439f995d07ddfad42b192dfcf3bc66a7ecfd8b4a1f5f6f046aa5c2c5d7677d" dependencies = [ "once_cell", + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839526a5c07a17ff44823679b68add4a58004de00512a95b6c1c98a6dcac0ee5" +dependencies = [ + "libc", + "pyo3-build-config", ] [[package]] name = "pyo3-macros" -version = "0.15.2" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b247e8c664be87998d8628e86f282c25066165f1f8dda66100c48202fdb93a" +checksum = "bd44cf207476c6a9760c4653559be4f206efafb924d3e4cbf2721475fc0d6cc5" dependencies = [ + "proc-macro2", "pyo3-macros-backend", "quote", "syn", @@ -505,12 +488,11 @@ dependencies = [ [[package]] name = "pyo3-macros-backend" -version = "0.15.2" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a8c2812c412e00e641d99eeb79dd478317d981d938aa60325dfa7157b607095" +checksum = "dc1f43d8e30460f36350d18631ccf85ded64c059829208fe680904c65bcd0a4c" dependencies = [ "proc-macro2", - "pyo3-build-config", "quote", "syn", ] @@ -563,6 +545,12 @@ dependencies = [ ] [[package]] +name = "target-lexicon" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c02424087780c9b71cc96799eaeddff35af2bc513278cda5c99fc1f5d026d3c1" + +[[package]] name = "termcolor" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 2c3e1ae93..5de812feb 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -9,7 +9,7 @@ rust-version = "1.56.0" [dependencies] once_cell = "1" -pyo3 = { version = "0.15.2" } +pyo3 = { version = "0.18" } asn1 = { version = "0.13.0", default-features = false, features = ["const-generics"] } pem = "1.1" chrono = { version = "0.4.24", default-features = false, features = ["alloc", "clock"] } diff --git a/src/rust/src/asn1.rs b/src/rust/src/asn1.rs index 0bc57341e..9d034ab77 100644 --- a/src/rust/src/asn1.rs +++ b/src/rust/src/asn1.rs @@ -105,9 +105,9 @@ pub(crate) fn encode_der_data<'p>( .import("cryptography.hazmat.primitives.serialization")? .getattr(crate::intern!(py, "Encoding"))?; - if encoding == encoding_class.getattr(crate::intern!(py, "DER"))? { + if encoding.is(encoding_class.getattr(crate::intern!(py, "DER"))?) { Ok(pyo3::types::PyBytes::new(py, &data)) - } else if encoding == encoding_class.getattr(crate::intern!(py, "PEM"))? { + } else if encoding.is(encoding_class.getattr(crate::intern!(py, "PEM"))?) { Ok(pyo3::types::PyBytes::new( py, &pem::encode_config( diff --git a/src/rust/src/backend/x25519.rs b/src/rust/src/backend/x25519.rs index 96a2c7a5c..72649ec7b 100644 --- a/src/rust/src/backend/x25519.rs +++ b/src/rust/src/backend/x25519.rs @@ -118,14 +118,14 @@ impl X25519PrivateKey { .getattr(crate::intern!(py, "BestAvailableEncryption"))? .extract()?; - if !encoding_class.is_instance(encoding)? { + if !encoding.is_instance(encoding_class)? { return Err(CryptographyError::from( pyo3::exceptions::PyTypeError::new_err( "encoding must be an item from the Encoding enum", ), )); } - if !private_format_class.is_instance(format)? { + if !format.is_instance(private_format_class)? { return Err(CryptographyError::from( pyo3::exceptions::PyTypeError::new_err( "format must be an item from the PrivateFormat enum", @@ -133,12 +133,12 @@ impl X25519PrivateKey { )); } - if encoding == encoding_class.getattr(crate::intern!(py, "Raw"))? - || format == private_format_class.getattr(crate::intern!(py, "Raw"))? + if encoding.is(encoding_class.getattr(crate::intern!(py, "Raw"))?) + || format.is(private_format_class.getattr(crate::intern!(py, "Raw"))?) { - if encoding != encoding_class.getattr(crate::intern!(py, "Raw"))? - || format != private_format_class.getattr(crate::intern!(py, "Raw"))? - || !no_encryption_class.is_instance(encryption_algorithm)? + if !encoding.is(encoding_class.getattr(crate::intern!(py, "Raw"))?) + || !format.is(private_format_class.getattr(crate::intern!(py, "Raw"))?) + || !encryption_algorithm.is_instance(no_encryption_class)? { return Err(CryptographyError::from(pyo3::exceptions::PyValueError::new_err( "When using Raw both encoding and format must be Raw and encryption_algorithm must be NoEncryption()" @@ -148,9 +148,9 @@ impl X25519PrivateKey { return Ok(pyo3::types::PyBytes::new(py, &raw_bytes)); } - let password = if no_encryption_class.is_instance(encryption_algorithm)? { + let password = if encryption_algorithm.is_instance(no_encryption_class)? { b"" - } else if best_available_encryption_class.is_instance(encryption_algorithm)? { + } else if encryption_algorithm.is_instance(best_available_encryption_class)? { encryption_algorithm .getattr(crate::intern!(py, "password"))? .extract::<&[u8]>()? @@ -170,8 +170,8 @@ impl X25519PrivateKey { )); } - if format == private_format_class.getattr(crate::intern!(py, "PKCS8"))? { - if encoding == encoding_class.getattr(crate::intern!(py, "PEM"))? { + if format.is(private_format_class.getattr(crate::intern!(py, "PKCS8"))?) { + if encoding.is(encoding_class.getattr(crate::intern!(py, "PEM"))?) { let pem_bytes = if password.is_empty() { self.pkey.private_key_to_pem_pkcs8()? } else { @@ -181,7 +181,7 @@ impl X25519PrivateKey { )? }; return Ok(pyo3::types::PyBytes::new(py, &pem_bytes)); - } else if encoding == encoding_class.getattr(crate::intern!(py, "DER"))? { + } else if encoding.is(encoding_class.getattr(crate::intern!(py, "DER"))?) { let der_bytes = if password.is_empty() { self.pkey.private_key_to_pkcs8()? } else { @@ -228,14 +228,14 @@ impl X25519PublicKey { .getattr(crate::intern!(py, "PublicFormat"))? .extract()?; - if !encoding_class.is_instance(encoding)? { + if !encoding.is_instance(encoding_class)? { return Err(CryptographyError::from( pyo3::exceptions::PyTypeError::new_err( "encoding must be an item from the Encoding enum", ), )); } - if !public_format_class.is_instance(format)? { + if !format.is_instance(public_format_class)? { return Err(CryptographyError::from( pyo3::exceptions::PyTypeError::new_err( "format must be an item from the PublicFormat enum", @@ -243,11 +243,11 @@ impl X25519PublicKey { )); } - if encoding == encoding_class.getattr(crate::intern!(py, "Raw"))? - || format == public_format_class.getattr(crate::intern!(py, "Raw"))? + if encoding.is(encoding_class.getattr(crate::intern!(py, "Raw"))?) + || format.is(public_format_class.getattr(crate::intern!(py, "Raw"))?) { - if encoding != encoding_class.getattr(crate::intern!(py, "Raw"))? - || format != public_format_class.getattr(crate::intern!(py, "Raw"))? + if !encoding.is(encoding_class.getattr(crate::intern!(py, "Raw"))?) + || !format.is(public_format_class.getattr(crate::intern!(py, "Raw"))?) { return Err(CryptographyError::from( pyo3::exceptions::PyValueError::new_err( @@ -260,11 +260,11 @@ impl X25519PublicKey { } // SubjectPublicKeyInfo + PEM/DER - if format == public_format_class.getattr(crate::intern!(py, "SubjectPublicKeyInfo"))? { - if encoding == encoding_class.getattr(crate::intern!(py, "PEM"))? { + if format.is(public_format_class.getattr(crate::intern!(py, "SubjectPublicKeyInfo"))?) { + if encoding.is(encoding_class.getattr(crate::intern!(py, "PEM"))?) { let pem_bytes = self.pkey.public_key_to_pem()?; return Ok(pyo3::types::PyBytes::new(py, &pem_bytes)); - } else if encoding == encoding_class.getattr(crate::intern!(py, "DER"))? { + } else if encoding.is(encoding_class.getattr(crate::intern!(py, "DER"))?) { let der_bytes = self.pkey.public_key_to_der()?; return Ok(pyo3::types::PyBytes::new(py, &der_bytes)); } else { diff --git a/src/rust/src/error.rs b/src/rust/src/error.rs index 6c6440c8d..35713bbab 100644 --- a/src/rust/src/error.rs +++ b/src/rust/src/error.rs @@ -62,10 +62,7 @@ impl From<CryptographyError> for pyo3::PyErr { ) } CryptographyError::Py(py_error) => py_error, - CryptographyError::OpenSSL(error_stack) => { - let gil = pyo3::Python::acquire_gil(); - let py = gil.python(); - + CryptographyError::OpenSSL(error_stack) => pyo3::Python::with_gil(|py| { let internal_error = py .import("cryptography.exceptions") .expect("Failed to import cryptography module") @@ -81,21 +78,21 @@ impl From<CryptographyError> for pyo3::PyErr { ) .expect("Failed to append to list"); } - pyo3::PyErr::from_instance( + pyo3::PyErr::from_value( internal_error .call1(( "Unknown OpenSSL error. This error is commonly encountered - when another library is not cleaning up the OpenSSL error - stack. If you are using cryptography with another library - that uses OpenSSL try disabling it before reporting a bug. - Otherwise please file an issue at - https://github.com/pyca/cryptography/issues with - information on how to reproduce this.", + when another library is not cleaning up the OpenSSL error + stack. If you are using cryptography with another library + that uses OpenSSL try disabling it before reporting a bug. + Otherwise please file an issue at + https://github.com/pyca/cryptography/issues with + information on how to reproduce this.", errors, )) .expect("Failed to create InternalError"), ) - } + }), } } } @@ -130,7 +127,7 @@ mod tests { CryptographyError::Asn1Write(asn1::WriteError::AllocationError) )); let py_e: pyo3::PyErr = e.into(); - assert!(py_e.is_instance::<pyo3::exceptions::PyMemoryError>(py)); + assert!(py_e.is_instance_of::<pyo3::exceptions::PyMemoryError>(py)); let e: CryptographyError = pyo3::PyDowncastError::new(py.None().as_ref(py), "abc").into(); diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs index 2ec4e66bb..dae286cc0 100644 --- a/src/rust/src/lib.rs +++ b/src/rust/src/lib.rs @@ -128,10 +128,7 @@ impl OpenSSLError { fn _lib_reason_match(&self, lib: i32, reason: i32) -> bool { self.e.library_code() == lib && self.e.reason_code() == reason } -} -#[pyo3::prelude::pyproto] -impl pyo3::PyObjectProtocol for OpenSSLError { fn __repr__(&self) -> pyo3::PyResult<String> { Ok(format!( "<OpenSSLError(code={}, lib={}, reason={}, reason_text={})>", diff --git a/src/rust/src/oid.rs b/src/rust/src/oid.rs index a13668579..43d26802a 100644 --- a/src/rust/src/oid.rs +++ b/src/rust/src/oid.rs @@ -39,14 +39,8 @@ impl ObjectIdentifier { fn __deepcopy__(slf: pyo3::PyRef<'_, Self>, _memo: pyo3::PyObject) -> pyo3::PyRef<'_, Self> { slf } -} - -#[pyo3::prelude::pyproto] -impl pyo3::PyObjectProtocol for ObjectIdentifier { - fn __repr__(&self) -> pyo3::PyResult<String> { - let gil = pyo3::Python::acquire_gil(); - let py = gil.python(); + fn __repr__(&self, py: pyo3::Python<'_>) -> pyo3::PyResult<String> { let self_clone = pyo3::PyCell::new( py, ObjectIdentifier { @@ -62,7 +56,7 @@ impl pyo3::PyObjectProtocol for ObjectIdentifier { fn __richcmp__( &self, - other: pyo3::PyRef<ObjectIdentifier>, + other: pyo3::PyRef<'_, ObjectIdentifier>, op: pyo3::basic::CompareOp, ) -> pyo3::PyResult<bool> { match op { diff --git a/src/rust/src/pkcs7.rs b/src/rust/src/pkcs7.rs index c23300ac4..53e479e5b 100644 --- a/src/rust/src/pkcs7.rs +++ b/src/rust/src/pkcs7.rs @@ -298,7 +298,7 @@ fn sign_and_serialize<'p>( .import("cryptography.hazmat.primitives.serialization")? .getattr(crate::intern!(py, "Encoding"))?; - if encoding == encoding_class.getattr(crate::intern!(py, "SMIME"))? { + if encoding.is(encoding_class.getattr(crate::intern!(py, "SMIME"))?) { let mic_algs = digest_algs .iter() .map(|d| OIDS_TO_MIC_NAME[&d.oid]) diff --git a/src/rust/src/x509/certificate.rs b/src/rust/src/x509/certificate.rs index 1a9820e5e..2e0378ff9 100644 --- a/src/rust/src/x509/certificate.rs +++ b/src/rust/src/x509/certificate.rs @@ -83,8 +83,8 @@ pub(crate) struct Certificate { pub(crate) cached_extensions: Option<pyo3::PyObject>, } -#[pyo3::prelude::pyproto] -impl pyo3::PyObjectProtocol for Certificate { +#[pyo3::prelude::pymethods] +impl Certificate { fn __hash__(&self) -> u64 { let mut hasher = DefaultHasher::new(); self.raw.borrow_value().hash(&mut hasher); @@ -93,7 +93,7 @@ impl pyo3::PyObjectProtocol for Certificate { fn __richcmp__( &self, - other: pyo3::PyRef<Certificate>, + other: pyo3::PyRef<'_, Certificate>, op: pyo3::basic::CompareOp, ) -> pyo3::PyResult<bool> { match op { @@ -105,18 +105,12 @@ impl pyo3::PyObjectProtocol for Certificate { } } - fn __repr__(&self) -> pyo3::PyResult<String> { - let gil = pyo3::Python::acquire_gil(); - let py = gil.python(); - + fn __repr__(&self, py: pyo3::Python<'_>) -> pyo3::PyResult<String> { let subject = self.subject(py)?; let subject_repr = subject.repr()?.extract::<&str>()?; Ok(format!("<Certificate(subject={}, ...)>", subject_repr)) } -} -#[pyo3::prelude::pymethods] -impl Certificate { fn __deepcopy__(slf: pyo3::PyRef<'_, Self>, _memo: pyo3::PyObject) -> pyo3::PyRef<'_, Self> { slf } @@ -277,7 +271,7 @@ impl Certificate { let hash_alg = sig_oids_to_hash.get_item(self.signature_algorithm_oid(py)?); match hash_alg { Ok(data) => Ok(data), - Err(_) => Err(CryptographyError::from(pyo3::PyErr::from_instance( + Err(_) => Err(CryptographyError::from(pyo3::PyErr::from_value( py.import("cryptography.exceptions")?.call_method1( "UnsupportedAlgorithm", (format!( @@ -359,11 +353,11 @@ fn cert_version(py: pyo3::Python<'_>, version: u8) -> Result<&pyo3::PyAny, Crypt match version { 0 => Ok(x509_module .getattr(crate::intern!(py, "Version"))? - .get_item("v1")?), + .get_item(crate::intern!(py, "v1"))?), 2 => Ok(x509_module .getattr(crate::intern!(py, "Version"))? - .get_item("v3")?), - _ => Err(CryptographyError::from(pyo3::PyErr::from_instance( + .get_item(crate::intern!(py, "v3"))?), + _ => Err(CryptographyError::from(pyo3::PyErr::from_value( x509_module .getattr(crate::intern!(py, "InvalidVersion"))? .call1((format!("{} is not a valid X509 version", version), version))?, diff --git a/src/rust/src/x509/common.rs b/src/rust/src/x509/common.rs index a765d6144..59710a3ae 100644 --- a/src/rust/src/x509/common.rs +++ b/src/rust/src/x509/common.rs @@ -112,10 +112,10 @@ pub(crate) fn encode_name_entry<'p>( let tag = attr_type .getattr(crate::intern!(py, "value"))? .extract::<u8>()?; - let value: &[u8] = if attr_type != asn1_type.getattr(crate::intern!(py, "BitString"))? { - let encoding = if attr_type == asn1_type.getattr(crate::intern!(py, "BMPString"))? { + let value: &[u8] = if !attr_type.is(asn1_type.getattr(crate::intern!(py, "BitString"))?) { + let encoding = if attr_type.is(asn1_type.getattr(crate::intern!(py, "BMPString"))?) { "utf_16_be" - } else if attr_type == asn1_type.getattr(crate::intern!(py, "UniversalString"))? { + } else if attr_type.is(asn1_type.getattr(crate::intern!(py, "UniversalString"))?) { "utf_32_be" } else { "utf8" @@ -233,18 +233,18 @@ pub(crate) fn encode_general_name<'a>( let gn_module = py.import("cryptography.x509.general_name")?; let gn_type = gn.get_type().as_ref(); let gn_value = gn.getattr(crate::intern!(py, "value"))?; - if gn_type == gn_module.getattr(crate::intern!(py, "DNSName"))? { + if gn_type.is(gn_module.getattr(crate::intern!(py, "DNSName"))?) { Ok(GeneralName::DNSName(UnvalidatedIA5String( gn_value.extract::<&str>()?, ))) - } else if gn_type == gn_module.getattr(crate::intern!(py, "RFC822Name"))? { + } else if gn_type.is(gn_module.getattr(crate::intern!(py, "RFC822Name"))?) { Ok(GeneralName::RFC822Name(UnvalidatedIA5String( gn_value.extract::<&str>()?, ))) - } else if gn_type == gn_module.getattr(crate::intern!(py, "DirectoryName"))? { + } else if gn_type.is(gn_module.getattr(crate::intern!(py, "DirectoryName"))?) { let name = encode_name(py, gn_value)?; Ok(GeneralName::DirectoryName(name)) - } else if gn_type == gn_module.getattr(crate::intern!(py, "OtherName"))? { + } else if gn_type.is(gn_module.getattr(crate::intern!(py, "OtherName"))?) { Ok(GeneralName::OtherName(OtherName { type_id: py_oid_to_oid(gn.getattr(crate::intern!(py, "type_id"))?)?, value: asn1::parse_single(gn_value.extract::<&[u8]>()?).map_err(|e| { @@ -254,15 +254,15 @@ pub(crate) fn encode_general_name<'a>( )) })?, })) - } else if gn_type == gn_module.getattr(crate::intern!(py, "UniformResourceIdentifier"))? { + } else if gn_type.is(gn_module.getattr(crate::intern!(py, "UniformResourceIdentifier"))?) { Ok(GeneralName::UniformResourceIdentifier( UnvalidatedIA5String(gn_value.extract::<&str>()?), )) - } else if gn_type == gn_module.getattr(crate::intern!(py, "IPAddress"))? { + } else if gn_type.is(gn_module.getattr(crate::intern!(py, "IPAddress"))?) { Ok(GeneralName::IPAddress( gn.call_method0("_packed")?.extract::<&[u8]>()?, )) - } else if gn_type == gn_module.getattr(crate::intern!(py, "RegisteredID"))? { + } else if gn_type.is(gn_module.getattr(crate::intern!(py, "RegisteredID"))?) { let oid = py_oid_to_oid(gn_value)?; Ok(GeneralName::RegisteredID(oid)) } else { @@ -462,7 +462,7 @@ pub(crate) fn parse_general_name( .to_object(py) } _ => { - return Err(CryptographyError::from(pyo3::PyErr::from_instance( + return Err(CryptographyError::from(pyo3::PyErr::from_value( x509_module.call_method1( "UnsupportedGeneralNameType", ("x400Address/EDIPartyName are not supported types",), @@ -563,7 +563,7 @@ pub(crate) fn parse_and_cache_extensions< let oid_obj = oid_to_py_oid(py, &raw_ext.extn_id)?; if seen_oids.contains(&raw_ext.extn_id) { - return Err(pyo3::PyErr::from_instance(x509_module.call_method1( + return Err(pyo3::PyErr::from_value(x509_module.call_method1( "DuplicateExtension", ( format!("Duplicate {} extension found", raw_ext.extn_id), @@ -613,7 +613,7 @@ pub(crate) fn encode_extensions< let oid = py_oid_to_oid(py_ext.getattr(crate::intern!(py, "oid"))?)?; let ext_val = py_ext.getattr(crate::intern!(py, "value"))?; - if unrecognized_extension_type.is_instance(ext_val)? { + if ext_val.is_instance(unrecognized_extension_type)? { exts.push(Extension { extn_id: oid, critical: py_ext.getattr(crate::intern!(py, "critical"))?.extract()?, diff --git a/src/rust/src/x509/crl.rs b/src/rust/src/x509/crl.rs index c1b5c8c48..37a4902ae 100644 --- a/src/rust/src/x509/crl.rs +++ b/src/rust/src/x509/crl.rs @@ -26,7 +26,7 @@ fn load_der_x509_crl( let version = raw.borrow_value().tbs_cert_list.version.unwrap_or(1); if version != 1 { let x509_module = py.import("cryptography.x509")?; - return Err(CryptographyError::from(pyo3::PyErr::from_instance( + return Err(CryptographyError::from(pyo3::PyErr::from_value( x509_module .getattr(crate::intern!(py, "InvalidVersion"))? .call1((format!("{} is not a valid CRL version", version), version))?, @@ -97,11 +97,11 @@ impl CertificateRevocationList { } } -#[pyo3::prelude::pyproto] -impl pyo3::PyObjectProtocol for CertificateRevocationList { +#[pyo3::prelude::pymethods] +impl CertificateRevocationList { fn __richcmp__( &self, - other: pyo3::PyRef<CertificateRevocationList>, + other: pyo3::PyRef<'_, CertificateRevocationList>, op: pyo3::basic::CompareOp, ) -> pyo3::PyResult<bool> { match op { @@ -112,18 +112,31 @@ impl pyo3::PyObjectProtocol for CertificateRevocationList { )), } } -} -#[pyo3::prelude::pyproto] -impl pyo3::PyMappingProtocol for CertificateRevocationList { fn __len__(&self) -> usize { self.len() } - fn __getitem__(&self, idx: &pyo3::PyAny) -> pyo3::PyResult<pyo3::PyObject> { - let gil = pyo3::Python::acquire_gil(); - let py = gil.python(); + fn __iter__(&self) -> CRLIterator { + CRLIterator { + contents: OwnedCRLIteratorData::try_new(Arc::clone(&self.raw), |v| { + Ok::<_, ()>( + v.borrow_value() + .tbs_cert_list + .revoked_certificates + .as_ref() + .map(|v| v.unwrap_read().clone()), + ) + }) + .unwrap(), + } + } + fn __getitem__( + &self, + py: pyo3::Python<'_>, + idx: &pyo3::PyAny, + ) -> pyo3::PyResult<pyo3::PyObject> { self.raw.with(|val| { val.revoked_certs.get_or_init(py, || { match &val.value.tbs_cert_list.revoked_certificates { @@ -133,7 +146,7 @@ impl pyo3::PyMappingProtocol for CertificateRevocationList { }); }); - if idx.is_instance::<pyo3::types::PySlice>()? { + if idx.is_instance_of::<pyo3::types::PySlice>()? { let indices = idx .downcast::<pyo3::types::PySlice>()? .indices(self.len().try_into().unwrap())?; @@ -154,10 +167,7 @@ impl pyo3::PyMappingProtocol for CertificateRevocationList { Ok(pyo3::PyCell::new(py, self.revoked_cert(py, idx as usize)?)?.to_object(py)) } } -} -#[pyo3::prelude::pymethods] -impl CertificateRevocationList { fn fingerprint<'p>( &self, py: pyo3::Python<'p>, @@ -189,7 +199,7 @@ impl CertificateRevocationList { .get_item(oid) { Ok(v) => Ok(v), - Err(_) => Err(pyo3::PyErr::from_instance(exceptions_module.call_method1( + Err(_) => Err(pyo3::PyErr::from_value(exceptions_module.call_method1( "UnsupportedAlgorithm", (format!( "Signature algorithm OID:{} not recognized", @@ -395,24 +405,6 @@ impl CertificateRevocationList { } } -#[pyo3::prelude::pyproto] -impl pyo3::PyIterProtocol<'_> for CertificateRevocationList { - fn __iter__(slf: pyo3::PyRef<'p, Self>) -> CRLIterator { - CRLIterator { - contents: OwnedCRLIteratorData::try_new(Arc::clone(&slf.raw), |v| { - Ok::<_, ()>( - v.borrow_value() - .tbs_cert_list - .revoked_certificates - .as_ref() - .map(|v| v.unwrap_read().clone()), - ) - }) - .unwrap(), - } - } -} - #[ouroboros::self_referencing] struct OwnedCRLIteratorData { data: Arc<OwnedRawCertificateRevocationList>, @@ -455,14 +447,18 @@ fn try_map_arc_data_mut_crl_iterator<E>( }) } -#[pyo3::prelude::pyproto] -impl pyo3::PyIterProtocol<'_> for CRLIterator { - fn __iter__(slf: pyo3::PyRef<'p, Self>) -> pyo3::PyRef<'p, Self> { +#[pyo3::prelude::pymethods] +impl CRLIterator { + fn __len__(&self) -> usize { + self.contents.borrow_value().clone().map_or(0, |v| v.len()) + } + + fn __iter__(slf: pyo3::PyRef<'_, Self>) -> pyo3::PyRef<'_, Self> { slf } - fn __next__(mut slf: pyo3::PyRefMut<'p, Self>) -> Option<RevokedCertificate> { - let revoked = try_map_arc_data_mut_crl_iterator(&mut slf.contents, |_data, v| match v { + fn __next__(&mut self) -> Option<RevokedCertificate> { + let revoked = try_map_arc_data_mut_crl_iterator(&mut self.contents, |_data, v| match v { Some(v) => match v.next() { Some(revoked) => Ok(revoked), None => Err(()), @@ -477,13 +473,6 @@ impl pyo3::PyIterProtocol<'_> for CRLIterator { } } -#[pyo3::prelude::pyproto] -impl pyo3::PySequenceProtocol<'_> for CRLIterator { - fn __len__(&self) -> usize { - self.contents.borrow_value().clone().map_or(0, |v| v.len()) - } -} - #[derive(asn1::Asn1Read, asn1::Asn1Write, PartialEq, Hash)] struct RawCertificateRevocationList<'a> { tbs_cert_list: TBSCertList<'a>, diff --git a/src/rust/src/x509/csr.rs b/src/rust/src/x509/csr.rs index e16a58164..8a7f53304 100644 --- a/src/rust/src/x509/csr.rs +++ b/src/rust/src/x509/csr.rs @@ -84,8 +84,8 @@ struct CertificateSigningRequest { cached_extensions: Option<pyo3::PyObject>, } -#[pyo3::prelude::pyproto] -impl pyo3::basic::PyObjectProtocol for CertificateSigningRequest { +#[pyo3::prelude::pymethods] +impl CertificateSigningRequest { fn __hash__(&self) -> u64 { let mut hasher = DefaultHasher::new(); self.raw.borrow_data().hash(&mut hasher); @@ -94,7 +94,7 @@ impl pyo3::basic::PyObjectProtocol for CertificateSigningRequest { fn __richcmp__( &self, - other: pyo3::PyRef<CertificateSigningRequest>, + other: pyo3::PyRef<'_, CertificateSigningRequest>, op: pyo3::basic::CompareOp, ) -> pyo3::PyResult<bool> { match op { @@ -105,10 +105,7 @@ impl pyo3::basic::PyObjectProtocol for CertificateSigningRequest { )), } } -} -#[pyo3::prelude::pymethods] -impl CertificateSigningRequest { fn public_key<'p>(&self, py: pyo3::Python<'p>) -> CryptographyResult<&'p pyo3::PyAny> { // This makes an unnecessary copy. It'd be nice to get rid of it. let serialized = pyo3::types::PyBytes::new( @@ -154,7 +151,7 @@ impl CertificateSigningRequest { let hash_alg = sig_oids_to_hash.get_item(self.signature_algorithm_oid(py)?); match hash_alg { Ok(data) => Ok(data), - Err(_) => Err(CryptographyError::from(pyo3::PyErr::from_instance( + Err(_) => Err(CryptographyError::from(pyo3::PyErr::from_value( py.import("cryptography.exceptions")?.call_method1( "UnsupportedAlgorithm", (format!( @@ -222,7 +219,7 @@ impl CertificateSigningRequest { } } } - Err(pyo3::PyErr::from_instance( + Err(pyo3::PyErr::from_value( py.import("cryptography.x509")?.call_method1( "AttributeNotFound", (format!("No {} attribute was found", oid), oid), @@ -309,7 +306,7 @@ fn load_der_x509_csr( let version = raw.borrow_value().csr_info.version; if version != 0 { let x509_module = py.import("cryptography.x509")?; - return Err(CryptographyError::from(pyo3::PyErr::from_instance( + return Err(CryptographyError::from(pyo3::PyErr::from_value( x509_module .getattr(crate::intern!(py, "InvalidVersion"))? .call1((format!("{} is not a valid CSR version", version), version))?, diff --git a/src/rust/src/x509/extensions.rs b/src/rust/src/x509/extensions.rs index d93e87c0f..1af8d389d 100644 --- a/src/rust/src/x509/extensions.rs +++ b/src/rust/src/x509/extensions.rs @@ -229,7 +229,7 @@ pub(crate) fn encode_extension( let mut qualifiers = vec![]; for py_qualifier in py_policy_qualifiers.iter()? { let py_qualifier = py_qualifier?; - let qualifier = if py_qualifier.is_instance::<pyo3::types::PyString>()? { + let qualifier = if py_qualifier.is_instance_of::<pyo3::types::PyString>()? { let cps_uri = match asn1::IA5String::new(py_qualifier.extract()?) { Some(s) => s, None => { diff --git a/src/rust/src/x509/ocsp_req.rs b/src/rust/src/x509/ocsp_req.rs index 638caf9b2..5711dd4a9 100644 --- a/src/rust/src/x509/ocsp_req.rs +++ b/src/rust/src/x509/ocsp_req.rs @@ -83,10 +83,10 @@ impl OCSPRequest { let hashes = py.import("cryptography.hazmat.primitives.hashes")?; match ocsp::OIDS_TO_HASH.get(&cert_id.hash_algorithm.oid) { - Some(alg_name) => Ok(hashes.getattr(alg_name)?.call0()?), + Some(alg_name) => Ok(hashes.getattr(*alg_name)?.call0()?), None => { let exceptions = py.import("cryptography.exceptions")?; - Err(CryptographyError::from(pyo3::PyErr::from_instance( + Err(CryptographyError::from(pyo3::PyErr::from_value( exceptions .getattr(crate::intern!(py, "UnsupportedAlgorithm"))? .call1((format!( @@ -141,7 +141,7 @@ impl OCSPRequest { .import("cryptography.hazmat.primitives.serialization")? .getattr(crate::intern!(py, "Encoding"))? .getattr(crate::intern!(py, "DER"))?; - if encoding != der { + if !encoding.is(der) { return Err(pyo3::exceptions::PyValueError::new_err( "The only allowed encoding value is Encoding.DER", ) diff --git a/src/rust/src/x509/ocsp_resp.rs b/src/rust/src/x509/ocsp_resp.rs index 2f878b2c4..9f3828293 100644 --- a/src/rust/src/x509/ocsp_resp.rs +++ b/src/rust/src/x509/ocsp_resp.rs @@ -183,7 +183,7 @@ impl OCSPResponse { "Signature algorithm OID: {} not recognized", self.requires_successful_response()?.signature_algorithm.oid ); - Err(CryptographyError::from(pyo3::PyErr::from_instance( + Err(CryptographyError::from(pyo3::PyErr::from_value( py.import("cryptography.exceptions")? .call_method1("UnsupportedAlgorithm", (exc_messsage,))?, ))) @@ -383,7 +383,7 @@ impl OCSPResponse { .import("cryptography.hazmat.primitives.serialization")? .getattr(crate::intern!(py, "Encoding"))? .getattr(crate::intern!(py, "DER"))?; - if encoding != der { + if !encoding.is(der) { return Err(pyo3::exceptions::PyValueError::new_err( "The only allowed encoding value is Encoding.DER", ) @@ -528,10 +528,10 @@ impl SingleResponse<'_> { ) -> Result<&'p pyo3::PyAny, CryptographyError> { let hashes = py.import("cryptography.hazmat.primitives.hashes")?; match ocsp::OIDS_TO_HASH.get(&self.cert_id.hash_algorithm.oid) { - Some(alg_name) => Ok(hashes.getattr(alg_name)?.call0()?), + Some(alg_name) => Ok(hashes.getattr(*alg_name)?.call0()?), None => { let exceptions = py.import("cryptography.exceptions")?; - Err(CryptographyError::from(pyo3::PyErr::from_instance( + Err(CryptographyError::from(pyo3::PyErr::from_value( exceptions .getattr(crate::intern!(py, "UnsupportedAlgorithm"))? .call1((format!( @@ -627,16 +627,14 @@ fn create_ocsp_response( .extract()?; let py_cert_status = py_single_resp.getattr(crate::intern!(py, "_cert_status"))?; - let cert_status = if py_cert_status - == ocsp_mod - .getattr(crate::intern!(py, "OCSPCertStatus"))? - .getattr(crate::intern!(py, "GOOD"))? + let cert_status = if py_cert_status.is(ocsp_mod + .getattr(crate::intern!(py, "OCSPCertStatus"))? + .getattr(crate::intern!(py, "GOOD"))?) { CertStatus::Good(()) - } else if py_cert_status - == ocsp_mod - .getattr(crate::intern!(py, "OCSPCertStatus"))? - .getattr(crate::intern!(py, "UNKNOWN"))? + } else if py_cert_status.is(ocsp_mod + .getattr(crate::intern!(py, "OCSPCertStatus"))? + .getattr(crate::intern!(py, "UNKNOWN"))?) { CertStatus::Unknown(()) } else { @@ -687,10 +685,9 @@ fn create_ocsp_response( }]; borrowed_cert = responder_cert.borrow(); - let responder_id = if responder_encoding - == ocsp_mod - .getattr(crate::intern!(py, "OCSPResponderEncoding"))? - .getattr(crate::intern!(py, "HASH"))? + let responder_id = if responder_encoding.is(ocsp_mod + .getattr(crate::intern!(py, "OCSPResponderEncoding"))? + .getattr(crate::intern!(py, "HASH"))?) { let sha1 = py .import("cryptography.hazmat.primitives.hashes")? @@ -801,15 +798,15 @@ struct OCSPResponseIterator { contents: OwnedOCSPResponseIteratorData, } -#[pyo3::prelude::pyproto] -impl pyo3::PyIterProtocol<'_> for OCSPResponseIterator { - fn __iter__(slf: pyo3::PyRef<'p, Self>) -> pyo3::PyRef<'p, Self> { +#[pyo3::prelude::pymethods] +impl OCSPResponseIterator { + fn __iter__(slf: pyo3::PyRef<'_, Self>) -> pyo3::PyRef<'_, Self> { slf } - fn __next__(mut slf: pyo3::PyRefMut<'p, Self>) -> Option<OCSPSingleResponse> { + fn __next__(&mut self) -> Option<OCSPSingleResponse> { let single_resp = - try_map_arc_data_mut_ocsp_response_iterator(&mut slf.contents, |_data, v| { + try_map_arc_data_mut_ocsp_response_iterator(&mut self.contents, |_data, v| { match v.next() { Some(single_resp) => Ok(single_resp), None => Err(()), diff --git a/src/rust/src/x509/sct.rs b/src/rust/src/x509/sct.rs index e3f7be4d9..b6b2e56da 100644 --- a/src/rust/src/x509/sct.rs +++ b/src/rust/src/x509/sct.rs @@ -143,6 +143,26 @@ pub(crate) struct Sct { #[pyo3::prelude::pymethods] impl Sct { + fn __richcmp__( + &self, + other: pyo3::PyRef<'_, Sct>, + op: pyo3::basic::CompareOp, + ) -> pyo3::PyResult<bool> { + match op { + pyo3::basic::CompareOp::Eq => Ok(self.sct_data == other.sct_data), + pyo3::basic::CompareOp::Ne => Ok(self.sct_data != other.sct_data), + _ => Err(pyo3::exceptions::PyTypeError::new_err( + "SCTs cannot be ordered", + )), + } + } + + fn __hash__(&self) -> u64 { + let mut hasher = DefaultHasher::new(); + self.sct_data.hash(&mut hasher); + hasher.finish() + } + #[getter] fn version<'p>(&self, py: pyo3::Python<'p>) -> pyo3::PyResult<&'p pyo3::PyAny> { py.import("cryptography.x509.certificate_transparency")? @@ -209,29 +229,6 @@ impl Sct { } } -#[pyo3::prelude::pyproto] -impl pyo3::PyObjectProtocol for Sct { - fn __richcmp__( - &self, - other: pyo3::PyRef<Sct>, - op: pyo3::basic::CompareOp, - ) -> pyo3::PyResult<bool> { - match op { - pyo3::basic::CompareOp::Eq => Ok(self.sct_data == other.sct_data), - pyo3::basic::CompareOp::Ne => Ok(self.sct_data != other.sct_data), - _ => Err(pyo3::exceptions::PyTypeError::new_err( - "SCTs cannot be ordered", - )), - } - } - - fn __hash__(&self) -> u64 { - let mut hasher = DefaultHasher::new(); - self.sct_data.hash(&mut hasher); - hasher.finish() - } -} - pub(crate) fn parse_scts( py: pyo3::Python<'_>, data: &[u8], diff --git a/src/rust/src/x509/sign.rs b/src/rust/src/x509/sign.rs index 33d293b21..4d505ece7 100644 --- a/src/rust/src/x509/sign.rs +++ b/src/rust/src/x509/sign.rs @@ -59,15 +59,15 @@ fn identify_key_type(py: pyo3::Python<'_>, private_key: &pyo3::PyAny) -> pyo3::P .getattr(crate::intern!(py, "Ed448PrivateKey"))? .extract()?; - if rsa_private_key.is_instance(private_key)? { + if private_key.is_instance(rsa_private_key)? { Ok(KeyType::Rsa) - } else if dsa_key_type.is_instance(private_key)? { + } else if private_key.is_instance(dsa_key_type)? { Ok(KeyType::Dsa) - } else if ec_key_type.is_instance(private_key)? { + } else if private_key.is_instance(ec_key_type)? { Ok(KeyType::Ec) - } else if ed25519_key_type.is_instance(private_key)? { + } else if private_key.is_instance(ed25519_key_type)? { Ok(KeyType::Ed25519) - } else if ed448_key_type.is_instance(private_key)? { + } else if private_key.is_instance(ed448_key_type)? { Ok(KeyType::Ed448) } else { Err(pyo3::exceptions::PyTypeError::new_err( @@ -88,7 +88,7 @@ fn identify_hash_type( .import("cryptography.hazmat.primitives.hashes")? .getattr(crate::intern!(py, "HashAlgorithm"))? .extract()?; - if !hash_algorithm_type.is_instance(hash_algorithm)? { + if !hash_algorithm.is_instance(hash_algorithm_type)? { return Err(pyo3::exceptions::PyTypeError::new_err( "Algorithm must be a registered hash algorithm.", )); @@ -106,7 +106,7 @@ fn identify_hash_type( "sha3-256" => Ok(HashType::Sha3_256), "sha3-384" => Ok(HashType::Sha3_384), "sha3-512" => Ok(HashType::Sha3_512), - name => Err(pyo3::PyErr::from_instance( + name => Err(pyo3::PyErr::from_value( py.import("cryptography.exceptions")?.call_method1( "UnsupportedAlgorithm", (format!( @@ -226,7 +226,7 @@ pub(crate) fn compute_signature_algorithm<'p>( (KeyType::Dsa, HashType::Sha3_224) | (KeyType::Dsa, HashType::Sha3_256) | (KeyType::Dsa, HashType::Sha3_384) - | (KeyType::Dsa, HashType::Sha3_512) => Err(pyo3::PyErr::from_instance( + | (KeyType::Dsa, HashType::Sha3_512) => Err(pyo3::PyErr::from_value( py.import("cryptography.exceptions")?.call_method1( "UnsupportedAlgorithm", ("SHA3 hashes are not supported with DSA keys",), @@ -354,15 +354,15 @@ pub(crate) fn identify_public_key_type( .getattr(crate::intern!(py, "Ed448PublicKey"))? .extract()?; - if rsa_key_type.is_instance(public_key)? { + if public_key.is_instance(rsa_key_type)? { Ok(KeyType::Rsa) - } else if dsa_key_type.is_instance(public_key)? { + } else if public_key.is_instance(dsa_key_type)? { Ok(KeyType::Dsa) - } else if ec_key_type.is_instance(public_key)? { + } else if public_key.is_instance(ec_key_type)? { Ok(KeyType::Ec) - } else if ed25519_key_type.is_instance(public_key)? { + } else if public_key.is_instance(ed25519_key_type)? { Ok(KeyType::Ed25519) - } else if ed448_key_type.is_instance(public_key)? { + } else if public_key.is_instance(ed448_key_type)? { Ok(KeyType::Ed448) } else { Err(pyo3::exceptions::PyTypeError::new_err( diff --git a/tests/hazmat/primitives/test_pkcs7.py b/tests/hazmat/primitives/test_pkcs7.py index 4e61c5ef5..172cf40bd 100644 --- a/tests/hazmat/primitives/test_pkcs7.py +++ b/tests/hazmat/primitives/test_pkcs7.py @@ -807,7 +807,7 @@ class TestPKCS7SerializeCerts: ) with pytest.raises(TypeError): pkcs7.serialize_certificates( - "not a list of certs", # type: ignore[arg-type] + object(), # type: ignore[arg-type] serialization.Encoding.PEM, ) |
