Skip to content

Commit

Permalink
Merge pull request #665 from flavio/improve-error-message
Browse files Browse the repository at this point in the history
fix: improve error message
  • Loading branch information
viccuad authored Dec 12, 2023
2 parents 4c67944 + c711cd7 commit 2c438a5
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,25 @@ pub(crate) enum Backend {
type KubewardenProtocolDetectorFn = fn(PathBuf) -> Result<ProtocolVersion>;
type RegoDetectorFn = fn(PathBuf) -> Result<bool>;

// 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<bool> {
let data: Vec<u8> = std::fs::read(wasm_path)?;
let data: Vec<u8> = 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);
}
}
Expand Down Expand Up @@ -80,12 +87,8 @@ impl BackendDetector {
}

pub(crate) fn is_rego_policy(&self, wasm_path: &Path) -> Result<bool> {
(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<Backend> {
Expand Down

0 comments on commit 2c438a5

Please sign in to comment.