From 9e741879efbf54eb41056bb4fc7f22418c2780a0 Mon Sep 17 00:00:00 2001 From: JALAL Date: Sun, 28 Jul 2024 20:38:26 +0100 Subject: [PATCH] fix internal error when passing invalid file fields --- internal/file/api.go | 7 ++----- internal/file/utils.go | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/internal/file/api.go b/internal/file/api.go index 4834965..395a770 100644 --- a/internal/file/api.go +++ b/internal/file/api.go @@ -91,11 +91,8 @@ func (r resource) get(c echo.Context) error { fields = strings.Split(fieldsParam, ",") } - if len(fields) > 0 { - allowed := areFieldsAllowed(fields) - if !allowed { - return errors.BadRequest("field not allowed") - } + if !checkFieldsExist(entity.File{}, fields) { + return errors.BadRequest("field not allowed") } ctx := c.Request().Context() diff --git a/internal/file/utils.go b/internal/file/utils.go index a1f0f05..46522b8 100644 --- a/internal/file/utils.go +++ b/internal/file/utils.go @@ -7,7 +7,9 @@ package file import ( "crypto/sha256" "encoding/hex" + "reflect" "regexp" + "strings" ) var ( @@ -24,6 +26,27 @@ func areFieldsAllowed(fields []string) bool { return true } +// checkFieldsExist checks if all fields exist in the tags map +func checkFieldsExist(v interface{}, fieldList []string) bool { + tags := make(map[string]struct{}) + val := reflect.ValueOf(v) + for i := 0; i < val.Type().NumField(); i++ { + field := val.Type().Field(i) + tag := field.Tag.Get("json") + if tag != "" { + tag = strings.Split(tag, ",")[0] + tags[tag] = struct{}{} + } + } + + for _, field := range fieldList { + if _, exists := tags[field]; !exists { + return false + } + } + return true +} + // isStringInSlice check if a string exist in a list of strings func isStringInSlice(a string, list []string) bool { for _, b := range list {