Support WithUserAgent in cti client (#3542)

This commit is contained in:
AlteredCoder 2025-03-31 14:44:51 +02:00 committed by GitHub
parent d64f196b3f
commit 78a6179566
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -9,9 +9,8 @@ import (
"net/http" "net/http"
"strings" "strings"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/crowdsec/pkg/apiclient/useragent" "github.com/crowdsecurity/crowdsec/pkg/apiclient/useragent"
log "github.com/sirupsen/logrus"
) )
const ( const (
@ -21,17 +20,19 @@ const (
) )
var ( var (
ErrUnauthorized = errors.New("unauthorized") ErrUnauthorized = errors.New("unauthorized")
ErrLimit = errors.New("request quota exceeded, please reduce your request rate") ErrLimit = errors.New("request quota exceeded, please reduce your request rate")
ErrNotFound = errors.New("ip not found") ErrNotFound = errors.New("ip not found")
ErrDisabled = errors.New("cti is disabled") ErrDisabled = errors.New("cti is disabled")
ErrUnknown = errors.New("unknown error") ErrUnknown = errors.New("unknown error")
defaultUserAgent = useragent.Default()
) )
type CrowdsecCTIClient struct { type CrowdsecCTIClient struct {
httpClient *http.Client httpClient *http.Client
apiKey string apiKey string
Logger *log.Entry Logger *log.Entry
UserAgent string
} }
func (c *CrowdsecCTIClient) doRequest(ctx context.Context, method string, endpoint string, params map[string]string) ([]byte, error) { func (c *CrowdsecCTIClient) doRequest(ctx context.Context, method string, endpoint string, params map[string]string) ([]byte, error) {
@ -48,7 +49,7 @@ func (c *CrowdsecCTIClient) doRequest(ctx context.Context, method string, endpoi
} }
req.Header.Set("X-Api-Key", c.apiKey) req.Header.Set("X-Api-Key", c.apiKey)
req.Header.Set("User-Agent", useragent.Default()) req.Header.Set("User-Agent", c.UserAgent)
resp, err := c.httpClient.Do(req) resp, err := c.httpClient.Do(req)
if err != nil { if err != nil {
@ -169,6 +170,10 @@ func NewCrowdsecCTIClient(options ...func(*CrowdsecCTIClient)) *CrowdsecCTIClien
client.Logger = log.NewEntry(log.New()) client.Logger = log.NewEntry(log.New())
} }
if client.UserAgent == "" {
client.UserAgent = defaultUserAgent
}
return client return client
} }
@ -189,3 +194,9 @@ func WithAPIKey(apiKey string) func(*CrowdsecCTIClient) {
c.apiKey = apiKey c.apiKey = apiKey
} }
} }
func WithUserAgent(userAgent string) func(*CrowdsecCTIClient) {
return func(c *CrowdsecCTIClient) {
c.UserAgent = userAgent
}
}