Ignore missing console/context.yaml if not explicitly required by config.yaml (#2726)

This commit is contained in:
mmetc 2024-01-12 16:29:04 +01:00 committed by GitHub
parent 733f5e165b
commit 1e0bcedef5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 4 deletions

View file

@ -2,7 +2,9 @@ package alertcontext
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
@ -14,6 +16,8 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
var ErrNoContextData = errors.New("no context to send")
// this file is here to avoid circular dependencies between the configuration and the hub
// HubItemWrapper is a wrapper around a hub item to unmarshal only the context part
@ -25,7 +29,7 @@ type HubItemWrapper struct {
// mergeContext adds the context from src to dest.
func mergeContext(dest map[string][]string, src map[string][]string) error {
if len(src) == 0 {
return fmt.Errorf("no context data to merge")
return ErrNoContextData
}
for k, v := range src {
@ -86,8 +90,9 @@ func addContextFromFile(toSend map[string][]string, filePath string) error {
}
err = mergeContext(toSend, newContext)
if err != nil {
log.Warningf("while merging context from %s: %s", filePath, err)
if err != nil && !errors.Is(err, ErrNoContextData) {
// having an empty console/context.yaml is not an error
return err
}
return nil
@ -125,8 +130,10 @@ func LoadConsoleContext(c *csconfig.Config, hub *cwhub.Hub) error {
}
if err := addContextFromFile(c.Crowdsec.ContextToSend, c.Crowdsec.ConsoleContextPath); err != nil {
if !ignoreMissing || !os.IsNotExist(err) {
if !errors.Is(err, fs.ErrNotExist) {
return err
} else if !ignoreMissing {
log.Warningf("while merging context from %s: %s", c.Crowdsec.ConsoleContextPath, err)
}
}

View file

@ -46,9 +46,21 @@ teardown() {
assert_stderr --partial "loading console context from $CONTEXT_YAML"
}
@test "no error if context file is missing but not explicitly set" {
config_set "del(.crowdsec_service.console_context_path)"
rune -0 rm -f "$CONTEXT_YAML"
rune -0 cscli lapi context status --error
refute_stderr
assert_output --partial "No context found on this agent."
rune -0 "$CROWDSEC" -t
refute_stderr --partial "no such file or directory"
}
@test "error if context file is explicitly set but does not exist" {
config_set ".crowdsec_service.console_context_path=strenv(CONTEXT_YAML)"
rune -0 rm -f "$CONTEXT_YAML"
rune -1 cscli lapi context status --error
assert_stderr --partial "context.yaml: no such file or directory"
rune -1 "$CROWDSEC" -t
assert_stderr --partial "while checking console_context_path: stat $CONTEXT_YAML: no such file or directory"
}