chore(): fix go-critic warnings

This commit is contained in:
Nicolas Carlier 2023-10-03 20:57:14 +00:00
parent 27947218e7
commit be011c24d4
13 changed files with 24 additions and 35 deletions

View File

@ -16,7 +16,7 @@ func HTTPParamsToShellVars[T url.Values | http.Header](params T) []string {
var result []string
for k, v := range params {
var buf bytes.Buffer
value, err := url.QueryUnescape(strings.Join(v[:], ","))
value, err := url.QueryUnescape(strings.Join(v, ","))
if err != nil {
continue
}

View File

@ -92,8 +92,6 @@ func triggerWebhook(w http.ResponseWriter, r *http.Request) {
params := HTTPParamsToShellVars(r.Form)
params = append(params, HTTPParamsToShellVars(r.Header)...)
// logger.Debug.Printf("API REQUEST: \"%s\" with params %s...\n", p, params)
// Create work
timeout := atoiFallback(r.Header.Get("X-Hook-Timeout"), defaultTimeout)
job, err := hook.NewHookJob(&hook.Request{

View File

@ -25,7 +25,7 @@ func NotNil(t *testing.T, actual interface{}, message string) {
}
// Equal assert that an object is equal to an expected value
func Equal(t *testing.T, expected interface{}, actual interface{}, message string) {
func Equal(t *testing.T, expected, actual interface{}, message string) {
if message == "" {
message = "Equal assertion failed"
}
@ -35,7 +35,7 @@ func Equal(t *testing.T, expected interface{}, actual interface{}, message strin
}
// NotEqual assert that an object is not equal to an expected value
func NotEqual(t *testing.T, expected interface{}, actual interface{}, message string) {
func NotEqual(t *testing.T, expected, actual interface{}, message string) {
if message == "" {
message = "Not equal assertion failed"
}

View File

@ -7,5 +7,5 @@ import (
// Authenticator is a generic interface to validate HTTP request credentials.
// It's returns the authentication result along with the principal (username) if it has one.
type Authenticator interface {
Validate(r *http.Request) (bool, *string)
Validate(r *http.Request) (ok bool, username string)
}

View File

@ -52,15 +52,13 @@ func NewHtpasswdFromFile(path string) (*HtpasswdFile, error) {
}
// Validate HTTP request credentials
func (h *HtpasswdFile) Validate(r *http.Request) (bool, *string) {
user, passwd, ok := r.BasicAuth()
if ok && h.validateCredentials(user, passwd) {
return true, &user
}
return false, nil
func (h *HtpasswdFile) Validate(r *http.Request) (ok bool, username string) {
username, password, ok := r.BasicAuth()
ok = ok && h.validateCredentials(username, password)
return
}
func (h *HtpasswdFile) validateCredentials(user string, password string) bool {
func (h *HtpasswdFile) validateCredentials(user, password string) bool {
pwd, exists := h.users[user]
if !exists {
return false

View File

@ -13,15 +13,15 @@ func TestValidateCredentials(t *testing.T) {
assert.Nil(t, err, ".htpasswd file should be loaded")
assert.NotNil(t, htpasswdFile, ".htpasswd file should be loaded")
req, err := http.NewRequest("POST", "http://localhost:8080", nil)
req, err := http.NewRequest("POST", "http://localhost:8080", http.NoBody)
assert.Nil(t, err, "")
req.SetBasicAuth("foo", "bar")
ok, username := htpasswdFile.Validate(req)
assert.Equal(t, true, ok, "credentials should be valid")
assert.Equal(t, "foo", *username, "invalid username")
assert.Equal(t, "foo", username, "invalid username")
req.SetBasicAuth("foo", "bad")
ok, username = htpasswdFile.Validate(req)
assert.Equal(t, false, ok, "credentials should be invalid")
assert.True(t, username == nil, "username should be nil")
assert.Equal(t, "foo", username, "invalid username")
}

View File

@ -59,7 +59,7 @@ func Bind(conf interface{}, prefix string) error {
case reflect.Bool:
bVal, err := strconv.ParseBool(val)
if err != nil {
return fmt.Errorf("Invalid boolean value for %s: %v", key, err)
return fmt.Errorf("invalid boolean value for %s: %v", key, err)
}
field.SetBool(bVal)
ptr, _ := field.Addr().Interface().(*bool)
@ -68,7 +68,7 @@ func Bind(conf interface{}, prefix string) error {
if field.Kind() == reflect.Int64 && field.Type().PkgPath() == "time" && field.Type().Name() == "Duration" {
d, err := time.ParseDuration(val)
if err != nil {
return fmt.Errorf("Invalid duration value for %s: %v", key, err)
return fmt.Errorf("invalid duration value for %s: %v", key, err)
}
field.SetInt(int64(d))
ptr, _ := field.Addr().Interface().(*time.Duration)
@ -76,7 +76,7 @@ func Bind(conf interface{}, prefix string) error {
} else {
i64Val, err := strconv.ParseInt(val, 0, fieldType.Type.Bits())
if err != nil {
return fmt.Errorf("Invalid number value for %s: %v", key, err)
return fmt.Errorf("invalid number value for %s: %v", key, err)
}
field.SetInt(i64Val)
ptr, _ := field.Addr().Interface().(*int)
@ -85,12 +85,10 @@ func Bind(conf interface{}, prefix string) error {
case reflect.Slice:
sliceType := field.Type().Elem()
if sliceType.Kind() == reflect.String {
if len(strings.TrimSpace(val)) != 0 {
if strings.TrimSpace(val) != "" {
vals := strings.Split(val, ",")
sl := make([]string, len(vals), len(vals))
for i, v := range vals {
sl[i] = v
}
sl := make([]string, len(vals))
copy(sl, vals)
field.Set(reflect.ValueOf(sl))
ptr, _ := field.Addr().Interface().(*[]string)
af := newArrayFlags(ptr)

View File

@ -56,7 +56,6 @@ func ToDelimited(s string, del uint8) string {
// ToScreamingDelimited converts a string to SCREAMING.DELIMITED.SNAKE.CASE (in this case `del = '.'; screaming = true`) or delimited.snake.case (in this case `del = '.'; screaming = false`)
func ToScreamingDelimited(s string, del uint8, screaming bool) string {
// s = addWordBoundariesToNumbers(s)
s = strings.Trim(s, " ")
n := ""
for i, v := range s {
@ -80,7 +79,7 @@ func ToScreamingDelimited(s string, del uint8, screaming bool) string {
// replace spaces/underscores with delimiters
n += string(del)
} else {
n = n + string(v)
n += string(v)
}
}

View File

@ -8,7 +8,7 @@ import (
// GetValueOrAlt get value or alt
func GetValueOrAlt(values url.Values, key, alt string) string {
if val, ok := values[key]; ok {
return strings.Join(val[:], ",")
return strings.Join(val, ",")
}
return alt
}

View File

@ -10,7 +10,7 @@ import (
// ResolveScript is resolving the target script.
func ResolveScript(dir, name string) (string, error) {
if path.Ext(name) == "" {
name = name + ".sh"
name += ".sh"
}
script := path.Clean(path.Join(dir, name))
if !strings.HasPrefix(script, dir) {

View File

@ -14,9 +14,7 @@ func AuthN(authenticator auth.Authenticator) Middleware {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Del(xWebAuthUser)
if ok, username := authenticator.Validate(r); ok {
if username != nil {
w.Header().Set(xWebAuthUser, *username)
}
w.Header().Set(xWebAuthUser, username)
next.ServeHTTP(w, r)
return
}

View File

@ -34,16 +34,14 @@ func TestHTTPSignature(t *testing.T) {
},
}
//pk := assertPrivateKey(t)
signer := assertSigner(t)
var body []byte
req, err := http.NewRequest("GET", "/", nil)
req, err := http.NewRequest("GET", "/", http.NoBody)
assert.Nil(t, err, "")
req.Header.Add("date", time.Now().UTC().Format(http.TimeFormat))
err = signer.SignRequest(privkey, "default", req, body)
assert.Nil(t, err, "")
// ts := assertTrustStore(t)
err = signature.HTTPSignatureHandler(req, ts)
assert.Nil(t, err, "")
}

View File

@ -17,7 +17,7 @@ import (
func cacheDir() (dir string) {
if u, _ := user.Current(); u != nil {
dir = filepath.Join(os.TempDir(), "webhookd-acme-cache-"+u.Username)
if err := os.MkdirAll(dir, 0700); err == nil {
if err := os.MkdirAll(dir, 0o700); err == nil {
return dir
}
}