Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
mmetc committed Jan 2, 2025
1 parent 5dabb29 commit 6fac1c7
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 10 deletions.
12 changes: 7 additions & 5 deletions pkg/acquisition/modules/appsec/appsec_runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

func TestAppsecRuleLoad(t *testing.T) {
log.SetLevel(log.TraceLevel)

tests := []appsecRuleTest{
{
name: "simple rule load",
Expand Down Expand Up @@ -106,21 +107,22 @@ func TestAppsecRuleLoad(t *testing.T) {

Or: []appsec_rule.CustomRule{
{
//Name: "rule1",
// Name: "rule1",
Zones: []string{"ARGS"},
Match: appsec_rule.Match{Type: "equals", Value: "toto"},
},
{
//Name: "rule1",
// Name: "rule1",
Zones: []string{"ARGS"},
Match: appsec_rule.Match{Type: "equals", Value: "tutu"},
},
{
//Name: "rule1",
// Name: "rule1",
Zones: []string{"ARGS"},
Match: appsec_rule.Match{Type: "equals", Value: "tata"},
}, {
//Name: "rule1",
},
{
// Name: "rule1",
Zones: []string{"ARGS"},
Match: appsec_rule.Match{Type: "equals", Value: "titi"},
},
Expand Down
26 changes: 24 additions & 2 deletions pkg/acquisition/modules/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ var linesRead = prometheus.NewCounterVec(
[]string{"path", "src"})

type HttpConfiguration struct {
//IPFilter []string `yaml:"ip_filter"`
//ChunkSize *int64 `yaml:"chunk_size"`
// IPFilter []string `yaml:"ip_filter"`
// ChunkSize *int64 `yaml:"chunk_size"`
ListenAddr string `yaml:"listen_addr"`
Path string `yaml:"path"`
AuthType string `yaml:"auth_type"`
Expand Down Expand Up @@ -75,6 +75,7 @@ func (h *HTTPSource) GetUuid() string {

func (h *HTTPSource) UnmarshalConfig(yamlConfig []byte) error {
h.Config = HttpConfiguration{}

err := yaml.Unmarshal(yamlConfig, &h.Config)
if err != nil {
return fmt.Errorf("cannot parse %s datasource configuration: %w", dataSourceName, err)
Expand All @@ -95,6 +96,7 @@ func (hc *HttpConfiguration) Validate() error {
if hc.Path == "" {
hc.Path = "/"
}

if hc.Path[0] != '/' {
return errors.New("path must start with /")
}
Expand All @@ -105,9 +107,11 @@ func (hc *HttpConfiguration) Validate() error {
if hc.BasicAuth == nil {
return errors.New(baseErr + " basic_auth is not provided")
}

if hc.BasicAuth.Username == "" {
return errors.New(baseErr + " username is not provided")
}

if hc.BasicAuth.Password == "" {
return errors.New(baseErr + " password is not provided")
}
Expand All @@ -127,6 +131,7 @@ func (hc *HttpConfiguration) Validate() error {
if hc.TLS.ServerCert == "" {
return errors.New("server_cert is required")
}

if hc.TLS.ServerKey == "" {
return errors.New("server_key is required")
}
Expand Down Expand Up @@ -155,6 +160,7 @@ func (hc *HttpConfiguration) Validate() error {
func (h *HTTPSource) Configure(yamlConfig []byte, logger *log.Entry, MetricsLevel int) error {
h.logger = logger
h.metricsLevel = MetricsLevel

err := h.UnmarshalConfig(yamlConfig)
if err != nil {
return err
Expand Down Expand Up @@ -209,6 +215,7 @@ func (hc *HttpConfiguration) NewTLSConfig() (*tls.Config, error) {
if err != nil {
return nil, fmt.Errorf("failed to load server cert/key: %w", err)
}

tlsConfig.Certificates = []tls.Certificate{cert}
}

Expand All @@ -226,6 +233,7 @@ func (hc *HttpConfiguration) NewTLSConfig() (*tls.Config, error) {
if caCertPool == nil {
caCertPool = x509.NewCertPool()
}

caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.ClientCAs = caCertPool
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
Expand All @@ -240,17 +248,20 @@ func authorizeRequest(r *http.Request, hc *HttpConfiguration) error {
if !ok {
return errors.New("missing basic auth")
}

if username != hc.BasicAuth.Username || password != hc.BasicAuth.Password {
return errors.New("invalid basic auth")
}
}

if hc.AuthType == "headers" {
for key, value := range *hc.Headers {
if r.Header.Get(key) != value {
return errors.New("invalid headers")
}
}
}

return nil
}

Expand Down Expand Up @@ -279,14 +290,17 @@ func (h *HTTPSource) processRequest(w http.ResponseWriter, r *http.Request, hc *
}

decoder := json.NewDecoder(reader)

for {
var message json.RawMessage

if err := decoder.Decode(&message); err != nil {
if err == io.EOF {
break
}

w.WriteHeader(http.StatusBadRequest)

return fmt.Errorf("failed to decode: %w", err)
}

Expand Down Expand Up @@ -327,11 +341,13 @@ func (h *HTTPSource) RunServer(out chan types.Event, t *tomb.Tomb) error {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}

if err := authorizeRequest(r, &h.Config); err != nil {
h.logger.Errorf("failed to authorize request from '%s': %s", r.RemoteAddr, err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

err := h.processRequest(w, r, &h.Config, out)
if err != nil {
h.logger.Errorf("failed to process request from '%s': %s", r.RemoteAddr, err)
Expand All @@ -343,6 +359,7 @@ func (h *HTTPSource) RunServer(out chan types.Event, t *tomb.Tomb) error {
w.Header().Set(key, value)
}
}

if h.Config.CustomStatusCode != nil {
w.WriteHeader(*h.Config.CustomStatusCode)
} else {
Expand All @@ -366,25 +383,30 @@ func (h *HTTPSource) RunServer(out chan types.Event, t *tomb.Tomb) error {
if err != nil {
return fmt.Errorf("failed to create tls config: %w", err)
}

h.logger.Tracef("tls config: %+v", tlsConfig)
h.Server.TLSConfig = tlsConfig
}

t.Go(func() error {
defer trace.CatchPanic("crowdsec/acquis/http/server")

if h.Config.TLS != nil {
h.logger.Infof("start https server on %s", h.Config.ListenAddr)

err := h.Server.ListenAndServeTLS(h.Config.TLS.ServerCert, h.Config.TLS.ServerKey)
if err != nil && err != http.ErrServerClosed {
return fmt.Errorf("https server failed: %w", err)
}
} else {
h.logger.Infof("start http server on %s", h.Config.ListenAddr)

err := h.Server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
return fmt.Errorf("http server failed: %w", err)
}
}

return nil
})

Expand Down
7 changes: 4 additions & 3 deletions pkg/alertcontext/alertcontext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@ func TestValidateContextExpr(t *testing.T) {
}
for _, test := range tests {
fmt.Printf("Running test '%s'\n", test.name)

err := ValidateContextExpr(test.key, test.exprs)
if test.expectedErr == nil {
require.NoError(t, err)
Expand Down Expand Up @@ -349,13 +350,13 @@ func TestAppsecEventToContext(t *testing.T) {
}

for _, test := range tests {
//reset cache
// reset cache
alertContext = Context{}
//compile
// compile
if err := NewAlertContext(test.contextToSend, 100); err != nil {
t.Fatalf("failed to compile %s: %s", test.name, err)
}
//run
// run

metas, errors := AppsecEventToContext(test.match, test.req)
assert.Len(t, errors, test.expectedErrLen)
Expand Down
2 changes: 2 additions & 0 deletions pkg/cwhub/item.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ func (d Dependencies) SubItems(hub *Hub) func(func(*Item) bool) {
if s == nil {
continue
}

if !yield(s) {
return
}
Expand Down Expand Up @@ -272,6 +273,7 @@ func (i *Item) CurrentDependencies() Dependencies {
if errors.Is(err, fs.ErrNotExist) {
return i.Dependencies
}

if err != nil {
// a file might be corrupted, or in development
i.hub.logger.Warningf("can't read dependencies for %s, using index", i.FQName())
Expand Down

0 comments on commit 6fac1c7

Please sign in to comment.