Skip to content

Commit

Permalink
Improve error messages for incorrect capabilities version
Browse files Browse the repository at this point in the history
As reported in #1202 (thanks @geirs73!)

Note however that this does not address the Windows path loading
issue from the same issue though.

Signed-off-by: Anders Eknert <anders@styra.com>
  • Loading branch information
anderseknert committed Oct 16, 2024
1 parent 5bc9d1d commit 16e6aca
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
15 changes: 12 additions & 3 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ type marshallingIntermediary struct {
Capabilities struct {
From struct {
Engine string `yaml:"engine"`
Version string `yaml:"version"`
Version any `yaml:"version"`
File string `yaml:"file"`
URL string `yaml:"url"`
} `yaml:"from"`
Expand Down Expand Up @@ -368,7 +368,7 @@ func (config *Config) UnmarshalYAML(value *yaml.Node) error {
return fmt.Errorf("unmarshalling config failed %w", err)
}

// this call will walk the rule config and load and defaults into the config
// this call will walk the rule config and load defaults into the config
if err := extractDefaults(config, &result); err != nil {
return fmt.Errorf("extracting defaults failed: %w", err)
}
Expand Down Expand Up @@ -411,7 +411,16 @@ func (config *Config) UnmarshalYAML(value *yaml.Node) error {
}

if capabilitiesEngine != "" {
capabilitiesURL = "regal:///capabilities/" + capabilitiesEngine + "/" + capabilitiesEngineVersion
version, ok := capabilitiesEngineVersion.(string)
if !ok {
return errors.New("capabilities: from.version must be a string")
}

if capabilitiesEngine == capabilitiesEngineOPA && !strings.HasPrefix(version, "v") {
return errors.New("capabilities: from.version must be a valid OPA version (with a 'v' prefix)")
}

capabilitiesURL = "regal:///capabilities/" + capabilitiesEngine + "/" + version
}

if capabilitiesFile != "" {
Expand Down
30 changes: 30 additions & 0 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,3 +394,33 @@ func TestUnmarshalConfigDefaultCapabilities(t *testing.T) {
}
}
}

func TestUnmarshalConfigWithNumericOPAVersion(t *testing.T) {
t.Parallel()

bs := []byte(`
capabilities:
from:
engine: opa
version: 68
`)
if err := yaml.Unmarshal(bs, &Config{}); err == nil ||
err.Error() != "capabilities: from.version must be a string" {
t.Errorf("expected error, got %v", err)
}
}

func TestUnmarshalConfigWithMissingVPrefixOPAVersion(t *testing.T) {
t.Parallel()

bs := []byte(`
capabilities:
from:
engine: opa
version: 0.68.0
`)
if err := yaml.Unmarshal(bs, &Config{}); err == nil ||
err.Error() != "capabilities: from.version must be a valid OPA version (with a 'v' prefix)" {
t.Errorf("expected error, got %v", err)
}
}

0 comments on commit 16e6aca

Please sign in to comment.