refactor: optionally compare passed hash with computed one and reject if they don't match

This commit is contained in:
Derrick Hammer 2023-05-22 11:00:24 -04:00
parent 09f9a5bdfd
commit ed6220fc7d
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
3 changed files with 25 additions and 3 deletions

View File

@ -26,7 +26,7 @@ func (f *FilesController) PostUpload() {
return return
} }
upload, err := files.Upload(file, meta.Size) upload, err := files.Upload(file, meta.Size, nil)
if internalError(ctx, err) { if internalError(ctx, err) {
shared.GetLogger().Debug("failed uploading file", zap.Error(err)) shared.GetLogger().Debug("failed uploading file", zap.Error(err))

View File

@ -1,6 +1,7 @@
package files package files
import ( import (
"bytes"
"context" "context"
"encoding/hex" "encoding/hex"
"errors" "errors"
@ -25,7 +26,7 @@ func Init() {
client.SetDisableWarn(true) client.SetDisableWarn(true)
} }
func Upload(r io.ReadSeeker, size int64) (model.Upload, error) { func Upload(r io.ReadSeeker, size int64, hash []byte) (model.Upload, error) {
var upload model.Upload var upload model.Upload
tree, hashBytes, err := bao.ComputeTree(r, size) tree, hashBytes, err := bao.ComputeTree(r, size)
@ -35,6 +36,13 @@ func Upload(r io.ReadSeeker, size int64) (model.Upload, error) {
return upload, err return upload, err
} }
if hash != nil {
if bytes.Compare(hashBytes[:], hash) != 0 {
shared.GetLogger().Error("File hash does not match provided file hash")
return upload, err
}
}
hashHex := hex.EncodeToString(hashBytes[:]) hashHex := hex.EncodeToString(hashBytes[:])
_, err = r.Seek(0, io.SeekStart) _, err = r.Seek(0, io.SeekStart)

View File

@ -147,7 +147,21 @@ func tusWorker(upload *tusd.Upload) error {
return err return err
} }
_, err = files.Upload(file.(io.ReadSeeker), info.Size) hashHex := info.MetaData[HASH_META_HEADER]
hashBytes, err := hex.DecodeString(hashHex)
if err != nil {
shared.GetLogger().Error("failed decoding hash", zap.Error(err))
tErr := terminateUpload(*upload)
if tErr != nil {
return tErr
}
return err
}
_, err = files.Upload(file.(io.ReadSeeker), info.Size, hashBytes)
tErr := terminateUpload(*upload) tErr := terminateUpload(*upload)
if tErr != nil { if tErr != nil {