refactor: add AppError helpers and harden upload/download error handling
- refactor: replace inline AppError literals with model.New*Error constructors in service and handler layers - feat: PromoteStaged falls back to copy/delete when os.Rename returns EXDEV (cross-device link) - fix: upload error messages no longer leak internal multipart field names or parser implementation details - fix: upload size violations are converted to domain error ErrUploadTooLarge at the handler boundary - fix: download logs error and size mismatch when io.Copy fails or writes fewer bytes than expected - test: add tests for field name leak prevention, parser error sanitization, read errors after response start, and EXDEV fallback
This commit is contained in:
@@ -2,11 +2,13 @@ package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -14,6 +16,8 @@ const (
|
||||
stagingPathPrefix = "staging"
|
||||
)
|
||||
|
||||
var renameLocalFile = os.Rename
|
||||
|
||||
// LocalStorage implements StorageBackend using the local filesystem.
|
||||
type LocalStorage struct {
|
||||
basePath string
|
||||
@@ -87,13 +91,47 @@ func (s *LocalStorage) PromoteStaged(_ context.Context, stagedPath, finalPath st
|
||||
return fmt.Errorf("create parent directory: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(fullStagedPath, fullFinalPath); err != nil {
|
||||
if err := renameLocalFile(fullStagedPath, fullFinalPath); err != nil {
|
||||
if errors.Is(err, syscall.EXDEV) {
|
||||
return promoteByCopy(fullStagedPath, fullFinalPath)
|
||||
}
|
||||
return fmt.Errorf("promote staged file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func promoteByCopy(stagedPath, finalPath string) error {
|
||||
source, err := os.Open(stagedPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open staged file: %w", err)
|
||||
}
|
||||
defer source.Close()
|
||||
|
||||
destination, err := os.OpenFile(finalPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create final file: %w", err)
|
||||
}
|
||||
|
||||
if _, err := io.Copy(destination, source); err != nil {
|
||||
destination.Close()
|
||||
os.Remove(finalPath)
|
||||
return fmt.Errorf("copy staged file: %w", err)
|
||||
}
|
||||
|
||||
if err := destination.Close(); err != nil {
|
||||
os.Remove(finalPath)
|
||||
return fmt.Errorf("close final file: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Remove(stagedPath); err != nil {
|
||||
os.Remove(finalPath)
|
||||
return fmt.Errorf("delete staged file after copy: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Open returns a reader for the file at path under the storage root.
|
||||
func (s *LocalStorage) Open(_ context.Context, path string) (io.ReadCloser, error) {
|
||||
fullPath := filepath.Join(s.basePath, path)
|
||||
|
||||
Reference in New Issue
Block a user