From c711cd750646d12ee0f8ccdfe77199da94a267f5 Mon Sep 17 00:00:00 2001 From: Flavio Castelli Date: Tue, 12 Dec 2023 09:40:53 +0100 Subject: [PATCH] fix: improve error message Provide a better error message when performing the OPA/Gatekeeper detection. This is is a follow up from issue https://github.com/kubewarden/kwctl/issues/662 Signed-off-by: Flavio Castelli --- src/backend.rs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/backend.rs b/src/backend.rs index 527c1d24..716e01bf 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -22,18 +22,25 @@ pub(crate) enum Backend { type KubewardenProtocolDetectorFn = fn(PathBuf) -> Result; type RegoDetectorFn = fn(PathBuf) -> Result; -// Looks at the Wasm module pointed by `wasm_path` and return whether it was generaed by a Rego +// Looks at the Wasm module pointed by `wasm_path` and return whether it was generated by a Rego // policy // // The code looks at the export symbols offered by the Wasm module. // Having at least one symbol that starts with the `opa_` prefix leads // the policy to be considered a Rego-based one. fn rego_policy_detector(wasm_path: PathBuf) -> Result { - let data: Vec = std::fs::read(wasm_path)?; + let data: Vec = std::fs::read(wasm_path.clone()) + .map_err(|e| anyhow!("cannot access file {:?}: {}", wasm_path, e))?; for payload in wasmparser::Parser::new(0).parse_all(&data) { - if let wasmparser::Payload::ExportSection(s) = payload? { + if let wasmparser::Payload::ExportSection(s) = + payload.map_err(|e| anyhow!("cannot parse WebAssembly file: {}", e))? + { for export in s { - if export?.name.starts_with("opa_") { + if export + .map_err(|e| anyhow!("cannot parse WebAssembly export section: {}", e))? + .name + .starts_with("opa_") + { return Ok(true); } } @@ -80,12 +87,8 @@ impl BackendDetector { } pub(crate) fn is_rego_policy(&self, wasm_path: &Path) -> Result { - (self.rego_detector_func)(wasm_path.to_path_buf()).map_err(|e| { - anyhow!( - "Error while checking if the policy has been created using Opa/Gatekeeper: {}", - e - ) - }) + (self.rego_detector_func)(wasm_path.to_path_buf()) + .map_err(|e| anyhow!("Rego policy type check failure: {}", e)) } pub(crate) fn detect(&self, wasm_path: PathBuf, metadata: &Metadata) -> Result {