From e2e6e6471e6cc11308b8efd3c89deb9ff2c0196c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Fern=C3=A1ndez=20L=C3=B3pez?= Date: Thu, 16 Dec 2021 18:20:15 +0200 Subject: [PATCH] Use TryInto when validating settings, not evaluating When evaluating, just unwrap the result, since we don't have to take a decision based on that. We know that settings are valid given that they were already validated with `validate_settings`. Just unwrap the result on the real evaluation. --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/lib.rs | 7 +++---- src/settings.rs | 7 +++++-- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44ef632..2325258 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -264,7 +264,7 @@ checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" [[package]] name = "selinux-psp" -version = "0.1.1" +version = "0.1.3" dependencies = [ "anyhow", "k8s-openapi", diff --git a/Cargo.toml b/Cargo.toml index 41c1605..43b4dd0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "selinux-psp" -version = "0.1.2" +version = "0.1.3" authors = ["Rafael Fernández López "] edition = "2018" diff --git a/src/lib.rs b/src/lib.rs index 4d66c74..12a8403 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,10 +29,9 @@ enum PolicyResponse { fn validate(payload: &[u8]) -> CallResult { let validation_request: ValidationRequest = ValidationRequest::new(payload)?; - let settings: Settings = match validation_request.settings.try_into() { - Ok(settings) => settings, - Err(err) => return kubewarden::reject_request(Some(err.to_string()), None), - }; + // It is safe to unwrap here, because the validate_settings function already made sure that + // ExternalSettings can be converted to Settings. + let settings: Settings = validation_request.settings.try_into().unwrap(); let pod = match serde_json::from_value::(validation_request.request.object) { Ok(pod) => pod, diff --git a/src/settings.rs b/src/settings.rs index 6463068..fd547b0 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -7,7 +7,7 @@ use std::{ use k8s_openapi::api::core::v1 as apicore; -#[derive(Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug)] pub(crate) struct SELinuxOptionsExternal { user: Option, role: Option, @@ -95,7 +95,7 @@ impl SELinuxLevel { } } -#[derive(Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug)] #[serde(tag = "rule", deny_unknown_fields)] pub(crate) enum ExternalSettings { MustRunAs(SELinuxOptionsExternal), @@ -141,6 +141,9 @@ impl kubewarden::settings::Validatable for ExternalSettings { .to_string(), ); } + if let Err(err) = TryInto::::try_into(self.clone()) { + return Err(format!("settings are invalid: {}", err)); + } Ok(()) } }