Skip to content

Commit

Permalink
Use TryInto when validating settings, not evaluating
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ereslibre committed Dec 16, 2021
1 parent 57ac40e commit e2e6e64
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 8 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "selinux-psp"
version = "0.1.2"
version = "0.1.3"
authors = ["Rafael Fernández López <[email protected]>"]
edition = "2018"

Expand Down
7 changes: 3 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,9 @@ enum PolicyResponse {
fn validate(payload: &[u8]) -> CallResult {
let validation_request: ValidationRequest<ExternalSettings> = 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::<apicore::Pod>(validation_request.request.object) {
Ok(pod) => pod,
Expand Down
7 changes: 5 additions & 2 deletions src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
role: Option<String>,
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -141,6 +141,9 @@ impl kubewarden::settings::Validatable for ExternalSettings {
.to_string(),
);
}
if let Err(err) = TryInto::<Settings>::try_into(self.clone()) {
return Err(format!("settings are invalid: {}", err));
}
Ok(())
}
}
Expand Down

0 comments on commit e2e6e64

Please sign in to comment.