diff --git a/src/rust/src/asn1.rs b/src/rust/src/asn1.rs index 366fc69eacd6..6dd7a48ca565 100644 --- a/src/rust/src/asn1.rs +++ b/src/rust/src/asn1.rs @@ -6,7 +6,7 @@ use cryptography_x509::common::{DssSignature, SubjectPublicKeyInfo}; use pyo3::pybacked::PyBackedBytes; use pyo3::types::IntoPyDict; use pyo3::types::PyAnyMethods; -use pyo3::ToPyObject; +use pyo3::IntoPyObject; use crate::error::{CryptographyError, CryptographyResult}; use crate::types; @@ -38,7 +38,7 @@ fn parse_spki_for_data<'p>( return Err(pyo3::exceptions::PyValueError::new_err("Invalid public key encoding").into()); } - Ok(pyo3::types::PyBytes::new_bound( + Ok(pyo3::types::PyBytes::new( py, spki.subject_public_key.as_bytes(), )) @@ -48,8 +48,8 @@ pub(crate) fn big_byte_slice_to_py_int<'p>( py: pyo3::Python<'p>, v: &'_ [u8], ) -> pyo3::PyResult> { - let int_type = py.get_type_bound::(); - let kwargs = [("signed", true)].into_py_dict_bound(py); + let int_type = py.get_type::(); + let kwargs = [("signed", true)].into_py_dict(py)?; int_type.call_method(pyo3::intern!(py, "from_bytes"), (v, "big"), Some(&kwargs)) } @@ -64,12 +64,14 @@ fn decode_dss_signature( big_byte_slice_to_py_int(py, sig.r.as_bytes())?, big_byte_slice_to_py_int(py, sig.s.as_bytes())?, ) - .to_object(py)) + .into_pyobject(py)? + .into_any() + .unbind()) } pub(crate) fn py_uint_to_big_endian_bytes<'p>( py: pyo3::Python<'p>, - v: pyo3::Bound<'p, pyo3::types::PyLong>, + v: pyo3::Bound<'p, pyo3::types::PyInt>, ) -> pyo3::PyResult { if v.lt(0)? { return Err(pyo3::exceptions::PyValueError::new_err( @@ -96,9 +98,9 @@ pub(crate) fn encode_der_data<'p>( encoding: &pyo3::Bound<'p, pyo3::PyAny>, ) -> CryptographyResult> { if encoding.is(&types::ENCODING_DER.get(py)?) { - Ok(pyo3::types::PyBytes::new_bound(py, &data)) + Ok(pyo3::types::PyBytes::new(py, &data)) } else if encoding.is(&types::ENCODING_PEM.get(py)?) { - Ok(pyo3::types::PyBytes::new_bound( + Ok(pyo3::types::PyBytes::new( py, &pem::encode_config( &pem::Pem::new(pem_tag, data), @@ -117,8 +119,8 @@ pub(crate) fn encode_der_data<'p>( #[pyo3::pyfunction] fn encode_dss_signature<'p>( py: pyo3::Python<'p>, - r: pyo3::Bound<'_, pyo3::types::PyLong>, - s: pyo3::Bound<'_, pyo3::types::PyLong>, + r: pyo3::Bound<'_, pyo3::types::PyInt>, + s: pyo3::Bound<'_, pyo3::types::PyInt>, ) -> CryptographyResult> { let r_bytes = py_uint_to_big_endian_bytes(py, r)?; let s_bytes = py_uint_to_big_endian_bytes(py, s)?; @@ -127,7 +129,7 @@ fn encode_dss_signature<'p>( s: asn1::BigUint::new(&s_bytes).unwrap(), }; let result = asn1::write_single(&sig)?; - Ok(pyo3::types::PyBytes::new_bound(py, &result)) + Ok(pyo3::types::PyBytes::new(py, &result)) } #[pyo3::pymodule] diff --git a/src/rust/src/backend/aead.rs b/src/rust/src/backend/aead.rs index 72b986e4bc58..fc56b64d6553 100644 --- a/src/rust/src/backend/aead.rs +++ b/src/rust/src/backend/aead.rs @@ -172,7 +172,7 @@ impl EvpCipherAead { Self::process_aad(&mut ctx, aad)?; - Ok(pyo3::types::PyBytes::new_bound_with( + Ok(pyo3::types::PyBytes::new_with( py, plaintext.len() + tag_len, |b| { @@ -254,7 +254,7 @@ impl EvpCipherAead { Self::process_aad(&mut ctx, aad)?; - Ok(pyo3::types::PyBytes::new_bound_with( + Ok(pyo3::types::PyBytes::new_with( py, ciphertext_data.len(), |b| { @@ -399,7 +399,7 @@ impl EvpAead { assert!(aad.is_none()); b"" }; - Ok(pyo3::types::PyBytes::new_bound_with( + Ok(pyo3::types::PyBytes::new_with( py, plaintext.len() + self.tag_len, |b| { @@ -430,7 +430,7 @@ impl EvpAead { b"" }; - Ok(pyo3::types::PyBytes::new_bound_with( + Ok(pyo3::types::PyBytes::new_with( py, ciphertext.len() - self.tag_len, |b| { diff --git a/src/rust/src/backend/ciphers.rs b/src/rust/src/backend/ciphers.rs index 8c90fe32e3d8..f102a8e57dfe 100644 --- a/src/rust/src/backend/ciphers.rs +++ b/src/rust/src/backend/ciphers.rs @@ -8,7 +8,7 @@ use crate::error::{CryptographyError, CryptographyResult}; use crate::exceptions; use crate::types; use pyo3::types::PyAnyMethods; -use pyo3::IntoPy; +use pyo3::IntoPyObject; pub(crate) struct CipherContext { ctx: openssl::cipher_ctx::CipherCtx, @@ -160,7 +160,7 @@ impl CipherContext { ) -> CryptographyResult> { let mut buf = vec![0; data.len() + self.ctx.block_size()]; let n = self.update_into(py, data, &mut buf)?; - Ok(pyo3::types::PyBytes::new_bound(py, &buf[..n])) + Ok(pyo3::types::PyBytes::new(py, &buf[..n])) } pub(crate) fn update_into( @@ -224,7 +224,7 @@ impl CipherContext { ), )) })?; - Ok(pyo3::types::PyBytes::new_bound(py, &out_buf[..n])) + Ok(pyo3::types::PyBytes::new(py, &out_buf[..n])) } } @@ -359,7 +359,7 @@ impl PyAEADEncryptionContext { let result = ctx.finalize(py)?; // XXX: do not hard code 16 - let tag = pyo3::types::PyBytes::new_bound_with(py, 16, |t| { + let tag = pyo3::types::PyBytes::new_with(py, 16, |t| { ctx.ctx.tag(t).map_err(CryptographyError::from)?; Ok(()) })?; @@ -539,9 +539,14 @@ fn create_encryption_ctx( .getattr(pyo3::intern!(py, "_MAX_AAD_BYTES"))? .extract()?, } - .into_py(py)) + .into_pyobject(py)? + .into_any() + .unbind()) } else { - Ok(PyCipherContext { ctx: Some(ctx) }.into_py(py)) + Ok(PyCipherContext { ctx: Some(ctx) } + .into_pyobject(py)? + .into_any() + .unbind()) } } @@ -571,9 +576,14 @@ fn create_decryption_ctx( .getattr(pyo3::intern!(py, "_MAX_AAD_BYTES"))? .extract()?, } - .into_py(py)) + .into_pyobject(py)? + .into_any() + .unbind()) } else { - Ok(PyCipherContext { ctx: Some(ctx) }.into_py(py)) + Ok(PyCipherContext { ctx: Some(ctx) } + .into_pyobject(py)? + .into_any() + .unbind()) } } diff --git a/src/rust/src/backend/cmac.rs b/src/rust/src/backend/cmac.rs index fe11f7495a33..7519c1b88603 100644 --- a/src/rust/src/backend/cmac.rs +++ b/src/rust/src/backend/cmac.rs @@ -77,7 +77,7 @@ impl Cmac { ) -> CryptographyResult> { let data = self.get_mut_ctx()?.finish()?; self.ctx = None; - Ok(pyo3::types::PyBytes::new_bound(py, &data)) + Ok(pyo3::types::PyBytes::new(py, &data)) } fn verify(&mut self, py: pyo3::Python<'_>, signature: &[u8]) -> CryptographyResult<()> { diff --git a/src/rust/src/backend/dh.rs b/src/rust/src/backend/dh.rs index e6cdbb67c7c1..a19ab6342e90 100644 --- a/src/rust/src/backend/dh.rs +++ b/src/rust/src/backend/dh.rs @@ -149,7 +149,7 @@ impl DHPrivateKey { .map_err(|_| pyo3::exceptions::PyValueError::new_err("Error computing shared key."))?; let len = deriver.len()?; - Ok(pyo3::types::PyBytes::new_bound_with(py, len, |b| { + Ok(pyo3::types::PyBytes::new_with(py, len, |b| { let n = deriver.derive(b).unwrap(); let pad = b.len() - n; @@ -363,7 +363,7 @@ impl DHParameters { #[pyo3::pyclass(frozen, module = "cryptography.hazmat.primitives.asymmetric.dh")] struct DHPrivateNumbers { #[pyo3(get)] - x: pyo3::Py, + x: pyo3::Py, #[pyo3(get)] public_numbers: pyo3::Py, } @@ -371,7 +371,7 @@ struct DHPrivateNumbers { #[pyo3::pyclass(frozen, module = "cryptography.hazmat.primitives.asymmetric.dh")] struct DHPublicNumbers { #[pyo3(get)] - y: pyo3::Py, + y: pyo3::Py, #[pyo3(get)] parameter_numbers: pyo3::Py, } @@ -379,18 +379,18 @@ struct DHPublicNumbers { #[pyo3::pyclass(frozen, module = "cryptography.hazmat.primitives.asymmetric.dh")] struct DHParameterNumbers { #[pyo3(get)] - p: pyo3::Py, + p: pyo3::Py, #[pyo3(get)] - g: pyo3::Py, + g: pyo3::Py, #[pyo3(get)] - q: Option>, + q: Option>, } #[pyo3::pymethods] impl DHPrivateNumbers { #[new] fn new( - x: pyo3::Py, + x: pyo3::Py, public_numbers: pyo3::Py, ) -> DHPrivateNumbers { DHPrivateNumbers { x, public_numbers } @@ -428,7 +428,7 @@ impl DHPrivateNumbers { py: pyo3::Python<'_>, other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { - Ok(self.x.bind(py).eq(other.x.bind(py))? + Ok((**self.x.bind(py)).eq(other.x.bind(py))? && self .public_numbers .bind(py) @@ -440,7 +440,7 @@ impl DHPrivateNumbers { impl DHPublicNumbers { #[new] fn new( - y: pyo3::Py, + y: pyo3::Py, parameter_numbers: pyo3::Py, ) -> DHPublicNumbers { DHPublicNumbers { @@ -472,7 +472,7 @@ impl DHPublicNumbers { py: pyo3::Python<'_>, other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { - Ok(self.y.bind(py).eq(other.y.bind(py))? + Ok((**self.y.bind(py)).eq(other.y.bind(py))? && self .parameter_numbers .bind(py) @@ -486,9 +486,9 @@ impl DHParameterNumbers { #[pyo3(signature = (p, g, q=None))] fn new( py: pyo3::Python<'_>, - p: pyo3::Py, - g: pyo3::Py, - q: Option>, + p: pyo3::Py, + g: pyo3::Py, + q: Option>, ) -> CryptographyResult { if g.bind(py).lt(2)? { return Err(CryptographyError::from( @@ -528,12 +528,12 @@ impl DHParameterNumbers { other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { let q_equal = match (self.q.as_ref(), other.q.as_ref()) { - (Some(self_q), Some(other_q)) => self_q.bind(py).eq(other_q.bind(py))?, + (Some(self_q), Some(other_q)) => (**self_q.bind(py)).eq(other_q.bind(py))?, (None, None) => true, _ => false, }; - Ok(self.p.bind(py).eq(other.p.bind(py))? - && self.g.bind(py).eq(other.g.bind(py))? + Ok((**self.p.bind(py)).eq(other.p.bind(py))? + && (**self.g.bind(py)).eq(other.g.bind(py))? && q_equal) } } diff --git a/src/rust/src/backend/dsa.rs b/src/rust/src/backend/dsa.rs index c904824bb894..86ddac9c88d0 100644 --- a/src/rust/src/backend/dsa.rs +++ b/src/rust/src/backend/dsa.rs @@ -7,7 +7,6 @@ use crate::buf::CffiBuf; use crate::error::{CryptographyError, CryptographyResult}; use crate::{error, exceptions}; use pyo3::types::PyAnyMethods; -use pyo3::ToPyObject; #[pyo3::pyclass( frozen, @@ -80,10 +79,10 @@ impl DsaPrivateKey { signer.sign_to_vec(data.as_bytes(), &mut sig).map_err(|e| { pyo3::exceptions::PyValueError::new_err(( "DSA signing failed. This generally indicates an invalid key.", - error::list_from_openssl_error(py, &e).to_object(py), + error::list_from_openssl_error(py, &e).unbind(), )) })?; - Ok(pyo3::types::PyBytes::new_bound(py, &sig)) + Ok(pyo3::types::PyBytes::new(py, &sig)) } #[getter] @@ -300,7 +299,7 @@ fn check_dsa_private_numbers( )); } - if numbers.public_numbers.get().y.bind(py).ne(params + if (**numbers.public_numbers.get().y.bind(py)).ne(params .g .bind(py) .pow(numbers.x.bind(py), Some(params.p.bind(py)))?)? @@ -320,7 +319,7 @@ fn check_dsa_private_numbers( )] struct DsaPrivateNumbers { #[pyo3(get)] - x: pyo3::Py, + x: pyo3::Py, #[pyo3(get)] public_numbers: pyo3::Py, } @@ -332,7 +331,7 @@ struct DsaPrivateNumbers { )] struct DsaPublicNumbers { #[pyo3(get)] - y: pyo3::Py, + y: pyo3::Py, #[pyo3(get)] parameter_numbers: pyo3::Py, } @@ -344,18 +343,18 @@ struct DsaPublicNumbers { )] struct DsaParameterNumbers { #[pyo3(get)] - p: pyo3::Py, + p: pyo3::Py, #[pyo3(get)] - q: pyo3::Py, + q: pyo3::Py, #[pyo3(get)] - g: pyo3::Py, + g: pyo3::Py, } #[pyo3::pymethods] impl DsaPrivateNumbers { #[new] fn new( - x: pyo3::Py, + x: pyo3::Py, public_numbers: pyo3::Py, ) -> DsaPrivateNumbers { DsaPrivateNumbers { x, public_numbers } @@ -391,7 +390,7 @@ impl DsaPrivateNumbers { py: pyo3::Python<'_>, other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { - Ok(self.x.bind(py).eq(other.x.bind(py))? + Ok((**self.x.bind(py)).eq(other.x.bind(py))? && self .public_numbers .bind(py) @@ -403,7 +402,7 @@ impl DsaPrivateNumbers { impl DsaPublicNumbers { #[new] fn new( - y: pyo3::Py, + y: pyo3::Py, parameter_numbers: pyo3::Py, ) -> DsaPublicNumbers { DsaPublicNumbers { @@ -440,7 +439,7 @@ impl DsaPublicNumbers { py: pyo3::Python<'_>, other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { - Ok(self.y.bind(py).eq(other.y.bind(py))? + Ok((**self.y.bind(py)).eq(other.y.bind(py))? && self .parameter_numbers .bind(py) @@ -460,9 +459,9 @@ impl DsaPublicNumbers { impl DsaParameterNumbers { #[new] fn new( - p: pyo3::Py, - q: pyo3::Py, - g: pyo3::Py, + p: pyo3::Py, + q: pyo3::Py, + g: pyo3::Py, ) -> DsaParameterNumbers { DsaParameterNumbers { p, q, g } } @@ -491,9 +490,9 @@ impl DsaParameterNumbers { py: pyo3::Python<'_>, other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { - Ok(self.p.bind(py).eq(other.p.bind(py))? - && self.q.bind(py).eq(other.q.bind(py))? - && self.g.bind(py).eq(other.g.bind(py))?) + Ok((**self.p.bind(py)).eq(other.p.bind(py))? + && (**self.q.bind(py)).eq(other.q.bind(py))? + && (**self.g.bind(py)).eq(other.g.bind(py))?) } fn __repr__(&self, py: pyo3::Python<'_>) -> pyo3::PyResult { diff --git a/src/rust/src/backend/ec.rs b/src/rust/src/backend/ec.rs index 793ae48cf59c..9039acde5d58 100644 --- a/src/rust/src/backend/ec.rs +++ b/src/rust/src/backend/ec.rs @@ -34,8 +34,8 @@ fn curve_from_py_curve( if !py_curve.is_instance(&types::ELLIPTIC_CURVE.get(py)?)? { if allow_curve_class { let warning_cls = types::DEPRECATED_IN_42.get(py)?; - let warning_msg = "Curve argument must be an instance of an EllipticCurve class. Did you pass a class by mistake? This will be an exception in a future version of cryptography."; - pyo3::PyErr::warn_bound(py, &warning_cls, warning_msg, 1)?; + let warning_msg = std::ffi::CString::new("Curve argument must be an instance of an EllipticCurve class. Did you pass a class by mistake? This will be an exception in a future version of cryptography.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, warning_msg.as_c_str(), 1)?; } else { return Err(CryptographyError::from( pyo3::exceptions::PyTypeError::new_err("curve must be an EllipticCurve instance"), @@ -175,7 +175,7 @@ fn generate_private_key( #[pyo3::pyfunction] fn derive_private_key( py: pyo3::Python<'_>, - py_private_value: &pyo3::Bound<'_, pyo3::types::PyLong>, + py_private_value: &pyo3::Bound<'_, pyo3::types::PyInt>, py_curve: pyo3::Bound<'_, pyo3::PyAny>, ) -> CryptographyResult { let curve = curve_from_py_curve(py, py_curve.clone(), false)?; @@ -257,7 +257,7 @@ impl ECPrivateKey { .map_err(|_| pyo3::exceptions::PyValueError::new_err("Error computing shared key."))?; let len = deriver.len()?; - Ok(pyo3::types::PyBytes::new_bound_with(py, len, |b| { + Ok(pyo3::types::PyBytes::new_with(py, len, |b| { let n = deriver.derive(b).map_err(|_| { pyo3::exceptions::PyValueError::new_err("Error computing shared key.") })?; @@ -314,7 +314,7 @@ impl ECPrivateKey { // will be a byte or two shorter than the maximum possible length). let mut sig = vec![]; signer.sign_to_vec(data.as_bytes(), &mut sig)?; - Ok(pyo3::types::PyBytes::new_bound(py, &sig)) + Ok(pyo3::types::PyBytes::new(py, &sig)) } fn public_key(&self, py: pyo3::Python<'_>) -> CryptographyResult { @@ -464,7 +464,7 @@ impl ECPublicKey { #[pyo3::pyclass(frozen, module = "cryptography.hazmat.primitives.asymmetric.ec")] struct EllipticCurvePrivateNumbers { #[pyo3(get)] - private_value: pyo3::Py, + private_value: pyo3::Py, #[pyo3(get)] public_numbers: pyo3::Py, } @@ -472,9 +472,9 @@ struct EllipticCurvePrivateNumbers { #[pyo3::pyclass(frozen, module = "cryptography.hazmat.primitives.asymmetric.ec")] struct EllipticCurvePublicNumbers { #[pyo3(get)] - x: pyo3::Py, + x: pyo3::Py, #[pyo3(get)] - y: pyo3::Py, + y: pyo3::Py, #[pyo3(get)] curve: pyo3::Py, } @@ -512,7 +512,7 @@ fn public_key_from_numbers( impl EllipticCurvePrivateNumbers { #[new] fn new( - private_value: pyo3::Py, + private_value: pyo3::Py, public_numbers: pyo3::Py, ) -> EllipticCurvePrivateNumbers { EllipticCurvePrivateNumbers { @@ -563,14 +563,13 @@ impl EllipticCurvePrivateNumbers { py: pyo3::Python<'_>, other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { - Ok(self - .private_value - .bind(py) - .eq(other.private_value.bind(py))? - && self - .public_numbers - .bind(py) - .eq(other.public_numbers.bind(py))?) + Ok( + (**self.private_value.bind(py)).eq(other.private_value.bind(py))? + && self + .public_numbers + .bind(py) + .eq(other.public_numbers.bind(py))?, + ) } fn __hash__(&self, py: pyo3::Python<'_>) -> CryptographyResult { @@ -586,8 +585,8 @@ impl EllipticCurvePublicNumbers { #[new] fn new( py: pyo3::Python<'_>, - x: pyo3::Py, - y: pyo3::Py, + x: pyo3::Py, + y: pyo3::Py, curve: pyo3::Py, ) -> CryptographyResult { if !curve @@ -628,8 +627,8 @@ impl EllipticCurvePublicNumbers { py: pyo3::Python<'_>, other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { - Ok(self.x.bind(py).eq(other.x.bind(py))? - && self.y.bind(py).eq(other.y.bind(py))? + Ok((**self.x.bind(py)).eq(other.x.bind(py))? + && (**self.y.bind(py)).eq(other.y.bind(py))? && self .curve .bind(py) diff --git a/src/rust/src/backend/ed25519.rs b/src/rust/src/backend/ed25519.rs index 3460640a1a53..721bac816882 100644 --- a/src/rust/src/backend/ed25519.rs +++ b/src/rust/src/backend/ed25519.rs @@ -70,7 +70,7 @@ impl Ed25519PrivateKey { ) -> CryptographyResult> { let mut signer = openssl::sign::Signer::new_without_digest(&self.pkey)?; let len = signer.len()?; - Ok(pyo3::types::PyBytes::new_bound_with(py, len, |b| { + Ok(pyo3::types::PyBytes::new_with(py, len, |b| { let n = signer .sign_oneshot(b, data.as_bytes()) .map_err(CryptographyError::from)?; @@ -94,7 +94,7 @@ impl Ed25519PrivateKey { py: pyo3::Python<'p>, ) -> CryptographyResult> { let raw_bytes = self.pkey.raw_private_key()?; - Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)) + Ok(pyo3::types::PyBytes::new(py, &raw_bytes)) } fn private_bytes<'p>( @@ -138,7 +138,7 @@ impl Ed25519PublicKey { py: pyo3::Python<'p>, ) -> CryptographyResult> { let raw_bytes = self.pkey.raw_public_key()?; - Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)) + Ok(pyo3::types::PyBytes::new(py, &raw_bytes)) } fn public_bytes<'p>( diff --git a/src/rust/src/backend/ed448.rs b/src/rust/src/backend/ed448.rs index 113819b8e53f..ba743d02c1ef 100644 --- a/src/rust/src/backend/ed448.rs +++ b/src/rust/src/backend/ed448.rs @@ -68,7 +68,7 @@ impl Ed448PrivateKey { ) -> CryptographyResult> { let mut signer = openssl::sign::Signer::new_without_digest(&self.pkey)?; let len = signer.len()?; - Ok(pyo3::types::PyBytes::new_bound_with(py, len, |b| { + Ok(pyo3::types::PyBytes::new_with(py, len, |b| { let n = signer .sign_oneshot(b, data.as_bytes()) .map_err(CryptographyError::from)?; @@ -92,7 +92,7 @@ impl Ed448PrivateKey { py: pyo3::Python<'p>, ) -> CryptographyResult> { let raw_bytes = self.pkey.raw_private_key()?; - Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)) + Ok(pyo3::types::PyBytes::new(py, &raw_bytes)) } fn private_bytes<'p>( @@ -135,7 +135,7 @@ impl Ed448PublicKey { py: pyo3::Python<'p>, ) -> CryptographyResult> { let raw_bytes = self.pkey.raw_public_key()?; - Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)) + Ok(pyo3::types::PyBytes::new(py, &raw_bytes)) } fn public_bytes<'p>( diff --git a/src/rust/src/backend/hashes.rs b/src/rust/src/backend/hashes.rs index 155ad6ec755c..09c75f336ec2 100644 --- a/src/rust/src/backend/hashes.rs +++ b/src/rust/src/backend/hashes.rs @@ -3,7 +3,6 @@ // for complete details. use pyo3::types::PyAnyMethods; -use pyo3::IntoPy; use std::borrow::Cow; use crate::buf::CffiBuf; @@ -93,7 +92,7 @@ impl Hash { let ctx = openssl::hash::Hasher::new(md)?; Ok(Hash { - algorithm: algorithm.clone().into_py(py), + algorithm: algorithm.clone().unbind(), ctx: Some(ctx), }) } @@ -115,7 +114,7 @@ impl Hash { let digest_size = algorithm .getattr(pyo3::intern!(py, "digest_size"))? .extract::()?; - let result = pyo3::types::PyBytes::new_bound_with(py, digest_size, |b| { + let result = pyo3::types::PyBytes::new_with(py, digest_size, |b| { ctx.finish_xof(b).unwrap(); Ok(()) })?; @@ -126,7 +125,7 @@ impl Hash { let data = self.get_mut_ctx()?.finish()?; self.ctx = None; - Ok(pyo3::types::PyBytes::new_bound(py, &data)) + Ok(pyo3::types::PyBytes::new(py, &data)) } fn copy(&self, py: pyo3::Python<'_>) -> CryptographyResult { diff --git a/src/rust/src/backend/hmac.rs b/src/rust/src/backend/hmac.rs index cce3593fa782..4e2d06943377 100644 --- a/src/rust/src/backend/hmac.rs +++ b/src/rust/src/backend/hmac.rs @@ -83,7 +83,7 @@ impl Hmac { ) -> CryptographyResult> { let data = self.get_mut_ctx()?.finish()?; self.ctx = None; - Ok(pyo3::types::PyBytes::new_bound(py, &data)) + Ok(pyo3::types::PyBytes::new(py, &data)) } fn verify(&mut self, py: pyo3::Python<'_>, signature: &[u8]) -> CryptographyResult<()> { diff --git a/src/rust/src/backend/kdf.rs b/src/rust/src/backend/kdf.rs index 0b4bfd54ed1f..2144caf1ea9a 100644 --- a/src/rust/src/backend/kdf.rs +++ b/src/rust/src/backend/kdf.rs @@ -21,7 +21,7 @@ pub(crate) fn derive_pbkdf2_hmac<'p>( ) -> CryptographyResult> { let md = hashes::message_digest_from_algorithm(py, algorithm)?; - Ok(pyo3::types::PyBytes::new_bound_with(py, length, |b| { + Ok(pyo3::types::PyBytes::new_with(py, length, |b| { openssl::pkcs5::pbkdf2_hmac(key_material.as_bytes(), salt, iterations, md, b).unwrap(); Ok(()) })?) @@ -125,11 +125,8 @@ impl Scrypt { } self.used = true; - Ok(pyo3::types::PyBytes::new_bound_with( - py, - self.length, - |b| { - openssl::pkcs5::scrypt(key_material.as_bytes(), self.salt.as_bytes(py), self.n, self.r, self.p, (usize::MAX / 2).try_into().unwrap(), b).map_err(|_| { + Ok(pyo3::types::PyBytes::new_with(py, self.length, |b| { + openssl::pkcs5::scrypt(key_material.as_bytes(), self.salt.as_bytes(py), self.n, self.r, self.p, (usize::MAX / 2).try_into().unwrap(), b).map_err(|_| { // memory required formula explained here: // https://blog.filippo.io/the-scrypt-parameters/ let min_memory = 128 * self.n * self.r / (1024 * 1024); @@ -137,8 +134,7 @@ impl Scrypt { "Not enough memory to derive key. These parameters require {min_memory}MB of memory." )) }) - }, - )?) + })?) } #[cfg(not(CRYPTOGRAPHY_IS_LIBRESSL))] @@ -286,25 +282,21 @@ impl Argon2id { return Err(exceptions::already_finalized_error()); } self.used = true; - Ok(pyo3::types::PyBytes::new_bound_with( - py, - self.length, - |b| { - openssl::kdf::argon2id( - None, - key_material.as_bytes(), - self.salt.as_bytes(py), - self.ad.as_ref().map(|ad| ad.as_bytes(py)), - self.secret.as_ref().map(|secret| secret.as_bytes(py)), - self.iterations, - self.lanes, - self.memory_cost, - b, - ) - .map_err(CryptographyError::from)?; - Ok(()) - }, - )?) + Ok(pyo3::types::PyBytes::new_with(py, self.length, |b| { + openssl::kdf::argon2id( + None, + key_material.as_bytes(), + self.salt.as_bytes(py), + self.ad.as_ref().map(|ad| ad.as_bytes(py)), + self.secret.as_ref().map(|secret| secret.as_bytes(py)), + self.iterations, + self.lanes, + self.memory_cost, + b, + ) + .map_err(CryptographyError::from)?; + Ok(()) + })?) } #[cfg(CRYPTOGRAPHY_OPENSSL_320_OR_GREATER)] diff --git a/src/rust/src/backend/keys.rs b/src/rust/src/backend/keys.rs index c16ff8628c2c..36c84aeebb8b 100644 --- a/src/rust/src/backend/keys.rs +++ b/src/rust/src/backend/keys.rs @@ -2,7 +2,7 @@ // 2.0, and the BSD License. See the LICENSE file in the root of this repository // for complete details. -use pyo3::IntoPy; +use pyo3::IntoPyObject; use crate::backend::utils; use crate::buf::CffiBuf; @@ -70,7 +70,9 @@ pub(crate) fn private_key_from_pkey( pkey, unsafe_skip_rsa_key_validation, )? - .into_py(py)), + .into_pyobject(py)? + .unbind() + .into_any()), openssl::pkey::Id::RSA_PSS => { // At the moment the way we handle RSA PSS keys is to strip the // PSS constraints from them and treat them as normal RSA keys @@ -81,34 +83,50 @@ pub(crate) fn private_key_from_pkey( let pkey = openssl::pkey::PKey::from_rsa(rsa)?; Ok( crate::backend::rsa::private_key_from_pkey(&pkey, unsafe_skip_rsa_key_validation)? - .into_py(py), + .into_pyobject(py)? + .into_any() + .unbind(), ) } - openssl::pkey::Id::EC => { - Ok(crate::backend::ec::private_key_from_pkey(py, pkey)?.into_py(py)) - } - openssl::pkey::Id::X25519 => { - Ok(crate::backend::x25519::private_key_from_pkey(pkey).into_py(py)) - } + openssl::pkey::Id::EC => Ok(crate::backend::ec::private_key_from_pkey(py, pkey)? + .into_pyobject(py)? + .into_any() + .unbind()), + openssl::pkey::Id::X25519 => Ok(crate::backend::x25519::private_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), #[cfg(all(not(CRYPTOGRAPHY_IS_LIBRESSL), not(CRYPTOGRAPHY_IS_BORINGSSL)))] - openssl::pkey::Id::X448 => { - Ok(crate::backend::x448::private_key_from_pkey(pkey).into_py(py)) - } + openssl::pkey::Id::X448 => Ok(crate::backend::x448::private_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), - openssl::pkey::Id::ED25519 => { - Ok(crate::backend::ed25519::private_key_from_pkey(pkey).into_py(py)) - } + openssl::pkey::Id::ED25519 => Ok(crate::backend::ed25519::private_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), #[cfg(all(not(CRYPTOGRAPHY_IS_LIBRESSL), not(CRYPTOGRAPHY_IS_BORINGSSL)))] - openssl::pkey::Id::ED448 => { - Ok(crate::backend::ed448::private_key_from_pkey(pkey).into_py(py)) - } - openssl::pkey::Id::DSA => Ok(crate::backend::dsa::private_key_from_pkey(pkey).into_py(py)), - openssl::pkey::Id::DH => Ok(crate::backend::dh::private_key_from_pkey(pkey).into_py(py)), + openssl::pkey::Id::ED448 => Ok(crate::backend::ed448::private_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), + openssl::pkey::Id::DSA => Ok(crate::backend::dsa::private_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), + openssl::pkey::Id::DH => Ok(crate::backend::dh::private_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), #[cfg(all(not(CRYPTOGRAPHY_IS_LIBRESSL), not(CRYPTOGRAPHY_IS_BORINGSSL)))] - openssl::pkey::Id::DHX => Ok(crate::backend::dh::private_key_from_pkey(pkey).into_py(py)), + openssl::pkey::Id::DHX => Ok(crate::backend::dh::private_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), _ => Err(CryptographyError::from( exceptions::UnsupportedAlgorithm::new_err("Unsupported key type."), )), @@ -190,29 +208,48 @@ fn public_key_from_pkey( // `id` is a separate argument so we can test this while passing something // unsupported. match id { - openssl::pkey::Id::RSA => Ok(crate::backend::rsa::public_key_from_pkey(pkey).into_py(py)), - openssl::pkey::Id::EC => { - Ok(crate::backend::ec::public_key_from_pkey(py, pkey)?.into_py(py)) - } - openssl::pkey::Id::X25519 => { - Ok(crate::backend::x25519::public_key_from_pkey(pkey).into_py(py)) - } + openssl::pkey::Id::RSA => Ok(crate::backend::rsa::public_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), + openssl::pkey::Id::EC => Ok(crate::backend::ec::public_key_from_pkey(py, pkey)? + .into_pyobject(py)? + .into_any() + .unbind()), + openssl::pkey::Id::X25519 => Ok(crate::backend::x25519::public_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), #[cfg(all(not(CRYPTOGRAPHY_IS_LIBRESSL), not(CRYPTOGRAPHY_IS_BORINGSSL)))] - openssl::pkey::Id::X448 => Ok(crate::backend::x448::public_key_from_pkey(pkey).into_py(py)), + openssl::pkey::Id::X448 => Ok(crate::backend::x448::public_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), - openssl::pkey::Id::ED25519 => { - Ok(crate::backend::ed25519::public_key_from_pkey(pkey).into_py(py)) - } + openssl::pkey::Id::ED25519 => Ok(crate::backend::ed25519::public_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), #[cfg(all(not(CRYPTOGRAPHY_IS_LIBRESSL), not(CRYPTOGRAPHY_IS_BORINGSSL)))] - openssl::pkey::Id::ED448 => { - Ok(crate::backend::ed448::public_key_from_pkey(pkey).into_py(py)) - } + openssl::pkey::Id::ED448 => Ok(crate::backend::ed448::public_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), - openssl::pkey::Id::DSA => Ok(crate::backend::dsa::public_key_from_pkey(pkey).into_py(py)), - openssl::pkey::Id::DH => Ok(crate::backend::dh::public_key_from_pkey(pkey).into_py(py)), + openssl::pkey::Id::DSA => Ok(crate::backend::dsa::public_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), + openssl::pkey::Id::DH => Ok(crate::backend::dh::public_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), #[cfg(all(not(CRYPTOGRAPHY_IS_LIBRESSL), not(CRYPTOGRAPHY_IS_BORINGSSL)))] - openssl::pkey::Id::DHX => Ok(crate::backend::dh::public_key_from_pkey(pkey).into_py(py)), + openssl::pkey::Id::DHX => Ok(crate::backend::dh::public_key_from_pkey(pkey) + .into_pyobject(py)? + .into_any() + .unbind()), _ => Err(CryptographyError::from( exceptions::UnsupportedAlgorithm::new_err("Unsupported key type."), diff --git a/src/rust/src/backend/poly1305.rs b/src/rust/src/backend/poly1305.rs index d955a9a90338..9b1d8165f8dc 100644 --- a/src/rust/src/backend/poly1305.rs +++ b/src/rust/src/backend/poly1305.rs @@ -32,7 +32,7 @@ impl Poly1305Boring { &mut self, py: pyo3::Python<'p>, ) -> CryptographyResult> { - let result = pyo3::types::PyBytes::new_bound_with(py, 16usize, |b| { + let result = pyo3::types::PyBytes::new_with(py, 16usize, |b| { self.context.finalize(b.as_mut()); Ok(()) })?; @@ -78,7 +78,7 @@ impl Poly1305Open { &mut self, py: pyo3::Python<'p>, ) -> CryptographyResult> { - let result = pyo3::types::PyBytes::new_bound_with(py, self.signer.len()?, |b| { + let result = pyo3::types::PyBytes::new_with(py, self.signer.len()?, |b| { let n = self.signer.sign(b).unwrap(); assert_eq!(n, b.len()); Ok(()) diff --git a/src/rust/src/backend/rsa.rs b/src/rust/src/backend/rsa.rs index 066b1412af92..79b385ffb73f 100644 --- a/src/rust/src/backend/rsa.rs +++ b/src/rust/src/backend/rsa.rs @@ -297,7 +297,7 @@ impl RsaPrivateKey { setup_signature_ctx(py, &mut ctx, padding, &algorithm, self.pkey.size(), true)?; let length = ctx.sign(data.as_bytes(), None)?; - Ok(pyo3::types::PyBytes::new_bound_with(py, length, |b| { + Ok(pyo3::types::PyBytes::new_with(py, length, |b| { let length = ctx.sign(data.as_bytes(), Some(b)).map_err(|_| { pyo3::exceptions::PyValueError::new_err( "Digest or salt length too long for key size. Use a larger key or shorter salt length if you are specifying a PSS salt", @@ -345,7 +345,7 @@ impl RsaPrivateKey { let result = ctx.decrypt(ciphertext, Some(&mut plaintext)); let py_result = - pyo3::types::PyBytes::new_bound(py, &plaintext[..*result.as_ref().unwrap_or(&length)]); + pyo3::types::PyBytes::new(py, &plaintext[..*result.as_ref().unwrap_or(&length)]); if result.is_err() { return Err(CryptographyError::from( pyo3::exceptions::PyValueError::new_err("Decryption failed"), @@ -458,7 +458,7 @@ impl RsaPublicKey { setup_encryption_ctx(py, &mut ctx, padding)?; let length = ctx.encrypt(plaintext, None)?; - Ok(pyo3::types::PyBytes::new_bound_with(py, length, |b| { + Ok(pyo3::types::PyBytes::new_with(py, length, |b| { let length = ctx .encrypt(plaintext, Some(b)) .map_err(|_| pyo3::exceptions::PyValueError::new_err("Encryption failed"))?; @@ -492,7 +492,7 @@ impl RsaPublicKey { .verify_recover(signature, Some(&mut buf)) .map_err(|_| exceptions::InvalidSignature::new_err(()))?; - Ok(pyo3::types::PyBytes::new_bound(py, &buf[..length])) + Ok(pyo3::types::PyBytes::new(py, &buf[..length])) } #[getter] @@ -537,17 +537,17 @@ impl RsaPublicKey { )] struct RsaPrivateNumbers { #[pyo3(get)] - p: pyo3::Py, + p: pyo3::Py, #[pyo3(get)] - q: pyo3::Py, + q: pyo3::Py, #[pyo3(get)] - d: pyo3::Py, + d: pyo3::Py, #[pyo3(get)] - dmp1: pyo3::Py, + dmp1: pyo3::Py, #[pyo3(get)] - dmq1: pyo3::Py, + dmq1: pyo3::Py, #[pyo3(get)] - iqmp: pyo3::Py, + iqmp: pyo3::Py, #[pyo3(get)] public_numbers: pyo3::Py, } @@ -559,21 +559,21 @@ struct RsaPrivateNumbers { )] struct RsaPublicNumbers { #[pyo3(get)] - e: pyo3::Py, + e: pyo3::Py, #[pyo3(get)] - n: pyo3::Py, + n: pyo3::Py, } #[allow(clippy::too_many_arguments)] fn check_private_key_components( - p: &pyo3::Bound<'_, pyo3::types::PyLong>, - q: &pyo3::Bound<'_, pyo3::types::PyLong>, - private_exponent: &pyo3::Bound<'_, pyo3::types::PyLong>, - dmp1: &pyo3::Bound<'_, pyo3::types::PyLong>, - dmq1: &pyo3::Bound<'_, pyo3::types::PyLong>, - iqmp: &pyo3::Bound<'_, pyo3::types::PyLong>, - public_exponent: &pyo3::Bound<'_, pyo3::types::PyLong>, - modulus: &pyo3::Bound<'_, pyo3::types::PyLong>, + p: &pyo3::Bound<'_, pyo3::types::PyInt>, + q: &pyo3::Bound<'_, pyo3::types::PyInt>, + private_exponent: &pyo3::Bound<'_, pyo3::types::PyInt>, + dmp1: &pyo3::Bound<'_, pyo3::types::PyInt>, + dmq1: &pyo3::Bound<'_, pyo3::types::PyInt>, + iqmp: &pyo3::Bound<'_, pyo3::types::PyInt>, + public_exponent: &pyo3::Bound<'_, pyo3::types::PyInt>, + modulus: &pyo3::Bound<'_, pyo3::types::PyInt>, ) -> CryptographyResult<()> { if modulus.lt(3)? { return Err(CryptographyError::from( @@ -654,12 +654,12 @@ fn check_private_key_components( impl RsaPrivateNumbers { #[new] fn new( - p: pyo3::Py, - q: pyo3::Py, - d: pyo3::Py, - dmp1: pyo3::Py, - dmq1: pyo3::Py, - iqmp: pyo3::Py, + p: pyo3::Py, + q: pyo3::Py, + d: pyo3::Py, + dmp1: pyo3::Py, + dmq1: pyo3::Py, + iqmp: pyo3::Py, public_numbers: pyo3::Py, ) -> RsaPrivateNumbers { Self { @@ -716,12 +716,12 @@ impl RsaPrivateNumbers { py: pyo3::Python<'_>, other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { - Ok(self.p.bind(py).eq(other.p.bind(py))? - && self.q.bind(py).eq(other.q.bind(py))? - && self.d.bind(py).eq(other.d.bind(py))? - && self.dmp1.bind(py).eq(other.dmp1.bind(py))? - && self.dmq1.bind(py).eq(other.dmq1.bind(py))? - && self.iqmp.bind(py).eq(other.iqmp.bind(py))? + Ok((**self.p.bind(py)).eq(other.p.bind(py))? + && (**self.q.bind(py)).eq(other.q.bind(py))? + && (**self.d.bind(py)).eq(other.d.bind(py))? + && (**self.dmp1.bind(py)).eq(other.dmp1.bind(py))? + && (**self.dmq1.bind(py)).eq(other.dmq1.bind(py))? + && (**self.iqmp.bind(py)).eq(other.iqmp.bind(py))? && self .public_numbers .bind(py) @@ -742,8 +742,8 @@ impl RsaPrivateNumbers { } fn check_public_key_components( - e: &pyo3::Bound<'_, pyo3::types::PyLong>, - n: &pyo3::Bound<'_, pyo3::types::PyLong>, + e: &pyo3::Bound<'_, pyo3::types::PyInt>, + n: &pyo3::Bound<'_, pyo3::types::PyInt>, ) -> CryptographyResult<()> { if n.lt(3)? { return Err(CryptographyError::from( @@ -769,7 +769,7 @@ fn check_public_key_components( #[pyo3::pymethods] impl RsaPublicNumbers { #[new] - fn new(e: pyo3::Py, n: pyo3::Py) -> RsaPublicNumbers { + fn new(e: pyo3::Py, n: pyo3::Py) -> RsaPublicNumbers { RsaPublicNumbers { e, n } } @@ -797,7 +797,10 @@ impl RsaPublicNumbers { py: pyo3::Python<'_>, other: pyo3::PyRef<'_, Self>, ) -> CryptographyResult { - Ok(self.e.bind(py).eq(other.e.bind(py))? && self.n.bind(py).eq(other.n.bind(py))?) + Ok( + (**self.e.bind(py)).eq(other.e.bind(py))? + && (**self.n.bind(py)).eq(other.n.bind(py))?, + ) } fn __hash__(&self, py: pyo3::Python<'_>) -> CryptographyResult { diff --git a/src/rust/src/backend/utils.rs b/src/rust/src/backend/utils.rs index 77b733ab2315..832fdf3542f5 100644 --- a/src/rust/src/backend/utils.rs +++ b/src/rust/src/backend/utils.rs @@ -6,7 +6,6 @@ use crate::backend::hashes::Hash; use crate::error::{CryptographyError, CryptographyResult}; use crate::{error, types}; use pyo3::types::{PyAnyMethods, PyBytesMethods}; -use pyo3::ToPyObject; pub(crate) fn py_int_to_bn( py: pyo3::Python<'_>, @@ -30,7 +29,7 @@ pub(crate) fn bn_to_py_int<'p>( ) -> CryptographyResult> { assert!(!b.is_negative()); - let int_type = py.get_type_bound::(); + let int_type = py.get_type::(); Ok(int_type.call_method1( pyo3::intern!(py, "from_bytes"), (b.to_vec(), pyo3::intern!(py, "big")), @@ -87,7 +86,7 @@ pub(crate) fn pkey_private_bytes<'p>( ))); } let raw_bytes = pkey.raw_private_key()?; - return Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &raw_bytes)); } let py_password; @@ -127,7 +126,7 @@ pub(crate) fn pkey_private_bytes<'p>( password, )? }; - return Ok(pyo3::types::PyBytes::new_bound(py, &pem_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &pem_bytes)); } else if encoding.is(&types::ENCODING_DER.get(py)?) { let der_bytes = if password.is_empty() { pkey.private_key_to_pkcs8()? @@ -137,7 +136,7 @@ pub(crate) fn pkey_private_bytes<'p>( password, )? }; - return Ok(pyo3::types::PyBytes::new_bound(py, &der_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &der_bytes)); } return Err(CryptographyError::from( pyo3::exceptions::PyValueError::new_err("Unsupported encoding for PKCS8"), @@ -162,7 +161,7 @@ pub(crate) fn pkey_private_bytes<'p>( password, )? }; - return Ok(pyo3::types::PyBytes::new_bound(py, &pem_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &pem_bytes)); } else if encoding.is(&types::ENCODING_DER.get(py)?) { if !password.is_empty() { return Err(CryptographyError::from( @@ -173,7 +172,7 @@ pub(crate) fn pkey_private_bytes<'p>( } let der_bytes = rsa.private_key_to_der()?; - return Ok(pyo3::types::PyBytes::new_bound(py, &der_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &der_bytes)); } } else if let Ok(dsa) = pkey.dsa() { if encoding.is(&types::ENCODING_PEM.get(py)?) { @@ -185,7 +184,7 @@ pub(crate) fn pkey_private_bytes<'p>( password, )? }; - return Ok(pyo3::types::PyBytes::new_bound(py, &pem_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &pem_bytes)); } else if encoding.is(&types::ENCODING_DER.get(py)?) { if !password.is_empty() { return Err(CryptographyError::from( @@ -196,7 +195,7 @@ pub(crate) fn pkey_private_bytes<'p>( } let der_bytes = dsa.private_key_to_der()?; - return Ok(pyo3::types::PyBytes::new_bound(py, &der_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &der_bytes)); } } else if let Ok(ec) = pkey.ec_key() { if encoding.is(&types::ENCODING_PEM.get(py)?) { @@ -208,7 +207,7 @@ pub(crate) fn pkey_private_bytes<'p>( password, )? }; - return Ok(pyo3::types::PyBytes::new_bound(py, &pem_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &pem_bytes)); } else if encoding.is(&types::ENCODING_DER.get(py)?) { if !password.is_empty() { return Err(CryptographyError::from( @@ -219,7 +218,7 @@ pub(crate) fn pkey_private_bytes<'p>( } let der_bytes = ec.private_key_to_der()?; - return Ok(pyo3::types::PyBytes::new_bound(py, &der_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &der_bytes)); } } } @@ -283,17 +282,17 @@ pub(crate) fn pkey_public_bytes<'p>( )); } let raw_bytes = pkey.raw_public_key()?; - return Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &raw_bytes)); } // SubjectPublicKeyInfo + PEM/DER if format.is(&types::PUBLIC_FORMAT_SUBJECT_PUBLIC_KEY_INFO.get(py)?) { if encoding.is(&types::ENCODING_PEM.get(py)?) { let pem_bytes = pkey.public_key_to_pem()?; - return Ok(pyo3::types::PyBytes::new_bound(py, &pem_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &pem_bytes)); } else if encoding.is(&types::ENCODING_DER.get(py)?) { let der_bytes = pkey.public_key_to_der()?; - return Ok(pyo3::types::PyBytes::new_bound(py, &der_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &der_bytes)); } return Err(CryptographyError::from( pyo3::exceptions::PyValueError::new_err( @@ -319,7 +318,7 @@ pub(crate) fn pkey_public_bytes<'p>( let data = ec .public_key() .to_bytes(ec.group(), point_form, &mut bn_ctx)?; - return Ok(pyo3::types::PyBytes::new_bound(py, &data)); + return Ok(pyo3::types::PyBytes::new(py, &data)); } } @@ -327,10 +326,10 @@ pub(crate) fn pkey_public_bytes<'p>( if format.is(&types::PUBLIC_FORMAT_PKCS1.get(py)?) { if encoding.is(&types::ENCODING_PEM.get(py)?) { let pem_bytes = rsa.public_key_to_pem_pkcs1()?; - return Ok(pyo3::types::PyBytes::new_bound(py, &pem_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &pem_bytes)); } else if encoding.is(&types::ENCODING_DER.get(py)?) { let der_bytes = rsa.public_key_to_der_pkcs1()?; - return Ok(pyo3::types::PyBytes::new_bound(py, &der_bytes)); + return Ok(pyo3::types::PyBytes::new(py, &der_bytes)); } return Err(CryptographyError::from( pyo3::exceptions::PyValueError::new_err( @@ -393,7 +392,7 @@ pub(crate) fn calculate_digest_and_algorithm<'p>( (algorithm.clone(), BytesOrPyBytes::PyBytes(h.finalize(py)?)) }; - if data.as_bytes().len() != algorithm.getattr("digest_size")?.extract()? { + if data.as_bytes().len() != (algorithm.getattr("digest_size")?.extract::()?) { return Err(CryptographyError::from( pyo3::exceptions::PyValueError::new_err( "The provided data must be the same length as the hash algorithm's digest size.", @@ -461,7 +460,7 @@ pub(crate) fn handle_key_load_result( Err(CryptographyError::from( pyo3::exceptions::PyValueError::new_err(( "Could not deserialize key data. The data may be in an incorrect format, the provided password may be incorrect, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).", - errors.to_object(py), + errors.unbind(), )) )) } diff --git a/src/rust/src/backend/x25519.rs b/src/rust/src/backend/x25519.rs index 84f355f49787..4cc6124aefc5 100644 --- a/src/rust/src/backend/x25519.rs +++ b/src/rust/src/backend/x25519.rs @@ -70,17 +70,13 @@ impl X25519PrivateKey { let mut deriver = openssl::derive::Deriver::new(&self.pkey)?; deriver.set_peer(&peer_public_key.pkey)?; - Ok(pyo3::types::PyBytes::new_bound_with( - py, - deriver.len()?, - |b| { - let n = deriver.derive(b).map_err(|_| { - pyo3::exceptions::PyValueError::new_err("Error computing shared key.") - })?; - assert_eq!(n, b.len()); - Ok(()) - }, - )?) + Ok(pyo3::types::PyBytes::new_with(py, deriver.len()?, |b| { + let n = deriver.derive(b).map_err(|_| { + pyo3::exceptions::PyValueError::new_err("Error computing shared key.") + })?; + assert_eq!(n, b.len()); + Ok(()) + })?) } fn public_key(&self) -> CryptographyResult { @@ -98,7 +94,7 @@ impl X25519PrivateKey { py: pyo3::Python<'p>, ) -> CryptographyResult> { let raw_bytes = self.pkey.raw_private_key()?; - Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)) + Ok(pyo3::types::PyBytes::new(py, &raw_bytes)) } fn private_bytes<'p>( @@ -128,7 +124,7 @@ impl X25519PublicKey { py: pyo3::Python<'p>, ) -> CryptographyResult> { let raw_bytes = self.pkey.raw_public_key()?; - Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)) + Ok(pyo3::types::PyBytes::new(py, &raw_bytes)) } fn public_bytes<'p>( diff --git a/src/rust/src/backend/x448.rs b/src/rust/src/backend/x448.rs index 0e9aa1c99194..953302dd63d1 100644 --- a/src/rust/src/backend/x448.rs +++ b/src/rust/src/backend/x448.rs @@ -69,17 +69,13 @@ impl X448PrivateKey { let mut deriver = openssl::derive::Deriver::new(&self.pkey)?; deriver.set_peer(&peer_public_key.pkey)?; - Ok(pyo3::types::PyBytes::new_bound_with( - py, - deriver.len()?, - |b| { - let n = deriver.derive(b).map_err(|_| { - pyo3::exceptions::PyValueError::new_err("Error computing shared key.") - })?; - assert_eq!(n, b.len()); - Ok(()) - }, - )?) + Ok(pyo3::types::PyBytes::new_with(py, deriver.len()?, |b| { + let n = deriver.derive(b).map_err(|_| { + pyo3::exceptions::PyValueError::new_err("Error computing shared key.") + })?; + assert_eq!(n, b.len()); + Ok(()) + })?) } fn public_key(&self) -> CryptographyResult { @@ -97,7 +93,7 @@ impl X448PrivateKey { py: pyo3::Python<'p>, ) -> CryptographyResult> { let raw_bytes = self.pkey.raw_private_key()?; - Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)) + Ok(pyo3::types::PyBytes::new(py, &raw_bytes)) } fn private_bytes<'p>( @@ -127,7 +123,7 @@ impl X448PublicKey { py: pyo3::Python<'p>, ) -> CryptographyResult> { let raw_bytes = self.pkey.raw_public_key()?; - Ok(pyo3::types::PyBytes::new_bound(py, &raw_bytes)) + Ok(pyo3::types::PyBytes::new(py, &raw_bytes)) } fn public_bytes<'p>( diff --git a/src/rust/src/buf.rs b/src/rust/src/buf.rs index 303e5ff86fe7..e55bf12a45be 100644 --- a/src/rust/src/buf.rs +++ b/src/rust/src/buf.rs @@ -19,7 +19,7 @@ fn _extract_buffer_length<'p>( ) -> pyo3::PyResult<(pyo3::Bound<'p, pyo3::PyAny>, usize)> { let py = pyobj.py(); let bufobj = if mutable { - let kwargs = [(pyo3::intern!(py, "require_writable"), true)].into_py_dict_bound(py); + let kwargs = [(pyo3::intern!(py, "require_writable"), true)].into_py_dict(py)?; types::FFI_FROM_BUFFER .get(py)? .call((pyobj,), Some(&kwargs))? diff --git a/src/rust/src/error.rs b/src/rust/src/error.rs index 7eb989b63c6d..f0c10391ff2f 100644 --- a/src/rust/src/error.rs +++ b/src/rust/src/error.rs @@ -5,7 +5,6 @@ use std::fmt; use pyo3::types::PyListMethods; -use pyo3::ToPyObject; use crate::exceptions; @@ -87,7 +86,7 @@ pub(crate) fn list_from_openssl_error<'p>( py: pyo3::Python<'p>, error_stack: &openssl::error::ErrorStack, ) -> pyo3::Bound<'p, pyo3::types::PyList> { - let errors = pyo3::types::PyList::empty_bound(py); + let errors = pyo3::types::PyList::empty(py); for e in error_stack.errors() { errors .append( @@ -146,7 +145,7 @@ impl From for pyo3::PyErr { CryptographyError::Py(py_error) => py_error, CryptographyError::OpenSSL(ref error_stack) => pyo3::Python::with_gil(|py| { let errors = list_from_openssl_error(py, error_stack); - exceptions::InternalError::new_err((e.to_string(), errors.to_object(py))) + exceptions::InternalError::new_err((e.to_string(), errors.unbind())) }), } } @@ -211,7 +210,7 @@ impl OpenSSLError { pub(crate) fn capture_error_stack( py: pyo3::Python<'_>, ) -> pyo3::PyResult> { - let errs = pyo3::types::PyList::empty_bound(py); + let errs = pyo3::types::PyList::empty(py); for e in openssl::error::ErrorStack::get().errors() { errs.append(pyo3::Bound::new(py, OpenSSLError { e: e.clone() })?)?; } diff --git a/src/rust/src/oid.rs b/src/rust/src/oid.rs index fb64837b6bff..c034c3dcb601 100644 --- a/src/rust/src/oid.rs +++ b/src/rust/src/oid.rs @@ -29,7 +29,7 @@ impl ObjectIdentifier { #[getter] fn _name<'p>( - slf: pyo3::PyRef<'_, Self>, + slf: pyo3::PyRef<'p, Self>, py: pyo3::Python<'p>, ) -> pyo3::PyResult> { types::OID_NAMES diff --git a/src/rust/src/padding.rs b/src/rust/src/padding.rs index 0031f148ea15..eb16cfaaad41 100644 --- a/src/rust/src/padding.rs +++ b/src/rust/src/padding.rs @@ -103,7 +103,7 @@ impl PKCS7PaddingContext { Some(v) => { let pad_size = self.block_size - (v % self.block_size); let pad = vec![pad_size as u8; pad_size]; - Ok(pyo3::types::PyBytes::new_bound(py, &pad)) + Ok(pyo3::types::PyBytes::new(py, &pad)) } None => Err(exceptions::already_finalized_error()), } @@ -137,7 +137,7 @@ impl PKCS7UnpaddingContext { let finished_blocks = (v.len() / self.block_size).saturating_sub(1); let result_size = finished_blocks * self.block_size; let result = v.drain(..result_size); - Ok(pyo3::types::PyBytes::new_bound(py, result.as_slice())) + Ok(pyo3::types::PyBytes::new(py, result.as_slice())) } None => Err(exceptions::already_finalized_error()), } @@ -162,7 +162,7 @@ impl PKCS7UnpaddingContext { let pad_size = *v.last().unwrap(); let result = &v[..v.len() - pad_size as usize]; - Ok(pyo3::types::PyBytes::new_bound(py, result)) + Ok(pyo3::types::PyBytes::new(py, result)) } None => Err(exceptions::already_finalized_error()), } diff --git a/src/rust/src/pkcs12.rs b/src/rust/src/pkcs12.rs index d58e339849eb..743a3cb3101b 100644 --- a/src/rust/src/pkcs12.rs +++ b/src/rust/src/pkcs12.rs @@ -10,7 +10,7 @@ use crate::x509::certificate::Certificate; use crate::{types, x509}; use cryptography_x509::common::Utf8StoredBMPString; use pyo3::types::{PyAnyMethods, PyBytesMethods, PyListMethods}; -use pyo3::IntoPy; +use pyo3::IntoPyObject; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -205,10 +205,10 @@ impl EncryptionAlgorithm { let triple_des = types::TRIPLE_DES .get(py)? - .call1((pyo3::types::PyBytes::new_bound(py, &key),))?; + .call1((pyo3::types::PyBytes::new(py, &key),))?; let cbc = types::CBC .get(py)? - .call1((pyo3::types::PyBytes::new_bound(py, &iv),))?; + .call1((pyo3::types::PyBytes::new(py, &iv),))?; symmetric_encrypt(py, triple_des, cbc, data) } @@ -415,7 +415,7 @@ fn decode_encryption_algorithm<'a>( if encryption_algorithm.is_instance(&types::NO_ENCRYPTION.get(py)?)? { Ok(( - pyo3::types::PyBytes::new_bound(py, b"").extract()?, + pyo3::types::PyBytes::new(py, b"").extract()?, default_hmac_alg, default_hmac_kdf_iter, default_cipher_kdf_iter, @@ -540,7 +540,7 @@ fn serialize_key_and_certificates<'p>( } if let Some(cas) = cas { - for cert in cas.iter()? { + for cert in cas.try_iter()? { ca_certs.push(cert?.extract::()?); } @@ -715,10 +715,7 @@ fn serialize_key_and_certificates<'p>( iterations: mac_kdf_iter, }), }; - Ok(pyo3::types::PyBytes::new_bound( - py, - &asn1::write_single(&p12)?, - )) + Ok(pyo3::types::PyBytes::new(py, &asn1::write_single(&p12)?)) } fn decode_p12( @@ -767,14 +764,14 @@ fn load_key_and_certificates<'p>( py.None() }; let cert = if let Some(ossl_cert) = p12.cert { - let cert_der = pyo3::types::PyBytes::new_bound(py, &ossl_cert.to_der()?).unbind(); + let cert_der = pyo3::types::PyBytes::new(py, &ossl_cert.to_der()?).unbind(); Some(x509::certificate::load_der_x509_certificate( py, cert_der, None, )?) } else { None }; - let additional_certs = pyo3::types::PyList::empty_bound(py); + let additional_certs = pyo3::types::PyList::empty(py); if let Some(ossl_certs) = p12.ca { cfg_if::cfg_if! { if #[cfg(any( @@ -787,9 +784,9 @@ fn load_key_and_certificates<'p>( }; for ossl_cert in it { - let cert_der = pyo3::types::PyBytes::new_bound(py, &ossl_cert.to_der()?).unbind(); + let cert_der = pyo3::types::PyBytes::new(py, &ossl_cert.to_der()?).unbind(); let cert = x509::certificate::load_der_x509_certificate(py, cert_der, None)?; - additional_certs.append(cert.into_py(py))?; + additional_certs.append(cert)?; } } @@ -814,17 +811,20 @@ fn load_pkcs12<'p>( py.None() }; let cert = if let Some(ossl_cert) = p12.cert { - let cert_der = pyo3::types::PyBytes::new_bound(py, &ossl_cert.to_der()?).unbind(); + let cert_der = pyo3::types::PyBytes::new(py, &ossl_cert.to_der()?).unbind(); let cert = x509::certificate::load_der_x509_certificate(py, cert_der, None)?; let alias = ossl_cert .alias() - .map(|a| pyo3::types::PyBytes::new_bound(py, a).unbind()); + .map(|a| pyo3::types::PyBytes::new(py, a).unbind()); - PKCS12Certificate::new(pyo3::Py::new(py, cert)?, alias).into_py(py) + PKCS12Certificate::new(pyo3::Py::new(py, cert)?, alias) + .into_pyobject(py)? + .into_any() + .unbind() } else { py.None() }; - let additional_certs = pyo3::types::PyList::empty_bound(py); + let additional_certs = pyo3::types::PyList::empty(py); if let Some(ossl_certs) = p12.ca { cfg_if::cfg_if! { if #[cfg(any( @@ -837,13 +837,13 @@ fn load_pkcs12<'p>( }; for ossl_cert in it { - let cert_der = pyo3::types::PyBytes::new_bound(py, &ossl_cert.to_der()?).unbind(); + let cert_der = pyo3::types::PyBytes::new(py, &ossl_cert.to_der()?).unbind(); let cert = x509::certificate::load_der_x509_certificate(py, cert_der, None)?; let alias = ossl_cert .alias() - .map(|a| pyo3::types::PyBytes::new_bound(py, a).unbind()); + .map(|a| pyo3::types::PyBytes::new(py, a).unbind()); - let p12_cert = PKCS12Certificate::new(pyo3::Py::new(py, cert)?, alias).into_py(py); + let p12_cert = PKCS12Certificate::new(pyo3::Py::new(py, cert)?, alias); additional_certs.append(p12_cert)?; } } diff --git a/src/rust/src/pkcs7.rs b/src/rust/src/pkcs7.rs index f8beaf4c2453..ec328e2b0920 100644 --- a/src/rust/src/pkcs7.rs +++ b/src/rust/src/pkcs7.rs @@ -14,8 +14,6 @@ use once_cell::sync::Lazy; #[cfg(not(CRYPTOGRAPHY_IS_BORINGSSL))] use openssl::pkcs7::Pkcs7; use pyo3::types::{PyAnyMethods, PyBytesMethods, PyListMethods}; -#[cfg(not(CRYPTOGRAPHY_IS_BORINGSSL))] -use pyo3::IntoPy; use crate::asn1::encode_der_data; use crate::buf::CffiBuf; @@ -441,11 +439,11 @@ fn load_pkcs7_certificates( ), )), Some(certificates) => { - let result = pyo3::types::PyList::empty_bound(py); + let result = pyo3::types::PyList::empty(py); for c in certificates { - let cert_der = pyo3::types::PyBytes::new_bound(py, c.to_der()?.as_slice()).unbind(); + let cert_der = pyo3::types::PyBytes::new(py, c.to_der()?.as_slice()).unbind(); let cert = load_der_x509_certificate(py, cert_der, None)?; - result.append(cert.into_py(py))?; + result.append(cert)?; } Ok(result) } diff --git a/src/rust/src/test_support.rs b/src/rust/src/test_support.rs index 9b37b6c51056..524e904873df 100644 --- a/src/rust/src/test_support.rs +++ b/src/rust/src/test_support.rs @@ -144,7 +144,7 @@ fn pkcs7_decrypt<'p>( let result = p7.decrypt(&pkey_ossl, &cert_ossl, flags)?; - Ok(pyo3::types::PyBytes::new_bound(py, &result)) + Ok(pyo3::types::PyBytes::new(py, &result)) } #[pyo3::pymodule] diff --git a/src/rust/src/types.rs b/src/rust/src/types.rs index af7e4e1624ed..3c36145cf32e 100644 --- a/src/rust/src/types.rs +++ b/src/rust/src/types.rs @@ -21,7 +21,7 @@ impl LazyPyImport { pub fn get<'p>(&'p self, py: pyo3::Python<'p>) -> pyo3::PyResult> { let p = self.value.get_or_try_init(py, || { - let mut obj = py.import_bound(self.module)?.into_any(); + let mut obj = py.import(self.module)?.into_any(); for name in self.names { obj = obj.getattr(*name)?; } diff --git a/src/rust/src/x509/certificate.rs b/src/rust/src/x509/certificate.rs index 8aa2e9343405..5758acccb456 100644 --- a/src/rust/src/x509/certificate.rs +++ b/src/rust/src/x509/certificate.rs @@ -18,7 +18,6 @@ use cryptography_x509::extensions::{Extension, SubjectAlternativeName}; use cryptography_x509::{common, oid}; use cryptography_x509_verification::ops::CryptoOps; use pyo3::types::{PyAnyMethods, PyListMethods}; -use pyo3::{IntoPy, ToPyObject}; use crate::asn1::{ big_byte_slice_to_py_int, encode_der_data, oid_to_py_oid, py_uint_to_big_endian_bytes, @@ -143,7 +142,7 @@ impl Certificate { py: pyo3::Python<'p>, ) -> CryptographyResult> { let result = asn1::write_single(&self.raw.borrow_dependent().tbs_cert)?; - Ok(pyo3::types::PyBytes::new_bound(py, &result)) + Ok(pyo3::types::PyBytes::new(py, &result)) } #[getter] @@ -177,13 +176,13 @@ impl Certificate { tbs_precert.raw_extensions = Some(filtered_extensions); let result = asn1::write_single(&tbs_precert)?; - Ok(pyo3::types::PyBytes::new_bound(py, &result)) + Ok(pyo3::types::PyBytes::new(py, &result)) } Err(DuplicateExtensionsError(oid)) => { let oid_obj = oid_to_py_oid(py, &oid)?; Err(exceptions::DuplicateExtension::new_err(( format!("Duplicate {} extension found", &oid), - oid_obj.into_py(py), + oid_obj.unbind(), )) .into()) } @@ -192,7 +191,7 @@ impl Certificate { #[getter] fn signature<'p>(&self, py: pyo3::Python<'p>) -> pyo3::Bound<'p, pyo3::types::PyBytes> { - pyo3::types::PyBytes::new_bound(py, self.raw.borrow_dependent().signature.as_bytes()) + pyo3::types::PyBytes::new(py, self.raw.borrow_dependent().signature.as_bytes()) } #[getter] @@ -201,12 +200,8 @@ impl Certificate { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_42.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to not_valid_before_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to not_valid_before_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; let dt = &self .raw .borrow_dependent() @@ -238,12 +233,8 @@ impl Certificate { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_42.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to not_valid_after_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to not_valid_after_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; let dt = &self .raw .borrow_dependent() @@ -382,7 +373,7 @@ pub(crate) fn load_pem_x509_certificate( )?; load_der_x509_certificate( py, - pyo3::types::PyBytes::new_bound(py, parsed.contents()).unbind(), + pyo3::types::PyBytes::new(py, parsed.contents()).unbind(), None, ) } @@ -398,7 +389,7 @@ pub(crate) fn load_pem_x509_certificates( .map(|p| { load_der_x509_certificate( py, - pyo3::types::PyBytes::new_bound(py, p.contents()).unbind(), + pyo3::types::PyBytes::new(py, p.contents()).unbind(), None, ) }) @@ -444,12 +435,8 @@ pub(crate) fn load_der_x509_certificate( fn warn_if_negative_serial(py: pyo3::Python<'_>, bytes: &'_ [u8]) -> pyo3::PyResult<()> { if bytes[0] & 0x80 != 0 { let warning_cls = types::DEPRECATED_IN_36.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Parsed a negative serial number, which is disallowed by RFC 5280. Loading this certificate will cause an exception in the next release of cryptography.", - 1, - )?; + let message = std::ffi::CString::new("Parsed a negative serial number, which is disallowed by RFC 5280. Loading this certificate will cause an exception in the next release of cryptography.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; } Ok(()) } @@ -470,12 +457,8 @@ fn warn_if_invalid_params( // This can also be triggered by an Intel On Die certificate // https://github.com/pyca/cryptography/issues/11723 let warning_cls = types::DEPRECATED_IN_41.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "The parsed certificate contains a NULL parameter value in its signature algorithm parameters. This is invalid and will be rejected in a future version of cryptography. If this certificate was created via Java, please upgrade to JDK21+ or the latest JDK11/17 once a fix is issued. If this certificate was created in some other fashion please report the issue to the cryptography issue tracker. See https://github.com/pyca/cryptography/issues/8996 and https://github.com/pyca/cryptography/issues/9253 for more details.", - 2, - )?; + let message = std::ffi::CString::new("The parsed certificate contains a NULL parameter value in its signature algorithm parameters. This is invalid and will be rejected in a future version of cryptography. If this certificate was created via Java, please upgrade to JDK21+ or the latest JDK11/17 once a fix is issued. If this certificate was created in some other fashion please report the issue to the cryptography issue tracker. See https://github.com/pyca/cryptography/issues/8996 and https://github.com/pyca/cryptography/issues/9253 for more details.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 2)?; } _ => {} } @@ -487,33 +470,31 @@ fn parse_display_text( text: DisplayText<'_>, ) -> pyo3::PyResult { match text { - DisplayText::IA5String(o) => { - Ok(pyo3::types::PyString::new_bound(py, o.as_str()).to_object(py)) - } - DisplayText::Utf8String(o) => { - Ok(pyo3::types::PyString::new_bound(py, o.as_str()).to_object(py)) - } + DisplayText::IA5String(o) => Ok(pyo3::types::PyString::new(py, o.as_str()) + .into_any() + .unbind()), + DisplayText::Utf8String(o) => Ok(pyo3::types::PyString::new(py, o.as_str()) + .into_any() + .unbind()), DisplayText::VisibleString(o) => { if asn1::VisibleString::new(o.as_str()).is_none() { let warning_cls = types::DEPRECATED_IN_41.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Invalid ASN.1 (UTF-8 characters in a VisibleString) in the explicit text and/or notice reference of the certificate policies extension. In a future version of cryptography, an exception will be raised.", - 1, - )?; + let message = std::ffi::CString::new("Invalid ASN.1 (UTF-8 characters in a VisibleString) in the explicit text and/or notice reference of the certificate policies extension. In a future version of cryptography, an exception will be raised.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; } - Ok(pyo3::types::PyString::new_bound(py, o.as_str()).to_object(py)) + Ok(pyo3::types::PyString::new(py, o.as_str()) + .into_any() + .unbind()) } DisplayText::BmpString(o) => { - let py_bytes = pyo3::types::PyBytes::new_bound(py, o.as_utf16_be_bytes()); + let py_bytes = pyo3::types::PyBytes::new(py, o.as_utf16_be_bytes()); // TODO: do the string conversion in rust perhaps Ok(py_bytes .call_method1( pyo3::intern!(py, "decode"), (pyo3::intern!(py, "utf_16_be"),), )? - .to_object(py)) + .unbind()) } } } @@ -529,30 +510,32 @@ fn parse_user_notice( let nr = match un.notice_ref { Some(data) => { let org = parse_display_text(py, data.organization)?; - let numbers = pyo3::types::PyList::empty_bound(py); + let numbers = pyo3::types::PyList::empty(py); for num in data.notice_numbers.unwrap_read().clone() { numbers.append(big_byte_slice_to_py_int(py, num.as_bytes())?)?; } types::NOTICE_REFERENCE .get(py)? .call1((org, numbers))? - .to_object(py) + .unbind() } None => py.None(), }; - Ok(types::USER_NOTICE.get(py)?.call1((nr, et))?.to_object(py)) + Ok(types::USER_NOTICE.get(py)?.call1((nr, et))?.unbind()) } fn parse_policy_qualifiers<'a>( py: pyo3::Python<'_>, policy_qualifiers: &asn1::SequenceOf<'a, PolicyQualifierInfo<'a>>, ) -> Result { - let py_pq = pyo3::types::PyList::empty_bound(py); + let py_pq = pyo3::types::PyList::empty(py); for pqi in policy_qualifiers.clone() { let qualifier = match pqi.qualifier { Qualifier::CpsUri(data) => { if pqi.policy_qualifier_id == oid::CP_CPS_URI_OID { - pyo3::types::PyString::new_bound(py, data.as_str()).to_object(py) + pyo3::types::PyString::new(py, data.as_str()) + .into_any() + .unbind() } else { return Err(CryptographyError::from( pyo3::exceptions::PyValueError::new_err( @@ -574,7 +557,7 @@ fn parse_policy_qualifiers<'a>( }; py_pq.append(qualifier)?; } - Ok(py_pq.to_object(py)) + Ok(py_pq.into_any().unbind()) } fn parse_cp( @@ -582,7 +565,7 @@ fn parse_cp( ext: &Extension<'_>, ) -> Result { let cp = ext.value::>>()?; - let certificate_policies = pyo3::types::PyList::empty_bound(py); + let certificate_policies = pyo3::types::PyList::empty(py); for policyinfo in cp { let pi_oid = oid_to_py_oid(py, &policyinfo.policy_identifier)?; let py_pqis = match policyinfo.policy_qualifiers { @@ -596,18 +579,18 @@ fn parse_cp( .call1((pi_oid, py_pqis))?; certificate_policies.append(pi)?; } - Ok(certificate_policies.to_object(py)) + Ok(certificate_policies.into_any().unbind()) } fn parse_general_subtrees( py: pyo3::Python<'_>, subtrees: SequenceOfSubtrees<'_>, ) -> Result { - let gns = pyo3::types::PyList::empty_bound(py); + let gns = pyo3::types::PyList::empty(py); for gs in subtrees.unwrap_read().clone() { gns.append(x509::parse_general_name(py, gs.base)?)?; } - Ok(gns.to_object(py)) + Ok(gns.into_any().unbind()) } pub(crate) fn parse_distribution_point_name( @@ -642,7 +625,7 @@ fn parse_distribution_point( Ok(types::DISTRIBUTION_POINT .get(py)? .call1((full_name, relative_name, reasons, crl_issuer))? - .to_object(py)) + .unbind()) } pub(crate) fn parse_distribution_points( @@ -650,12 +633,12 @@ pub(crate) fn parse_distribution_points( ext: &Extension<'_>, ) -> Result { let dps = ext.value::>>()?; - let py_dps = pyo3::types::PyList::empty_bound(py); + let py_dps = pyo3::types::PyList::empty(py); for dp in dps { let py_dp = parse_distribution_point(py, dp)?; py_dps.append(py_dp)?; } - Ok(py_dps.to_object(py)) + Ok(py_dps.into_any().unbind()) } pub(crate) fn parse_distribution_point_reasons( @@ -672,7 +655,7 @@ pub(crate) fn parse_distribution_point_reasons( vec.push(reason_bit_mapping.get_item(i)?); } } - pyo3::types::PyFrozenSet::new_bound(py, &vec)?.to_object(py) + pyo3::types::PyFrozenSet::new(py, &vec)?.into_any().unbind() } None => py.None(), }) @@ -685,7 +668,7 @@ pub(crate) fn encode_distribution_point_reasons( let reason_flag_mapping = types::CRL_REASON_FLAGS.get(py)?; let mut bits = vec![0, 0]; - for py_reason in py_reasons.iter()? { + for py_reason in py_reasons.try_iter()? { let bit = reason_flag_mapping .get_item(py_reason?)? .extract::()?; @@ -704,7 +687,7 @@ pub(crate) fn parse_authority_key_identifier<'p>( ) -> Result, CryptographyError> { let aki = ext.value::>()?; let serial = match aki.authority_cert_serial_number { - Some(biguint) => big_byte_slice_to_py_int(py, biguint.as_bytes())?.to_object(py), + Some(biguint) => big_byte_slice_to_py_int(py, biguint.as_bytes())?.unbind(), None => py.None(), }; let issuer = match aki.authority_cert_issuer { @@ -720,15 +703,15 @@ pub(crate) fn parse_access_descriptions( py: pyo3::Python<'_>, ext: &Extension<'_>, ) -> Result { - let ads = pyo3::types::PyList::empty_bound(py); + let ads = pyo3::types::PyList::empty(py); let parsed = ext.value::>()?; for access in parsed.unwrap_read().clone() { - let py_oid = oid_to_py_oid(py, &access.access_method)?.to_object(py); + let py_oid = oid_to_py_oid(py, &access.access_method)?.unbind(); let gn = x509::parse_general_name(py, access.access_location)?; let ad = types::ACCESS_DESCRIPTION.get(py)?.call1((py_oid, gn))?; ads.append(ad)?; } - Ok(ads.to_object(py)) + Ok(ads.into_any().unbind()) } fn parse_naming_authority<'p>( @@ -740,7 +723,7 @@ fn parse_naming_authority<'p>( None => py.None().into_bound(py), }; let py_url = match authority.url { - Some(data) => pyo3::types::PyString::new_bound(py, data.as_str()).into_any(), + Some(data) => pyo3::types::PyString::new(py, data.as_str()).into_any(), None => py.None().into_bound(py), }; let py_text = match authority.text { @@ -757,20 +740,20 @@ fn parse_profession_infos<'a>( py: pyo3::Python<'a>, profession_infos: &asn1::SequenceOf<'a, ProfessionInfo<'a>>, ) -> CryptographyResult> { - let py_infos = pyo3::types::PyList::empty_bound(py); + let py_infos = pyo3::types::PyList::empty(py); for info in profession_infos.clone() { let py_naming_authority = match info.naming_authority { Some(data) => parse_naming_authority(py, data)?, None => py.None().into_bound(py), }; - let py_profession_items = pyo3::types::PyList::empty_bound(py); + let py_profession_items = pyo3::types::PyList::empty(py); for item in info.profession_items.unwrap_read().clone() { let py_item = parse_display_text(py, item)?; py_profession_items.append(py_item)?; } let py_profession_oids = match info.profession_oids { Some(oids) => { - let py_oids = pyo3::types::PyList::empty_bound(py); + let py_oids = pyo3::types::PyList::empty(py); for oid in oids.unwrap_read().clone() { let py_oid = oid_to_py_oid(py, &oid)?; py_oids.append(py_oid)?; @@ -780,11 +763,11 @@ fn parse_profession_infos<'a>( None => py.None().into_bound(py), }; let py_registration_number = match info.registration_number { - Some(data) => pyo3::types::PyString::new_bound(py, data.as_str()).into_any(), + Some(data) => pyo3::types::PyString::new(py, data.as_str()).into_any(), None => py.None().into_bound(py), }; let py_add_profession_info = match info.add_profession_info { - Some(data) => pyo3::types::PyBytes::new_bound(py, data).into_any(), + Some(data) => pyo3::types::PyBytes::new(py, data).into_any(), None => py.None().into_bound(py), }; let py_info = types::PROFESSION_INFO.get(py)?.call1(( @@ -803,7 +786,7 @@ fn parse_admissions<'a>( py: pyo3::Python<'a>, admissions: &asn1::SequenceOf<'a, Admission<'a>>, ) -> CryptographyResult> { - let py_admissions = pyo3::types::PyList::empty_bound(py); + let py_admissions = pyo3::types::PyList::empty(py); for admission in admissions.clone() { let py_admission_authority = match admission.admission_authority { Some(authority) => x509::parse_general_name(py, authority)?, @@ -851,7 +834,7 @@ pub fn parse_cert_ext<'p>( oid::TLS_FEATURE_OID => { let tls_feature_type_to_enum = types::TLS_FEATURE_TYPE_TO_ENUM.get(py)?; - let features = pyo3::types::PyList::empty_bound(py); + let features = pyo3::types::PyList::empty(py); for feature in ext.value::>()? { let py_feature = tls_feature_type_to_enum.get_item(feature)?; features.append(py_feature)?; @@ -867,7 +850,7 @@ pub fn parse_cert_ext<'p>( )) } oid::EXTENDED_KEY_USAGE_OID => { - let ekus = pyo3::types::PyList::empty_bound(py); + let ekus = pyo3::types::PyList::empty(py); for oid in ext.value::>()? { let oid_obj = oid_to_py_oid(py, &oid)?; ekus.append(oid_obj)?; @@ -1075,11 +1058,7 @@ pub(crate) fn create_x509_certificate( signature_alg: sigalg, signature: asn1::BitString::new(&signature, 0).unwrap(), })?; - load_der_x509_certificate( - py, - pyo3::types::PyBytes::new_bound(py, &data).unbind(), - None, - ) + load_der_x509_certificate(py, pyo3::types::PyBytes::new(py, &data).unbind(), None) } pub(crate) fn set_bit(vals: &mut [u8], n: usize, set: bool) { diff --git a/src/rust/src/x509/common.rs b/src/rust/src/x509/common.rs index cdb53a7b6553..5b01500d8d5d 100644 --- a/src/rust/src/x509/common.rs +++ b/src/rust/src/x509/common.rs @@ -9,7 +9,6 @@ use cryptography_x509::extensions::{ use cryptography_x509::name::{GeneralName, Name, NameReadable, OtherName, UnvalidatedIA5String}; use pyo3::types::IntoPyDict; use pyo3::types::{PyAnyMethods, PyListMethods}; -use pyo3::{IntoPy, ToPyObject}; use crate::asn1::{oid_to_py_oid, py_oid_to_oid}; use crate::error::{CryptographyError, CryptographyResult}; @@ -38,11 +37,11 @@ pub(crate) fn encode_name<'p>( ) -> pyo3::PyResult> { let mut rdns = vec![]; - for py_rdn in py_name.getattr(pyo3::intern!(py, "rdns"))?.iter()? { + for py_rdn in py_name.getattr(pyo3::intern!(py, "rdns"))?.try_iter()? { let py_rdn = py_rdn?; let mut attrs = vec![]; - for py_attr in py_rdn.iter()? { + for py_attr in py_rdn.try_iter()? { attrs.push(encode_name_entry(py, ka, &py_attr?)?); } rdns.push(asn1::SetOfWriter::new(attrs)); @@ -96,7 +95,7 @@ pub(crate) fn encode_name_bytes<'p>( let ka = cryptography_keepalive::KeepAlive::new(); let name = encode_name(py, &ka, py_name)?; let result = asn1::write_single(&name)?; - Ok(pyo3::types::PyBytes::new_bound(py, &result)) + Ok(pyo3::types::PyBytes::new(py, &result)) } pub(crate) fn encode_general_names<'a>( @@ -106,7 +105,7 @@ pub(crate) fn encode_general_names<'a>( py_gns: &pyo3::Bound<'a, pyo3::PyAny>, ) -> Result>, CryptographyError> { let mut gns = vec![]; - for el in py_gns.iter()? { + for el in py_gns.try_iter()? { let gn = encode_general_name(py, ka_bytes, ka_str, &el?)?; gns.push(gn); } @@ -168,7 +167,7 @@ pub(crate) fn encode_access_descriptions<'a>( let mut ads = vec![]; let ka_bytes = cryptography_keepalive::KeepAlive::new(); let ka_str = cryptography_keepalive::KeepAlive::new(); - for py_ad in py_ads.iter()? { + for py_ad in py_ads.try_iter()? { let py_ad = py_ad?; let py_oid = py_ad.getattr(pyo3::intern!(py, "access_method"))?; let access_method = py_oid_to_oid(py_oid)?; @@ -186,7 +185,7 @@ pub(crate) fn parse_name<'p>( py: pyo3::Python<'p>, name: &NameReadable<'_>, ) -> Result, CryptographyError> { - let py_rdns = pyo3::types::PyList::empty_bound(py); + let py_rdns = pyo3::types::PyList::empty(py); for rdn in name.clone() { let py_rdn = parse_rdn(py, &rdn)?; py_rdns.append(py_rdn)?; @@ -207,35 +206,35 @@ fn parse_name_attribute( let py_tag = types::ASN1_TYPE_TO_ENUM.get(py)?.get_item(tag_val)?; let py_data = match attribute.value.tag().as_u8() { // BitString tag value - Some(3) => pyo3::types::PyBytes::new_bound(py, attribute.value.data()).into_any(), + Some(3) => pyo3::types::PyBytes::new(py, attribute.value.data()).into_any(), // BMPString tag value Some(30) => { - let py_bytes = pyo3::types::PyBytes::new_bound(py, attribute.value.data()); + let py_bytes = pyo3::types::PyBytes::new(py, attribute.value.data()); py_bytes.call_method1(pyo3::intern!(py, "decode"), ("utf_16_be",))? } // UniversalString Some(28) => { - let py_bytes = pyo3::types::PyBytes::new_bound(py, attribute.value.data()); + let py_bytes = pyo3::types::PyBytes::new(py, attribute.value.data()); py_bytes.call_method1(pyo3::intern!(py, "decode"), ("utf_32_be",))? } _ => { let parsed = std::str::from_utf8(attribute.value.data()) .map_err(|_| asn1::ParseError::new(asn1::ParseErrorKind::InvalidValue))?; - pyo3::types::PyString::new_bound(py, parsed).into_any() + pyo3::types::PyString::new(py, parsed).into_any() } }; - let kwargs = [(pyo3::intern!(py, "_validate"), false)].into_py_dict_bound(py); + let kwargs = [(pyo3::intern!(py, "_validate"), false)].into_py_dict(py)?; Ok(types::NAME_ATTRIBUTE .get(py)? .call((oid, py_data, py_tag), Some(&kwargs))? - .to_object(py)) + .unbind()) } pub(crate) fn parse_rdn<'a>( py: pyo3::Python<'_>, rdn: &asn1::SetOf<'a, AttributeTypeValue<'a>>, ) -> Result { - let py_attrs = pyo3::types::PyList::empty_bound(py); + let py_attrs = pyo3::types::PyList::empty(py); for attribute in rdn.clone() { let na = parse_name_attribute(py, attribute)?; py_attrs.append(na)?; @@ -243,7 +242,7 @@ pub(crate) fn parse_rdn<'a>( Ok(types::RELATIVE_DISTINGUISHED_NAME .get(py)? .call1((py_attrs,))? - .to_object(py)) + .unbind()) } pub(crate) fn parse_general_name( @@ -256,31 +255,28 @@ pub(crate) fn parse_general_name( types::OTHER_NAME .get(py)? .call1((oid, data.value.full_data()))? - .to_object(py) + .unbind() } GeneralName::RFC822Name(data) => types::RFC822_NAME .get(py)? .call_method1(pyo3::intern!(py, "_init_without_validation"), (data.0,))? - .to_object(py), + .unbind(), GeneralName::DNSName(data) => types::DNS_NAME .get(py)? .call_method1(pyo3::intern!(py, "_init_without_validation"), (data.0,))? - .to_object(py), + .unbind(), GeneralName::DirectoryName(data) => { let py_name = parse_name(py, data.unwrap_read())?; - types::DIRECTORY_NAME - .get(py)? - .call1((py_name,))? - .to_object(py) + types::DIRECTORY_NAME.get(py)?.call1((py_name,))?.unbind() } GeneralName::UniformResourceIdentifier(data) => types::UNIFORM_RESOURCE_IDENTIFIER .get(py)? .call_method1(pyo3::intern!(py, "_init_without_validation"), (data.0,))? - .to_object(py), + .unbind(), GeneralName::IPAddress(data) => { if data.len() == 4 || data.len() == 16 { let addr = types::IPADDRESS_IPADDRESS.get(py)?.call1((data,))?; - types::IP_ADDRESS.get(py)?.call1((addr,))?.to_object(py) + types::IP_ADDRESS.get(py)?.call1((addr,))?.unbind() } else { // if it's not an IPv4 or IPv6 we assume it's an IPNetwork and // verify length in this function. @@ -289,7 +285,7 @@ pub(crate) fn parse_general_name( } GeneralName::RegisteredID(data) => { let oid = oid_to_py_oid(py, &data)?; - types::REGISTERED_ID.get(py)?.call1((oid,))?.to_object(py) + types::REGISTERED_ID.get(py)?.call1((oid,))?.unbind() } _ => { return Err(CryptographyError::from( @@ -306,12 +302,12 @@ pub(crate) fn parse_general_names<'a>( py: pyo3::Python<'_>, gn_seq: &asn1::SequenceOf<'a, GeneralName<'a>>, ) -> Result { - let gns = pyo3::types::PyList::empty_bound(py); + let gns = pyo3::types::PyList::empty(py); for gn in gn_seq.clone() { let py_gn = parse_general_name(py, gn)?; gns.append(py_gn)?; } - Ok(gns.to_object(py)) + Ok(gns.into_any().unbind()) } fn create_ip_network( @@ -333,7 +329,7 @@ fn create_ip_network( }; let base = types::IPADDRESS_IPADDRESS .get(py)? - .call1((pyo3::types::PyBytes::new_bound(py, &data[..data.len() / 2]),))?; + .call1((pyo3::types::PyBytes::new(py, &data[..data.len() / 2]),))?; let net = format!( "{}/{}", base.getattr(pyo3::intern!(py, "exploded"))? @@ -341,7 +337,7 @@ fn create_ip_network( prefix? ); let addr = types::IPADDRESS_IPNETWORK.get(py)?.call1((net,))?; - Ok(types::IP_ADDRESS.get(py)?.call1((addr,))?.to_object(py)) + Ok(types::IP_ADDRESS.get(py)?.call1((addr,))?.unbind()) } fn ipv4_netmask(num: u32) -> Result { @@ -379,12 +375,12 @@ pub(crate) fn parse_and_cache_extensions< let oid_obj = oid_to_py_oid(py, &oid)?; return Err(exceptions::DuplicateExtension::new_err(( format!("Duplicate {} extension found", &oid), - oid_obj.into_py(py), + oid_obj.unbind(), ))); } }; - let exts = pyo3::types::PyList::empty_bound(py); + let exts = pyo3::types::PyList::empty(py); for raw_ext in extensions.iter() { let oid_obj = oid_to_py_oid(py, &raw_ext.extn_id)?; @@ -400,7 +396,7 @@ pub(crate) fn parse_and_cache_extensions< .call1((oid_obj, raw_ext.critical, extn_value))?; exts.append(ext_obj)?; } - Ok(types::EXTENSIONS.get(py)?.call1((exts,))?.to_object(py)) + Ok(types::EXTENSIONS.get(py)?.call1((exts,))?.unbind()) }) .map(|p| p.clone_ref(py)) } @@ -420,7 +416,7 @@ pub(crate) fn encode_extensions< encode_ext: F, ) -> pyo3::PyResult>> { let mut exts = vec![]; - for py_ext in py_exts.iter()? { + for py_ext in py_exts.try_iter()? { let py_ext = py_ext?; let py_oid = py_ext.getattr(pyo3::intern!(py, "oid"))?; let oid = py_oid_to_oid(py_oid)?; @@ -466,7 +462,7 @@ pub(crate) fn encode_extension_value<'p>( if let Some(data) = x509::extensions::encode_extension(py, &oid, &py_ext)? { // TODO: extra copy - let py_data = pyo3::types::PyBytes::new_bound(py, &data); + let py_data = pyo3::types::PyBytes::new(py, &data); return Ok(py_data); } diff --git a/src/rust/src/x509/crl.rs b/src/rust/src/x509/crl.rs index 58c22408557b..b1d4b7b6ba92 100644 --- a/src/rust/src/x509/crl.rs +++ b/src/rust/src/x509/crl.rs @@ -14,7 +14,6 @@ use cryptography_x509::{ name, oid, }; use pyo3::types::{PyAnyMethods, PyListMethods, PySliceMethods}; -use pyo3::ToPyObject; use crate::asn1::{ big_byte_slice_to_py_int, encode_der_data, oid_to_py_oid, py_uint_to_big_endian_bytes, @@ -70,7 +69,7 @@ pub(crate) fn load_pem_x509_crl( )?; load_der_x509_crl( py, - pyo3::types::PyBytes::new_bound(py, block.contents()).unbind(), + pyo3::types::PyBytes::new(py, block.contents()).unbind(), None, ) } @@ -156,12 +155,12 @@ impl CertificateRevocationList { let indices = idx .downcast::()? .indices(self.len().try_into().unwrap())?; - let result = pyo3::types::PyList::empty_bound(py); + let result = pyo3::types::PyList::empty(py); for i in (indices.start..indices.stop).step_by(indices.step.try_into().unwrap()) { let revoked_cert = pyo3::Bound::new(py, self.revoked_cert(py, i as usize))?; result.append(revoked_cert)?; } - Ok(result.to_object(py)) + Ok(result.into_any().unbind()) } else { let mut idx = idx.extract::()?; if idx < 0 { @@ -170,7 +169,9 @@ impl CertificateRevocationList { if idx >= (self.len() as isize) || idx < 0 { return Err(pyo3::exceptions::PyIndexError::new_err(())); } - Ok(pyo3::Bound::new(py, self.revoked_cert(py, idx as usize))?.to_object(py)) + Ok(pyo3::Bound::new(py, self.revoked_cert(py, idx as usize))? + .into_any() + .unbind()) } } @@ -231,7 +232,7 @@ impl CertificateRevocationList { py: pyo3::Python<'p>, ) -> CryptographyResult> { let b = asn1::write_single(&self.owned.borrow_dependent().tbs_cert_list)?; - Ok(pyo3::types::PyBytes::new_bound(py, &b)) + Ok(pyo3::types::PyBytes::new(py, &b)) } fn public_bytes<'p>( @@ -262,12 +263,8 @@ impl CertificateRevocationList { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_42.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to next_update_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to next_update_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; match &self.owned.borrow_dependent().tbs_cert_list.next_update { Some(t) => x509::datetime_to_py(py, t.as_datetime()), None => Ok(py.None().into_bound(py)), @@ -291,12 +288,8 @@ impl CertificateRevocationList { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_42.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to last_update_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to last_update_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; x509::datetime_to_py( py, self.owned @@ -393,7 +386,7 @@ impl CertificateRevocationList { fn get_revoked_certificate_by_serial_number( &self, py: pyo3::Python<'_>, - serial: pyo3::Bound<'_, pyo3::types::PyLong>, + serial: pyo3::Bound<'_, pyo3::types::PyInt>, ) -> pyo3::PyResult> { let serial_bytes = py_uint_to_big_endian_bytes(py, serial)?; let owned = OwnedRevokedCertificate::try_new(Arc::clone(&self.owned), |v| { @@ -559,12 +552,8 @@ impl RevokedCertificate { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_42.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to revocation_date_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to revocation_date_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; x509::datetime_to_py( py, self.owned.borrow_dependent().revocation_date.as_datetime(), @@ -661,7 +650,7 @@ pub(crate) fn create_x509_crl( let ka_bytes = cryptography_keepalive::KeepAlive::new(); for py_revoked_cert in builder .getattr(pyo3::intern!(py, "_revoked_certificates"))? - .iter()? + .try_iter()? { let py_revoked_cert = py_revoked_cert?; let serial_number = py_revoked_cert @@ -723,9 +712,5 @@ pub(crate) fn create_x509_crl( signature_algorithm: sigalg, signature_value: asn1::BitString::new(&signature, 0).unwrap(), })?; - load_der_x509_crl( - py, - pyo3::types::PyBytes::new_bound(py, &data).unbind(), - None, - ) + load_der_x509_crl(py, pyo3::types::PyBytes::new(py, &data).unbind(), None) } diff --git a/src/rust/src/x509/csr.rs b/src/rust/src/x509/csr.rs index 9d4f81958c51..fe42cb8365ad 100644 --- a/src/rust/src/x509/csr.rs +++ b/src/rust/src/x509/csr.rs @@ -9,7 +9,6 @@ use asn1::SimpleAsn1Readable; use cryptography_x509::csr::{check_attribute_length, Attribute, CertificationRequestInfo, Csr}; use cryptography_x509::{common, oid}; use pyo3::types::{PyAnyMethods, PyListMethods}; -use pyo3::IntoPy; use crate::asn1::{encode_der_data, oid_to_py_oid, py_oid_to_oid}; use crate::backend::keys; @@ -80,12 +79,12 @@ impl CertificateSigningRequest { py: pyo3::Python<'p>, ) -> CryptographyResult> { let result = asn1::write_single(&self.raw.borrow_dependent().csr_info)?; - Ok(pyo3::types::PyBytes::new_bound(py, &result)) + Ok(pyo3::types::PyBytes::new(py, &result)) } #[getter] fn signature<'p>(&self, py: pyo3::Python<'p>) -> pyo3::Bound<'p, pyo3::types::PyBytes> { - pyo3::types::PyBytes::new_bound(py, self.raw.borrow_dependent().signature.as_bytes()) + pyo3::types::PyBytes::new(py, self.raw.borrow_dependent().signature.as_bytes()) } #[getter] @@ -131,8 +130,8 @@ impl CertificateSigningRequest { oid: pyo3::Bound<'p, pyo3::PyAny>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_36.get(py)?; - let warning_msg = "CertificateSigningRequest.get_attribute_for_oid has been deprecated. Please switch to request.attributes.get_attribute_for_oid."; - pyo3::PyErr::warn_bound(py, &warning_cls, warning_msg, 1)?; + let warning_msg = std::ffi::CString::new("CertificateSigningRequest.get_attribute_for_oid has been deprecated. Please switch to request.attributes.get_attribute_for_oid.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, warning_msg.as_c_str(), 1)?; let rust_oid = py_oid_to_oid(oid.clone())?; for attribute in self @@ -155,7 +154,7 @@ impl CertificateSigningRequest { || val.tag() == asn1::PrintableString::TAG || val.tag() == asn1::IA5String::TAG { - return Ok(pyo3::types::PyBytes::new_bound(py, val.data()).into_any()); + return Ok(pyo3::types::PyBytes::new(py, val.data()).into_any()); } return Err(pyo3::exceptions::PyValueError::new_err(format!( "OID {} has a disallowed ASN.1 type: {:?}", @@ -166,13 +165,13 @@ impl CertificateSigningRequest { } Err(exceptions::AttributeNotFound::new_err(( format!("No {oid} attribute was found"), - oid.into_py(py), + oid.unbind(), ))) } #[getter] fn attributes<'p>(&self, py: pyo3::Python<'p>) -> pyo3::PyResult> { - let pyattrs = pyo3::types::PyList::empty_bound(py); + let pyattrs = pyo3::types::PyList::empty(py); for attribute in self .raw .borrow_dependent() @@ -188,7 +187,7 @@ impl CertificateSigningRequest { })?; let oid = oid_to_py_oid(py, &attribute.type_id)?; let val = attribute.values.unwrap_read().clone().next().unwrap(); - let serialized = pyo3::types::PyBytes::new_bound(py, val.data()); + let serialized = pyo3::types::PyBytes::new(py, val.data()); let tag = val.tag().as_u8().ok_or_else(|| { CryptographyError::from(pyo3::exceptions::PyValueError::new_err( "Long-form tags are not supported in CSR attribute values", @@ -253,7 +252,7 @@ pub(crate) fn load_pem_x509_csr( )?; load_der_x509_csr( py, - pyo3::types::PyBytes::new_bound(py, parsed.contents()).unbind(), + pyo3::types::PyBytes::new(py, parsed.contents()).unbind(), None, ) } @@ -329,7 +328,10 @@ pub(crate) fn create_x509_csr( } let mut attr_values = vec![]; - for py_attr in builder.getattr(pyo3::intern!(py, "_attributes"))?.iter()? { + for py_attr in builder + .getattr(pyo3::intern!(py, "_attributes"))? + .try_iter()? + { let (py_oid, value, tag): ( pyo3::Bound<'_, pyo3::PyAny>, pyo3::pybacked::PyBackedBytes, @@ -387,7 +389,7 @@ pub(crate) fn create_x509_csr( })?; load_der_x509_csr( py, - pyo3::types::PyBytes::new_bound(py, &data).clone().unbind(), + pyo3::types::PyBytes::new(py, &data).clone().unbind(), None, ) } diff --git a/src/rust/src/x509/extensions.rs b/src/rust/src/x509/extensions.rs index 2342c40a1f03..7659a4bd5fdd 100644 --- a/src/rust/src/x509/extensions.rs +++ b/src/rust/src/x509/extensions.rs @@ -21,7 +21,7 @@ fn encode_general_subtrees<'a>( Ok(None) } else { let mut subtree_seq = vec![]; - for name in subtrees.iter()? { + for name in subtrees.try_iter()? { let gn = x509::common::encode_general_name(py, ka_bytes, ka_str, &name?)?; subtree_seq.push(extensions::GeneralSubtree { base: gn, @@ -43,7 +43,7 @@ pub(crate) fn encode_authority_key_identifier<'a>( struct PyAuthorityKeyIdentifier<'a> { key_identifier: Option, authority_cert_issuer: Option>, - authority_cert_serial_number: Option>, + authority_cert_serial_number: Option>, } let aki = py_aki.extract::>()?; @@ -88,7 +88,7 @@ pub(crate) fn encode_distribution_points<'p>( let ka_bytes = cryptography_keepalive::KeepAlive::new(); let ka_str = cryptography_keepalive::KeepAlive::new(); let mut dps = vec![]; - for py_dp in py_dps.iter()? { + for py_dp in py_dps.try_iter()? { let py_dp = py_dp?.extract::>()?; let crl_issuer = if let Some(py_crl_issuer) = py_dp.crl_issuer { @@ -106,7 +106,7 @@ pub(crate) fn encode_distribution_points<'p>( )) } else if let Some(py_relative_name) = py_dp.relative_name { let mut name_entries = vec![]; - for py_name_entry in py_relative_name.iter()? { + for py_name_entry in py_relative_name.try_iter()? { let ne = x509::common::encode_name_entry(py, &ka_bytes, &py_name_entry?)?; name_entries.push(ne); } @@ -228,13 +228,13 @@ fn encode_certificate_policies( let mut policy_informations = vec![]; let ka_bytes = cryptography_keepalive::KeepAlive::new(); let ka_str = cryptography_keepalive::KeepAlive::new(); - for py_policy_info in ext.iter()? { + for py_policy_info in ext.try_iter()? { let py_policy_info = py_policy_info?; let py_policy_qualifiers = py_policy_info.getattr(pyo3::intern!(py, "policy_qualifiers"))?; let qualifiers = if py_policy_qualifiers.is_truthy()? { let mut qualifiers = vec![]; - for py_qualifier in py_policy_qualifiers.iter()? { + for py_qualifier in py_policy_qualifiers.try_iter()? { let py_qualifier = py_qualifier?; let qualifier = if py_qualifier.is_instance_of::() { let py_qualifier_str = ka_str.add(py_qualifier.extract::()?); @@ -257,7 +257,7 @@ fn encode_certificate_policies( let mut notice_numbers = vec![]; for py_num in py_notice .getattr(pyo3::intern!(py, "notice_numbers"))? - .iter()? + .try_iter()? { let bytes = ka_bytes .add(py_uint_to_big_endian_bytes(ext.py(), py_num?.extract()?)?); @@ -346,7 +346,10 @@ fn encode_issuing_distribution_point( .is_truthy()? { let mut name_entries = vec![]; - for py_name_entry in ext.getattr(pyo3::intern!(py, "relative_name"))?.iter()? { + for py_name_entry in ext + .getattr(pyo3::intern!(py, "relative_name"))? + .try_iter()? + { let name_entry = x509::common::encode_name_entry(ext.py(), &ka_bytes, &py_name_entry?)?; name_entries.push(name_entry); } @@ -376,7 +379,7 @@ fn encode_issuing_distribution_point( fn encode_oid_sequence(ext: &pyo3::Bound<'_, pyo3::PyAny>) -> CryptographyResult> { let mut oids = vec![]; - for el in ext.iter()? { + for el in ext.try_iter()? { let oid = py_oid_to_oid(el?)?; oids.push(oid); } @@ -392,7 +395,7 @@ fn encode_tls_features( // an asn1::Sequence can't return an error, and we need to handle errors // from Python. let mut els = vec![]; - for el in ext.iter()? { + for el in ext.try_iter()? { els.push(el?.getattr(pyo3::intern!(py, "value"))?.extract::()?); } @@ -401,14 +404,14 @@ fn encode_tls_features( fn encode_scts(ext: &pyo3::Bound<'_, pyo3::PyAny>) -> CryptographyResult> { let mut length = 0; - for sct in ext.iter()? { + for sct in ext.try_iter()? { let sct = sct?.downcast::()?.clone(); length += sct.get().sct_data.len() + 2; } let mut result = vec![]; result.extend_from_slice(&(length as u16).to_be_bytes()); - for sct in ext.iter()? { + for sct in ext.try_iter()? { let sct = sct?.downcast::()?.clone(); result.extend_from_slice(&(sct.get().sct_data.len() as u16).to_be_bytes()); result.extend_from_slice(&sct.get().sct_data); @@ -454,7 +457,7 @@ fn encode_naming_authority<'a>( } fn encode_profession_info<'a>( - py: pyo3::Python<'_>, + py: pyo3::Python<'a>, ka_bytes: &'a cryptography_keepalive::KeepAlive, ka_str: &'a cryptography_keepalive::KeepAlive, py_info: &pyo3::Bound<'a, pyo3::PyAny>, @@ -467,7 +470,7 @@ fn encode_profession_info<'a>( }; let mut profession_items = vec![]; let py_items = py_info.getattr(pyo3::intern!(py, "profession_items"))?; - for py_item in py_items.iter()? { + for py_item in py_items.try_iter()? { let py_item = py_item?; let py_item_str = ka_str.add(py_item.extract::()?); let item = extensions::DisplayText::Utf8String(asn1::Utf8String::new(py_item_str)); @@ -478,7 +481,7 @@ fn encode_profession_info<'a>( let py_oids = py_info.getattr(pyo3::intern!(py, "profession_oids"))?; let profession_oids = if !py_oids.is_none() { let mut profession_oids = vec![]; - for py_oid in py_oids.iter()? { + for py_oid in py_oids.try_iter()? { let py_oid = py_oid?; let oid = py_oid_to_oid(py_oid)?; profession_oids.push(oid); @@ -522,7 +525,7 @@ fn encode_profession_info<'a>( } fn encode_admission<'a>( - py: pyo3::Python<'_>, + py: pyo3::Python<'a>, ka_bytes: &'a cryptography_keepalive::KeepAlive, ka_str: &'a cryptography_keepalive::KeepAlive, py_admission: &pyo3::Bound<'a, pyo3::PyAny>, @@ -547,7 +550,7 @@ fn encode_admission<'a>( let py_profession_infos = py_admission.getattr(pyo3::intern!(py, "profession_infos"))?; let mut profession_infos = vec![]; - for py_info in py_profession_infos.iter()? { + for py_info in py_profession_infos.try_iter()? { profession_infos.push(encode_profession_info(py, ka_bytes, ka_str, &py_info?)?); } let profession_infos = @@ -627,7 +630,7 @@ pub(crate) fn encode_extension( &oid::INHIBIT_ANY_POLICY_OID => { let intval = ext .getattr(pyo3::intern!(py, "skip_certs"))? - .downcast::()? + .downcast::()? .clone(); let bytes = py_uint_to_big_endian_bytes(ext.py(), intval)?; Ok(Some(asn1::write_single( @@ -680,7 +683,7 @@ pub(crate) fn encode_extension( &oid::CRL_NUMBER_OID | &oid::DELTA_CRL_INDICATOR_OID => { let intval = ext .getattr(pyo3::intern!(py, "crl_number"))? - .downcast::()? + .downcast::()? .clone(); let bytes = py_uint_to_big_endian_bytes(ext.py(), intval)?; Ok(Some(asn1::write_single( @@ -721,7 +724,7 @@ pub(crate) fn encode_extension( None }; let mut admissions = vec![]; - for py_admission in ext.iter()? { + for py_admission in ext.try_iter()? { let admission = encode_admission(py, &ka_bytes, &ka_str, &py_admission?)?; admissions.push(admission); } diff --git a/src/rust/src/x509/ocsp_req.rs b/src/rust/src/x509/ocsp_req.rs index 7770fb9d6f40..2b3ae3df3656 100644 --- a/src/rust/src/x509/ocsp_req.rs +++ b/src/rust/src/x509/ocsp_req.rs @@ -132,7 +132,7 @@ impl OCSPRequest { } oid::ACCEPTABLE_RESPONSES_OID => { let oids = ext.value::>()?; - let py_oids = pyo3::types::PyList::empty_bound(py); + let py_oids = pyo3::types::PyList::empty(py); for oid in oids { py_oids.append(oid_to_py_oid(py, &oid)?)?; } @@ -161,7 +161,7 @@ impl OCSPRequest { .into()); } let result = asn1::write_single(self.raw.borrow_dependent())?; - Ok(pyo3::types::PyBytes::new_bound(py, &result)) + Ok(pyo3::types::PyBytes::new(py, &result)) } } @@ -188,7 +188,7 @@ pub(crate) fn create_ocsp_request( (py_cert, py_issuer, py_hash) = builder_request.extract()?; ocsp::certid_new(py, &ka_bytes, &py_cert, &py_issuer, &py_hash)? } else { - let py_serial: pyo3::Bound<'_, pyo3::types::PyLong>; + let py_serial: pyo3::Bound<'_, pyo3::types::PyInt>; (issuer_name_hash, issuer_key_hash, py_serial, py_hash) = builder .getattr(pyo3::intern!(py, "_request_hash"))? .extract()?; @@ -226,5 +226,5 @@ pub(crate) fn create_ocsp_request( optional_signature: None, }; let data = asn1::write_single(&ocsp_req)?; - load_der_ocsp_request(py, pyo3::types::PyBytes::new_bound(py, &data).unbind()) + load_der_ocsp_request(py, pyo3::types::PyBytes::new(py, &data).unbind()) } diff --git a/src/rust/src/x509/ocsp_resp.rs b/src/rust/src/x509/ocsp_resp.rs index 955bf35a4c31..c7bb2130a67a 100644 --- a/src/rust/src/x509/ocsp_resp.rs +++ b/src/rust/src/x509/ocsp_resp.rs @@ -168,7 +168,7 @@ impl OCSPResponse { let resp = self.requires_successful_response()?; match resp.tbs_response_data.responder_id { ocsp_resp::ResponderId::ByKey(key_hash) => { - Ok(pyo3::types::PyBytes::new_bound(py, key_hash).into_any()) + Ok(pyo3::types::PyBytes::new(py, key_hash).into_any()) } ocsp_resp::ResponderId::ByName(_) => Ok(py.None().into_bound(py)), } @@ -180,12 +180,8 @@ impl OCSPResponse { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_43.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to produced_at_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to produced_at_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; let resp = self.requires_successful_response()?; x509::datetime_to_py(py, resp.tbs_response_data.produced_at.as_datetime()) } @@ -238,10 +234,7 @@ impl OCSPResponse { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let resp = self.requires_successful_response()?; - Ok(pyo3::types::PyBytes::new_bound( - py, - resp.signature.as_bytes(), - )) + Ok(pyo3::types::PyBytes::new(py, resp.signature.as_bytes())) } #[getter] @@ -251,7 +244,7 @@ impl OCSPResponse { ) -> CryptographyResult> { let resp = self.requires_successful_response()?; let result = asn1::write_single(&resp.tbs_response_data)?; - Ok(pyo3::types::PyBytes::new_bound(py, &result)) + Ok(pyo3::types::PyBytes::new(py, &result)) } #[getter] @@ -260,7 +253,7 @@ impl OCSPResponse { py: pyo3::Python<'p>, ) -> CryptographyResult> { let resp = self.requires_successful_response()?; - let py_certs = pyo3::types::PyList::empty_bound(py); + let py_certs = pyo3::types::PyList::empty(py); let certs = match &resp.certs { Some(certs) => certs.unwrap_read(), None => return Ok(py_certs), @@ -342,12 +335,8 @@ impl OCSPResponse { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_43.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to revocation_time_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to revocation_time_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; let resp = self.requires_successful_response()?; let single_resp = single_response(resp)?; singleresp_py_revocation_time(&single_resp, py) @@ -379,12 +368,8 @@ impl OCSPResponse { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_43.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to this_update_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to this_update_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; let resp = self.requires_successful_response()?; let single_resp = single_response(resp)?; singleresp_py_this_update(&single_resp, py) @@ -406,12 +391,8 @@ impl OCSPResponse { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_43.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to next_update_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to next_update_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; let resp = self.requires_successful_response()?; let single_resp = single_response(resp)?; singleresp_py_next_update(&single_resp, py) @@ -507,7 +488,7 @@ impl OCSPResponse { .into()); } let result = asn1::write_single(self.raw.borrow_dependent())?; - Ok(pyo3::types::PyBytes::new_bound(py, &result)) + Ok(pyo3::types::PyBytes::new(py, &result)) } } @@ -708,7 +689,7 @@ pub(crate) fn create_ocsp_response( response_bytes: None, }; let data = asn1::write_single(&resp)?; - return load_der_ocsp_response(py, pyo3::types::PyBytes::new_bound(py, &data).unbind()); + return load_der_ocsp_response(py, pyo3::types::PyBytes::new(py, &data).unbind()); } let py_single_resp = builder.getattr(pyo3::intern!(py, "_response"))?; @@ -873,7 +854,7 @@ pub(crate) fn create_ocsp_response( response_bytes, }; let data = asn1::write_single(&resp)?; - load_der_ocsp_response(py, pyo3::types::PyBytes::new_bound(py, &data).unbind()) + load_der_ocsp_response(py, pyo3::types::PyBytes::new(py, &data).unbind()) } type RawOCSPResponseIterator<'a> = asn1::SequenceOf<'a, SingleResponse<'a>>; @@ -975,12 +956,8 @@ impl OCSPSingleResponse { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_43.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to revocation_time_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to revocation_time_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; let single_resp = self.single_response(); singleresp_py_revocation_time(single_resp, py) } @@ -1009,12 +986,8 @@ impl OCSPSingleResponse { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_43.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to this_update_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to revocation_time_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; let single_resp = self.single_response(); singleresp_py_this_update(single_resp, py) } @@ -1034,12 +1007,8 @@ impl OCSPSingleResponse { py: pyo3::Python<'p>, ) -> pyo3::PyResult> { let warning_cls = types::DEPRECATED_IN_43.get(py)?; - pyo3::PyErr::warn_bound( - py, - &warning_cls, - "Properties that return a naïve datetime object have been deprecated. Please switch to next_update_utc.", - 1, - )?; + let message = std::ffi::CString::new("Properties that return a naïve datetime object have been deprecated. Please switch to next_update_utc.").unwrap(); + pyo3::PyErr::warn(py, &warning_cls, message.as_c_str(), 1)?; let single_resp = self.single_response(); singleresp_py_next_update(single_resp, py) } diff --git a/src/rust/src/x509/sct.rs b/src/rust/src/x509/sct.rs index 78985af4dfc0..88ab8c911df5 100644 --- a/src/rust/src/x509/sct.rs +++ b/src/rust/src/x509/sct.rs @@ -6,7 +6,6 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use pyo3::types::{PyAnyMethods, PyDictMethods, PyListMethods}; -use pyo3::ToPyObject; use crate::error::CryptographyError; use crate::types; @@ -167,7 +166,7 @@ impl Sct { fn timestamp<'p>(&self, py: pyo3::Python<'p>) -> pyo3::PyResult> { let utc = types::DATETIME_TIMEZONE_UTC.get(py)?; - let kwargs = pyo3::types::PyDict::new_bound(py); + let kwargs = pyo3::types::PyDict::new(py); kwargs.set_item("microsecond", self.timestamp % 1000 * 1000)?; kwargs.set_item("tzinfo", None::>)?; @@ -226,7 +225,7 @@ pub(crate) fn parse_scts( ) -> Result { let mut reader = TLSReader::new(data).read_length_prefixed()?; - let py_scts = pyo3::types::PyList::empty_bound(py); + let py_scts = pyo3::types::PyList::empty(py); while !reader.is_empty() { let mut sct_data = reader.read_length_prefixed()?; let raw_sct_data = sct_data.data.to_vec(); @@ -256,7 +255,7 @@ pub(crate) fn parse_scts( }; py_scts.append(pyo3::Bound::new(py, sct)?)?; } - Ok(py_scts.to_object(py)) + Ok(py_scts.into_any().unbind()) } #[cfg(test)] diff --git a/src/rust/src/x509/sign.rs b/src/rust/src/x509/sign.rs index 4e96b8a8e02d..d826dda8fbae 100644 --- a/src/rust/src/x509/sign.rs +++ b/src/rust/src/x509/sign.rs @@ -119,7 +119,7 @@ fn compute_pss_salt_length<'p>( hash_algorithm .getattr(pyo3::intern!(py, "digest_size"))? .extract::() - } else if py_saltlen.is_instance_of::() { + } else if py_saltlen.is_instance_of::() { py_saltlen.extract::() } else { Err(pyo3::exceptions::PyTypeError::new_err( diff --git a/src/rust/src/x509/verify.rs b/src/rust/src/x509/verify.rs index 20121f0a4764..1722ab960bac 100644 --- a/src/rust/src/x509/verify.rs +++ b/src/rust/src/x509/verify.rs @@ -298,7 +298,7 @@ impl PyClientVerifier { ) .or_else(|e| handle_validation_error(py, e))?; - let py_chain = pyo3::types::PyList::empty_bound(py); + let py_chain = pyo3::types::PyList::empty(py); for c in &chain { py_chain.append(c.extra())?; } @@ -382,7 +382,7 @@ impl PyServerVerifier { ) .or_else(|e| handle_validation_error(py, e))?; - let result = pyo3::types::PyList::empty_bound(py); + let result = pyo3::types::PyList::empty(py); for c in chain { result.append(c.extra())?; }