Sanitize at API level

This commit is contained in:
breel
2020-07-25 19:40:31 -06:00
parent a1d59a0248
commit 09507d38e9
4 changed files with 88 additions and 20 deletions

View File

@@ -9,6 +9,7 @@ import (
"local/dndex/storage/entity"
"local/dndex/storage/operator"
"net/http"
"regexp"
"sort"
"strings"
@@ -43,7 +44,7 @@ func who(g storage.Graph, w http.ResponseWriter, r *http.Request) error {
}
func whoGet(namespace string, g storage.Graph, w http.ResponseWriter, r *http.Request) error {
id, err := getID(r)
id, err := getCleanID(r)
if err != nil {
return whoTrace(namespace, g, w, r)
}
@@ -145,7 +146,7 @@ func whoPost(namespace string, g storage.Graph, w http.ResponseWriter, r *http.R
}
func whoDelete(namespace string, g storage.Graph, w http.ResponseWriter, r *http.Request) error {
id, err := getID(r)
id, err := getCleanID(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
@@ -201,6 +202,11 @@ func whoTrace(namespace string, g storage.Graph, w http.ResponseWriter, r *http.
return enc.Encode(names)
}
func getCleanID(r *http.Request) (string, error) {
id, err := getID(r)
return sanitize(id), err
}
func getID(r *http.Request) (string, error) {
id := r.URL.Query().Get("id")
if id == "" {
@@ -210,11 +216,11 @@ func getID(r *http.Request) (string, error) {
}
func sortOnes(ones []entity.One, r *http.Request) []entity.One {
sorting := r.URL.Query().Get("sort")
sorting := sanitize(r.URL.Query().Get("sort"))
if sorting == "" {
sorting = entity.Modified
}
order := r.URL.Query().Get("order")
order := sanitize(r.URL.Query().Get("order"))
if order == "" {
order = "-1"
}
@@ -236,3 +242,9 @@ func sortOnes(ones []entity.One, r *http.Request) []entity.One {
})
return ones
}
func sanitize(s string) string {
re := regexp.MustCompile(`[^a-zA-Z0-9- _]`)
s = re.ReplaceAllString(s, `.`)
return s
}

View File

@@ -246,6 +246,30 @@ func TestWho(t *testing.T) {
}
})
t.Run("delete regexp should be sanitized", func(t *testing.T) {
r := httptest.NewRequest(http.MethodDelete, "/who?namespace=col&id=.*", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatalf("%d: %s", w.Code, w.Body.Bytes())
}
r = httptest.NewRequest(http.MethodTrace, "/who?namespace=col", nil)
w = httptest.NewRecorder()
handler.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatalf("%d: %s", w.Code, w.Body.Bytes())
}
var v []string
if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil {
t.Fatalf("%v: %s", err, w.Body.Bytes())
}
if len(v) < 5 {
t.Fatal(len(v))
}
t.Logf("%+v", v)
})
t.Run("patch fake", func(t *testing.T) {
r := httptest.NewRequest(http.MethodPatch, "/who?namespace=col&id=FAKER"+want.Name, nil)
w := httptest.NewRecorder()