Imp: Limit somehow the upload file in size and mimetype

This commit is contained in:
Óscar M. Lage 2024-12-05 18:46:36 +01:00
parent 5c42ff6851
commit 1ba891eef0
2 changed files with 38 additions and 1 deletions

View File

@ -25,13 +25,23 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
return return
} }
file, _, err := r.FormFile("file") file, fileHeader, err := r.FormFile("file")
if err != nil { if err != nil {
http.Error(w, "Error reading file", http.StatusBadRequest) http.Error(w, "Error reading file", http.StatusBadRequest)
return return
} }
defer file.Close() defer file.Close()
isValid, err := isTextFileAndSizeOk(file, fileHeader.Size)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !isValid {
http.Error(w, "Invalid file type or size", http.StatusBadRequest)
return
}
commandCounts, categories, pipeRedirectionCounts, commonPatterns := ProcessHistory(file) commandCounts, categories, pipeRedirectionCounts, commonPatterns := ProcessHistory(file)
limit := os.Getenv("TOP_N_COMMANDS") limit := os.Getenv("TOP_N_COMMANDS")

View File

@ -5,7 +5,9 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"html/template" "html/template"
"io"
"log" "log"
"mime/multipart"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@ -166,3 +168,28 @@ func loadTemplatesFromDir(dir string) ([]string, error) {
return templates, err return templates, err
} }
func isTextFileAndSizeOk(file multipart.File, size int64) (bool, error) {
if size > 1*1024*1024 {
return false, fmt.Errorf("File size exceeds 1MB")
}
buffer := make([]byte, 512)
_, err := file.Read(buffer)
if err != nil && err != io.EOF {
return false, fmt.Errorf("Error reading file: %v", err)
}
mimeType := http.DetectContentType(buffer)
if !strings.HasPrefix(mimeType, "text/") {
return false, fmt.Errorf("File is not a text file (mimetype: %s)", mimeType)
}
_, err = file.Seek(0, 0)
if err != nil {
return false, fmt.Errorf("Error seeking file: %v", err)
}
return true, nil
}