Skip to content

Commit

Permalink
[Security] New filename go through FilterFilename function while rena…
Browse files Browse the repository at this point in the history
…ming (#52)

* [Testing]: add unit tests for FilterFilename function

* [Security]: add filename filtering when user renames file

modified: handlers/image/handleImageRename.go - added FilterFilename

---------

Co-authored-by: Kevin Nielsen <[email protected]>
  • Loading branch information
raj3k and kevinanielsen authored Dec 22, 2023
1 parent 88b01b6 commit 2342b1a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
13 changes: 10 additions & 3 deletions handlers/image/handleImageRename.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,25 @@ func HandleImageRename(c *gin.Context) {
return
}

filteredNewName, err := util.FilterFilename(newName)

if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}

prefix := filepath.Join(util.ExPath, "uploads", "images")

err := os.Rename(
err = os.Rename(
filepath.Join(prefix, oldName),
filepath.Join(prefix, newName),
filepath.Join(prefix, filteredNewName),
)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to rename file: %s", err.Error())
return
}

err = database.RenameImage(oldName, newName)
err = database.RenameImage(oldName, filteredNewName)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to rename file: %s", err.Error())
return
Expand Down
31 changes: 31 additions & 0 deletions util/filterFilename_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package util

import "testing"

func TestFilterFilename(t *testing.T) {
testCases := []struct {
input string
expected string
wantErr bool
}{
{"file.txt", "file.txt", false},
{"file/with/slashes.txt", "filewithslashes.txt", false},
{"file\\with\\backslashes.txt", "filewithbackslashes.txt", false},
{"file/with/more/than/one.period.txt", "file/with/more/than/one.period.txt", true},
}

for _, tc := range testCases {
t.Run(tc.input, func(t *testing.T) {
result, err := FilterFilename(tc.input)

if (err != nil) != tc.wantErr {
t.Errorf("FilterFilename(%s) error = %v, wantErr %v", tc.input, err, tc.wantErr)
return
}

if result != tc.expected {
t.Errorf("FilterFilename(%s) = %v, want %v", tc.input, result, tc.expected)
}
})
}
}

0 comments on commit 2342b1a

Please sign in to comment.