Skip to content

Commit

Permalink
Check if remote file is empty
Browse files Browse the repository at this point in the history
  • Loading branch information
anbsky committed Mar 25, 2021
1 parent e5ac60e commit 0f55d5c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
27 changes: 27 additions & 0 deletions app/publish/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,3 +226,30 @@ func Test_fetchFile(t *testing.T) {
require.NoError(t, err)
require.EqualValues(t, 125000, s.Size())
}

func Test_fetchFileEmptyRemoteFile(t *testing.T) {
ts := test.MockHTTPServer(nil)
defer ts.Close()
ts.NextResponse <- ""

h := &Handler{UploadPath: os.TempDir()}
r := CreatePublishRequest(t, nil, FormParam{remoteURLParam, fmt.Sprintf("%v/file.mp4", ts.URL)})

f, err := h.fetchFile(r, 20404)
require.EqualError(t, err, "remote file is empty")
assert.Nil(t, f)
}

func Test_fetchFileRemoteFileTooLarge(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Length", fmt.Sprintf("%v", MaxRemoteFileSize+1))
}))
defer ts.Close()

h := &Handler{UploadPath: os.TempDir()}
r := CreatePublishRequest(t, nil, FormParam{remoteURLParam, fmt.Sprintf("%v/file.mp4", ts.URL)})

f, err := h.fetchFile(r, 20404)
require.EqualError(t, err, fmt.Sprintf("remote file is too large at %v bytes", MaxRemoteFileSize+1))
assert.Nil(t, f)
}
18 changes: 15 additions & 3 deletions app/publish/publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ var logger = monitor.NewModuleLogger("publish")
var method = "publish"

const (
RemotePublishLimit = 4 << 30 // 4GB
MaxRemoteFileSize = 4 << 30 // 4GB

// fileFieldName refers to the POST field containing file upload
fileFieldName = "file"
Expand Down Expand Up @@ -265,8 +265,11 @@ func (h Handler) fetchFile(r *http.Request, userID int) (*os.File, error) {
if err != nil {
return nil, werrors.Wrap(err, "cannot determine remote file size")
}
if cl >= RemotePublishLimit {
return nil, fmt.Errorf("remote file is too big at %v bytes", cl)
if cl >= MaxRemoteFileSize {
return nil, fmt.Errorf("remote file is too large at %v bytes", cl)
}
if cl == 0 {
return nil, werrors.New("remote file is empty")
}

f, err := h.createFile(userID, fname)
Expand All @@ -279,7 +282,16 @@ func (h Handler) fetchFile(r *http.Request, userID int) (*os.File, error) {
if err != nil {
return nil, err
}
if numWritten == 0 {
f.Close()
os.Remove(f.Name())
return f, werrors.New("remote file is empty")
}
log.Infof("saved uploaded file %v (%v bytes written)", f.Name(), numWritten)

if err := f.Close(); err != nil {
return f, err
}

return f, nil
}

0 comments on commit 0f55d5c

Please sign in to comment.