Skip to content

Commit

Permalink
🚨 Optimize Lint for strings
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieuHa committed May 18, 2024
1 parent 4969c91 commit ab9f4d5
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 35 deletions.
23 changes: 12 additions & 11 deletions bouncer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -89,7 +90,7 @@ func New(ctx context.Context, next http.Handler, config *configuration.Config, n
log := logger.New(config.LogLevel)
err := configuration.ValidateParams(config)
if err != nil {
log.Error(fmt.Sprintf("New:validateParams %s", err.Error()))
log.Error("New:validateParams " + err.Error())
return nil, err
}

Expand All @@ -112,12 +113,12 @@ func New(ctx context.Context, next http.Handler, config *configuration.Config, n
crowdsecHeader = crowdsecLapiHeader
tlsConfig, err = configuration.GetTLSConfigCrowdsec(config, log)
if err != nil {
log.Error(fmt.Sprintf("New:getTLSConfigCrowdsec fail to get tlsConfig %s", err.Error()))
log.Error("New:getTLSConfigCrowdsec fail to get tlsConfig " + err.Error())
return nil, err
}
apiKey, errAPIKey := configuration.GetVariable(config, "CrowdsecLapiKey")
if errAPIKey != nil && len(tlsConfig.Certificates) == 0 {
log.Error(fmt.Sprintf("New:crowdsecLapiKey fail to get CrowdsecLapiKey and no client certificate setup %s", errAPIKey.Error()))
log.Error("New:crowdsecLapiKey fail to get CrowdsecLapiKey and no client certificate setup " + errAPIKey.Error())
return nil, err
}
config.CrowdsecLapiKey = apiKey
Expand All @@ -129,7 +130,7 @@ func New(ctx context.Context, next http.Handler, config *configuration.Config, n
banTemplate, _ := configuration.GetHTMLTemplate(config.BanHTMLFilePath)
err = banTemplate.Execute(&buf, nil)
if err != nil {
log.Error(fmt.Sprintf("New:banTemplate is bad formatted %s", err.Error()))
log.Error("New:banTemplate is bad formatted " + err.Error())
return nil, err
}
banTemplateString = buf.String()
Expand Down Expand Up @@ -209,7 +210,7 @@ func New(ctx context.Context, next http.Handler, config *configuration.Config, n
if (config.CrowdsecMode == configuration.StreamMode || config.CrowdsecMode == configuration.AloneMode) && ticker == nil {
if config.CrowdsecMode == configuration.AloneMode {
if err := getToken(bouncer); err != nil {
bouncer.log.Error(fmt.Sprintf("New:getToken %s", err.Error()))
bouncer.log.Error("New:getToken " + err.Error())
return nil, err
}
}
Expand All @@ -219,7 +220,7 @@ func New(ctx context.Context, next http.Handler, config *configuration.Config, n
handleStreamTicker(bouncer)
})
}
bouncer.log.Debug(fmt.Sprintf("New initialized mode:%s", config.CrowdsecMode))
bouncer.log.Debug("New initialized mode:" + config.CrowdsecMode)

return bouncer, nil
}
Expand Down Expand Up @@ -443,7 +444,7 @@ func handleNoStreamCache(bouncer *Bouncer, remoteIP string) (string, error) {
case "captcha":
value = cache.CaptchaValue
default:
bouncer.log.Debug(fmt.Sprintf("handleStreamCache:unknownType %s", decision.Type))
bouncer.log.Debug("handleStreamCache:unknownType " + decision.Type)
}
if isLiveMode {
durationSecond := int64(duration.Seconds())
Expand All @@ -452,7 +453,7 @@ func handleNoStreamCache(bouncer *Bouncer, remoteIP string) (string, error) {
}
bouncer.cacheClient.Set(remoteIP, value, durationSecond)
}
return value, fmt.Errorf("handleNoStreamCache:banned")
return value, errors.New("handleNoStreamCache:banned")
}

func getToken(bouncer *Bouncer) error {
Expand Down Expand Up @@ -517,7 +518,7 @@ func handleStreamCache(bouncer *Bouncer) error {
case "captcha":
value = cache.CaptchaValue
default:
bouncer.log.Debug(fmt.Sprintf("handleStreamCache:unknownType %s", decision.Type))
bouncer.log.Debug("handleStreamCache:unknownType " + decision.Type)
}
bouncer.cacheClient.Set(decision.Value, value, int64(duration.Seconds()))
}
Expand Down Expand Up @@ -549,7 +550,7 @@ func crowdsecQuery(bouncer *Bouncer, stringURL string, isPost bool) ([]byte, err
}
defer func() {
if err = res.Body.Close(); err != nil {
bouncer.log.Error(fmt.Sprintf("crowdsecQuery:closeBody %s", err.Error()))
bouncer.log.Error("crowdsecQuery:closeBody " + err.Error())
}
}()
if res.StatusCode == http.StatusUnauthorized && bouncer.crowdsecMode == configuration.AloneMode {
Expand Down Expand Up @@ -605,7 +606,7 @@ func appsecQuery(bouncer *Bouncer, ip string, httpReq *http.Request) error {
}
defer func() {
if err = res.Body.Close(); err != nil {
bouncer.log.Error(fmt.Sprintf("appsecQuery:closeBody %s", err.Error()))
bouncer.log.Error("appsecQuery:closeBody " + err.Error())
}
}()
if res.StatusCode == http.StatusInternalServerError {
Expand Down
9 changes: 5 additions & 4 deletions pkg/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package cache

import (
"errors"
"fmt"

ttl_map "github.com/leprosus/golang-ttl-map"
Expand Down Expand Up @@ -38,7 +39,7 @@ func (localCache) get(key string) (string, error) {
if isCached && isValid && len(valueString) > 0 {
return valueString, nil
}
return "", fmt.Errorf(CacheMiss)
return "", errors.New(CacheMiss)
}

func (localCache) set(key, value string, duration int64) {
Expand All @@ -60,20 +61,20 @@ func (redisCache) get(key string) (string, error) {
return valueString, nil
}
if err.Error() == simpleredis.RedisMiss {
return "", fmt.Errorf(CacheMiss)
return "", errors.New(CacheMiss)
}
return "", err
}

func (rc redisCache) set(key, value string, duration int64) {
if err := redis.Set(key, []byte(value), duration); err != nil {
rc.log.Error(fmt.Sprintf("cache:setDecisionRedisCache %s", err.Error()))
rc.log.Error("cache:setDecisionRedisCache" + err.Error())
}
}

func (rc redisCache) delete(key string) {
if err := redis.Del(key); err != nil {
rc.log.Error(fmt.Sprintf("cache:deleteDecisionRedisCache %s", err.Error()))
rc.log.Error("cache:deleteDecisionRedisCache " + err.Error())
}
}

Expand Down
14 changes: 7 additions & 7 deletions pkg/captcha/captcha.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,13 @@ func (c *Client) New(log *logger.Log, cacheClient *cache.Client, httpClient *htt
func (c *Client) ServeHTTP(rw http.ResponseWriter, r *http.Request, remoteIP string) {
valid, err := c.Validate(r)
if err != nil {
c.log.Debug(fmt.Sprintf("captcha:ServeHTTP:validate %s", err.Error()))
c.log.Info("captcha:ServeHTTP:validate " + err.Error())
rw.WriteHeader(http.StatusBadRequest)
return
}
if valid {
c.log.Debug("captcha:ServeHTTP captcha:valid")
c.cacheClient.Set(fmt.Sprintf("%s_captcha", remoteIP), cache.CaptchaDoneValue, c.gracePeriodSeconds)
c.cacheClient.Set(remoteIP+"_captcha", cache.CaptchaDoneValue, c.gracePeriodSeconds)
http.Redirect(rw, r, r.URL.String(), http.StatusFound)
return
}
Expand All @@ -94,13 +94,13 @@ func (c *Client) ServeHTTP(rw http.ResponseWriter, r *http.Request, remoteIP str
"FrontendKey": captcha[c.provider].key,
})
if err != nil {
c.log.Info(fmt.Sprintf("captcha:ServeHTTP captchaTemplateServe %s", err.Error()))
c.log.Info("captcha:ServeHTTP captchaTemplateServe " + err.Error())
}
}

// Check Verify if the captcha is already done.
func (c *Client) Check(remoteIP string) bool {
value, _ := c.cacheClient.Get(fmt.Sprintf("%s_captcha", remoteIP))
value, _ := c.cacheClient.Get(remoteIP + "_captcha")
passed := value == cache.CaptchaDoneValue
c.log.Debug(fmt.Sprintf("captcha:Check ip:%s pass:%v", remoteIP, passed))
return passed
Expand All @@ -113,10 +113,10 @@ type responseProvider struct {
// Validate Verify the captcha from provider API.
func (c *Client) Validate(r *http.Request) (bool, error) {
if r.Method != http.MethodPost {
c.log.Debug(fmt.Sprintf("captcha:Validate invalid method: %s", r.Method))
c.log.Debug("captcha:Validate invalid method: " + r.Method)
return false, nil
}
var response = r.FormValue(fmt.Sprintf("%s-response", captcha[c.provider].key))
var response = r.FormValue(captcha[c.provider].key + "%s-response")
if response == "" {
c.log.Debug("captcha:Validate no captcha response found in request")
return false, nil
Expand All @@ -130,7 +130,7 @@ func (c *Client) Validate(r *http.Request) (bool, error) {
}
defer func() {
if err = res.Body.Close(); err != nil {
c.log.Error(fmt.Sprintf("captcha:Validate %s", err.Error()))
c.log.Error("captcha:Validate " + err.Error())
}
}()
if !strings.Contains(res.Header.Get("content-type"), "application/json") {
Expand Down
21 changes: 11 additions & 10 deletions pkg/configuration/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package configuration
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"html/template"
"net/http"
Expand Down Expand Up @@ -124,7 +125,7 @@ func New() *Config {
func GetVariable(config *Config, key string) (string, error) {
value := ""
object := reflect.Indirect(reflect.ValueOf(config))
field := object.FieldByName(fmt.Sprintf("%sFile", key))
field := object.FieldByName(key + "File")
// Here linter say you should simplify this code, but lets not, performance is important not clarity and complexity
fp := field.String()
if fp != "" {
Expand All @@ -151,7 +152,7 @@ func GetVariable(config *Config, key string) (string, error) {
func GetHTMLTemplate(path string) (*template.Template, error) {
var err error
if path == "" {
return nil, fmt.Errorf("no html template provided")
return nil, errors.New("no html template provided")
}
//nolint:gosec
b, err := os.ReadFile(path)
Expand Down Expand Up @@ -234,7 +235,7 @@ func ValidateParams(config *Config) error {
}
// We need to either have crowdsecLapiKey defined or the BouncerCert and Bouncerkey
if lapiKey == "" && (certBouncer == "" || certBouncerKey == "") {
return fmt.Errorf("CrowdsecLapiKey || (CrowdsecLapiTLSCertificateBouncer && CrowdsecLapiTLSCertificateBouncerKey): cannot be all empty")
return errors.New("CrowdsecLapiKey || (CrowdsecLapiTLSCertificateBouncer && CrowdsecLapiTLSCertificateBouncerKey): cannot be all empty")
} else if lapiKey != "" && (certBouncer == "" || certBouncerKey == "") {
lapiKey = strings.TrimSpace(lapiKey)
if err = validateParamsAPIKey(lapiKey); err != nil {
Expand Down Expand Up @@ -279,12 +280,12 @@ func validateParamsTLS(config *Config) error {
return err
}
if certAuth == "" {
return fmt.Errorf("CrowdsecLapiTLSCertificateAuthority must be specified when CrowdsecLapiScheme='https' and CrowdsecLapiTLSInsecureVerify=false")
return errors.New("CrowdsecLapiTLSCertificateAuthority must be specified when CrowdsecLapiScheme='https' and CrowdsecLapiTLSInsecureVerify=false")
}
tlsConfig := new(tls.Config)
tlsConfig.RootCAs = x509.NewCertPool()
if !tlsConfig.RootCAs.AppendCertsFromPEM([]byte(certAuth)) {
return fmt.Errorf("failed parsing pem file")
return errors.New("failed parsing pem file")
}
return nil
}
Expand Down Expand Up @@ -321,17 +322,17 @@ func validateParamsRequired(config *Config) error {
}
}
if config.UpdateMaxFailure < -1 {
return fmt.Errorf("UpdateMaxFailure: cannot be less than -1")
return errors.New("UpdateMaxFailure: cannot be less than -1")
}

if !contains([]string{NoneMode, LiveMode, StreamMode, AloneMode, AppsecMode}, config.CrowdsecMode) {
return fmt.Errorf("CrowdsecMode: must be one of 'none', 'live', 'stream', 'alone' or 'appsec'")
return errors.New("CrowdsecMode: must be one of 'none', 'live', 'stream', 'alone' or 'appsec'")
}
if !contains([]string{HTTP, HTTPS}, config.CrowdsecLapiScheme) {
return fmt.Errorf("CrowdsecLapiScheme: must be one of 'http' or 'https'")
return errors.New("CrowdsecLapiScheme: must be one of 'http' or 'https'")
}
if !contains([]string{"", HcaptchaProvider, RecaptchaProvider, TurnstileProvider}, config.CaptchaProvider) {
return fmt.Errorf("CrowdsecLapiScheme: must be one of 'hcaptcha', 'recaptcha' or 'turnstile'")
return errors.New("CrowdsecLapiScheme: must be one of 'hcaptcha', 'recaptcha' or 'turnstile'")
}
return nil
}
Expand Down Expand Up @@ -360,7 +361,7 @@ func GetTLSConfigCrowdsec(config *Config, log *logger.Log) (*tls.Config, error)
if !tlsConfig.RootCAs.AppendCertsFromPEM([]byte(certAuthority)) {
// here we return because if CrowdsecLapiTLSInsecureVerify is false
// and CA not load, we can't communicate with https
return nil, fmt.Errorf("getTLSConfigCrowdsec:cannot load CA and verify cert is enabled")
return nil, errors.New("getTLSConfigCrowdsec:cannot load CA and verify cert is enabled")
}
log.Debug("getTLSConfigCrowdsec:CrowdsecLapiTLSCertificateAuthority CA added successfully")
}
Expand Down
3 changes: 2 additions & 1 deletion pkg/ip/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package ip

import (
"errors"
"fmt"
"net"
"net/http"
Expand Down Expand Up @@ -45,7 +46,7 @@ func NewChecker(log *logger.Log, trustedIPs []string) (*Checker, error) {
// Contains checks if provided address is in the trusted IPs.
func (ip *Checker) Contains(addr string) (bool, error) {
if len(addr) == 0 {
return false, fmt.Errorf("Contains:noAddress")
return false, errors.New("Contains:noAddress")
}

ipAddr, err := parseIP(addr)
Expand Down
4 changes: 2 additions & 2 deletions vendor/github.com/maxlerebourg/simpleredis/simpleredis.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit ab9f4d5

Please sign in to comment.