Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce code duplication in PolicyBuilder already set checks. #11666

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 20 additions & 19 deletions src/rust/src/x509/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@ pyo3::create_exception!(
pyo3::exceptions::PyException
);

macro_rules! policy_builder_set_once_check {
($self: ident, $property: ident, $human_readable_name: literal) => {
if $self.$property.is_some() {
return Err(CryptographyError::from(
pyo3::exceptions::PyValueError::new_err(concat!(
"The ",
$human_readable_name,
" may only be set once."
)),
));
}
};
}

#[pyo3::pyclass(frozen, module = "cryptography.x509.verification")]
pub(crate) struct PolicyBuilder {
time: Option<asn1::DateTime>,
Expand All @@ -77,13 +91,8 @@ impl PolicyBuilder {
py: pyo3::Python<'_>,
new_time: pyo3::Bound<'_, pyo3::PyAny>,
) -> CryptographyResult<PolicyBuilder> {
if self.time.is_some() {
return Err(CryptographyError::from(
pyo3::exceptions::PyValueError::new_err(
"The validation time may only be set once.",
),
));
}
policy_builder_set_once_check!(self, time, "validation time");

Ok(PolicyBuilder {
time: Some(py_to_datetime(py, new_time)?),
store: self.store.as_ref().map(|s| s.clone_ref(py)),
Expand All @@ -92,11 +101,8 @@ impl PolicyBuilder {
}

fn store(&self, new_store: pyo3::Py<PyStore>) -> CryptographyResult<PolicyBuilder> {
if self.store.is_some() {
return Err(CryptographyError::from(
pyo3::exceptions::PyValueError::new_err("The trust store may only be set once."),
));
}
policy_builder_set_once_check!(self, store, "trust store");

Ok(PolicyBuilder {
time: self.time.clone(),
store: Some(new_store),
Expand All @@ -109,13 +115,8 @@ impl PolicyBuilder {
py: pyo3::Python<'_>,
new_max_chain_depth: u8,
) -> CryptographyResult<PolicyBuilder> {
if self.max_chain_depth.is_some() {
return Err(CryptographyError::from(
pyo3::exceptions::PyValueError::new_err(
"The maximum chain depth may only be set once.",
),
));
}
policy_builder_set_once_check!(self, max_chain_depth, "maximum chain depth");

Ok(PolicyBuilder {
time: self.time.clone(),
store: self.store.as_ref().map(|s| s.clone_ref(py)),
Expand Down