From 320f757917ffb83c209aa074d35f702d4170d3dd Mon Sep 17 00:00:00 2001 From: grumbulon Date: Sat, 21 Jan 2023 11:19:29 -0500 Subject: [PATCH] add confirmation of zonefile upload and add mimetype validation to only allow users to upload text/plain --- internal/api/zone.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/internal/api/zone.go b/internal/api/zone.go index 259d6a6..1a152a0 100644 --- a/internal/api/zone.go +++ b/internal/api/zone.go @@ -2,6 +2,7 @@ package api import ( "bytes" + "encoding/json" "fmt" "io" "log" @@ -64,6 +65,12 @@ func ReceiveFile(w http.ResponseWriter, r *http.Request) { return } + ok := validateContentType(file) + if !ok { + http.Error(w, "file must be text/plain", http.StatusUnsupportedMediaType) + + return + } defer file.Close() //nolint: errcheck name := strings.Split(header.Filename, ".") @@ -97,6 +104,20 @@ func ReceiveFile(w http.ResponseWriter, r *http.Request) { }) buf.Reset() + + w.WriteHeader(http.StatusCreated) + w.Header().Set("Content-Type", "application/json") + err = json.NewEncoder(w).Encode( + internal.Response{ + HTTPResponse: http.StatusCreated, + Message: "Successfully uploaded zonefile", + }) + + if err != nil { + internalServerError(w, "internal server error") + + return + } } // Parse godoc @@ -197,3 +218,20 @@ func (zone *ZoneRequest) Parse() error { return nil } + +func validateContentType(file io.Reader) bool { + bytes, err := io.ReadAll(file) + if err != nil { + return false + } + + mimeType := http.DetectContentType(bytes) + mime := strings.Contains(mimeType, "text/plain") + + switch mime { + case true: + return true + default: + return false + } +}