-
-
Notifications
You must be signed in to change notification settings - Fork 2k
🔥 feat: Add support for RootDir and RootFs #4035
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 1 commit
e5d4bf3
06e9506
27bd252
2ddecf0
6722830
030c269
ca7e850
9e92226
09cb0c8
0d76119
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -7,10 +7,13 @@ package fiber | |||||||||||||||||||||||||||||
| import ( | ||||||||||||||||||||||||||||||
| "context" | ||||||||||||||||||||||||||||||
| "crypto/tls" | ||||||||||||||||||||||||||||||
| "errors" | ||||||||||||||||||||||||||||||
| "fmt" | ||||||||||||||||||||||||||||||
| "io" | ||||||||||||||||||||||||||||||
| "maps" | ||||||||||||||||||||||||||||||
| "mime/multipart" | ||||||||||||||||||||||||||||||
| "os" | ||||||||||||||||||||||||||||||
| "path/filepath" | ||||||||||||||||||||||||||||||
| "strconv" | ||||||||||||||||||||||||||||||
| "strings" | ||||||||||||||||||||||||||||||
| "sync/atomic" | ||||||||||||||||||||||||||||||
|
|
@@ -496,12 +499,57 @@ func (c *DefaultCtx) IsPreflight() bool { | |||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| // SaveFile saves any multipart file to disk. | ||||||||||||||||||||||||||||||
| func (*DefaultCtx) SaveFile(fileheader *multipart.FileHeader, path string) error { | ||||||||||||||||||||||||||||||
| return fasthttp.SaveMultipartFile(fileheader, path) | ||||||||||||||||||||||||||||||
| func (c *DefaultCtx) SaveFile(fileheader *multipart.FileHeader, path string) error { | ||||||||||||||||||||||||||||||
| normalized, err := validateUploadPath(path) | ||||||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||||||
| return err | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| if c.app.config.RootFs != nil { | ||||||||||||||||||||||||||||||
| fsPath := storageUploadPath(c.app.config.uploadRootFSPrefix, normalized.slashPath) | ||||||||||||||||||||||||||||||
| err = ensureNoSymlinkFS(c.app.config.RootFs, fsPath) | ||||||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||||||
| return err | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| return saveMultipartFileToFS(fileheader, fsPath, c.app.config.uploadRootFSWriter) | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| fullPath := normalized.osPath | ||||||||||||||||||||||||||||||
| if root := c.app.config.uploadRootDir; root != "" { | ||||||||||||||||||||||||||||||
| fullPath = filepath.Join(root, normalized.osPath) | ||||||||||||||||||||||||||||||
| err = ensureUploadPathWithinRoot(c.app.config.uploadRootEval, fullPath) | ||||||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||||||
| return err | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| return fasthttp.SaveMultipartFile(fileheader, fullPath) | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| // SaveFileToStorage saves any multipart file to an external storage system. | ||||||||||||||||||||||||||||||
| func (c *DefaultCtx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error { | ||||||||||||||||||||||||||||||
| normalized, err := validateUploadPath(path) | ||||||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||||||
| return err | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| if c.app.config.RootFs != nil { | ||||||||||||||||||||||||||||||
| fsPath := storageUploadPath(c.app.config.uploadRootFSPrefix, normalized.slashPath) | ||||||||||||||||||||||||||||||
| err = ensureNoSymlinkFS(c.app.config.RootFs, fsPath) | ||||||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||||||
| return err | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| if root := c.app.config.uploadRootDir; root != "" { | ||||||||||||||||||||||||||||||
| fullPath := filepath.Join(root, filepath.FromSlash(normalized.slashPath)) | ||||||||||||||||||||||||||||||
| err = ensureUploadPathWithinRoot(c.app.config.uploadRootEval, fullPath) | ||||||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||||||
| return err | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| storagePath := storageUploadPath(c.app.config.uploadRootPath, normalized.slashPath) | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| file, err := fileheader.Open() | ||||||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||||||
| return fmt.Errorf("failed to open: %w", err) | ||||||||||||||||||||||||||||||
|
|
@@ -531,13 +579,49 @@ func (c *DefaultCtx) SaveFileToStorage(fileheader *multipart.FileHeader, path st | |||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| data := append([]byte(nil), buf.Bytes()...) | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| if err := storage.SetWithContext(c.Context(), path, data, 0); err != nil { | ||||||||||||||||||||||||||||||
| if err := storage.SetWithContext(c.Context(), storagePath, data, 0); err != nil { | ||||||||||||||||||||||||||||||
| return fmt.Errorf("failed to store: %w", err) | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| return nil | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| func saveMultipartFileToFS( | ||||||||||||||||||||||||||||||
| fileheader *multipart.FileHeader, | ||||||||||||||||||||||||||||||
| path string, | ||||||||||||||||||||||||||||||
| fsys uploadFSWriter, | ||||||||||||||||||||||||||||||
| ) error { | ||||||||||||||||||||||||||||||
| file, err := fileheader.Open() | ||||||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||||||
| return fmt.Errorf("failed to open multipart file: %w", err) | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| defer file.Close() //nolint:errcheck // not needed | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| dst, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) | ||||||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||||||
| return fmt.Errorf("failed to open upload destination: %w", err) | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| writer, ok := dst.(io.Writer) | ||||||||||||||||||||||||||||||
| if !ok { | ||||||||||||||||||||||||||||||
| closeErr := dst.Close() | ||||||||||||||||||||||||||||||
| if closeErr != nil { | ||||||||||||||||||||||||||||||
| return fmt.Errorf("failed to close upload destination: %w", closeErr) | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| return errors.New("failed to open upload destination for write") | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| if _, err = io.Copy(writer, file); err != nil { | ||||||||||||||||||||||||||||||
| closeErr := dst.Close() | ||||||||||||||||||||||||||||||
| if closeErr != nil { | ||||||||||||||||||||||||||||||
| return fmt.Errorf("failed to close upload destination: %w", closeErr) | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| return fmt.Errorf("failed to copy upload data: %w", err) | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
Comment on lines
+631
to
+637
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Original copy error is lost when close also fails. When Proposed fix to preserve both errors if _, err = io.Copy(writer, file); err != nil {
closeErr := dst.Close()
if closeErr != nil {
- return fmt.Errorf("failed to close upload destination: %w", closeErr)
+ return fmt.Errorf("failed to copy upload data: %w (also failed to close: %v)", err, closeErr)
}
return fmt.Errorf("failed to copy upload data: %w", err)
}📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||
| if err := dst.Close(); err != nil { | ||||||||||||||||||||||||||||||
| return fmt.Errorf("failed to close upload destination: %w", err) | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| return nil | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| // Secure returns whether a secure connection was established. | ||||||||||||||||||||||||||||||
| func (c *DefaultCtx) Secure() bool { | ||||||||||||||||||||||||||||||
| return c.Protocol() == schemeHTTPS | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4230,25 +4230,20 @@ func Test_Ctx_RouteNormalized(t *testing.T) { | |
| func Test_Ctx_SaveFile(t *testing.T) { | ||
| // TODO We should clean this up | ||
| t.Parallel() | ||
| app := New() | ||
| rootDir := t.TempDir() | ||
| app := New(Config{RootDir: rootDir}) | ||
|
|
||
| app.Post("/test", func(c Ctx) error { | ||
| fh, err := c.Req().FormFile("file") | ||
| require.NoError(t, err) | ||
|
|
||
| tempFile, err := os.CreateTemp(os.TempDir(), "test-") | ||
| require.NoError(t, err) | ||
|
|
||
| defer func(file *os.File) { | ||
| closeErr := file.Close() | ||
| require.NoError(t, closeErr) | ||
| closeErr = os.Remove(file.Name()) | ||
| require.NoError(t, closeErr) | ||
| }(tempFile) | ||
| err = c.SaveFile(fh, tempFile.Name()) | ||
| relativePath := "upload.txt" | ||
| err = c.SaveFile(fh, relativePath) | ||
| require.NoError(t, err) | ||
|
|
||
| bs, err := os.ReadFile(tempFile.Name()) | ||
| targetPath := filepath.Join(rootDir, relativePath) | ||
| // #nosec G304 -- reading from test-controlled temp directory. | ||
| bs, err := os.ReadFile(targetPath) | ||
| require.NoError(t, err) | ||
| require.Equal(t, "hello world", string(bs)) | ||
| return nil | ||
|
|
@@ -4273,6 +4268,57 @@ func Test_Ctx_SaveFile(t *testing.T) { | |
| require.Equal(t, StatusOK, resp.StatusCode, "Status code") | ||
| } | ||
|
|
||
| // go test -run Test_Ctx_SaveFile_RootDirTraversal | ||
| func Test_Ctx_SaveFile_RootDirTraversal(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| tests := map[string]string{ | ||
| "traversal": filepath.Join("..", "outside.txt"), | ||
| "absolute": filepath.Join(t.TempDir(), "abs.txt"), | ||
| } | ||
|
|
||
| for name, targetPath := range tests { | ||
|
gaby marked this conversation as resolved.
|
||
| t.Run(name, func(t *testing.T) { | ||
| t.Parallel() | ||
| rootDir := t.TempDir() | ||
| app := New(Config{RootDir: rootDir}) | ||
|
|
||
| app.Post("/test", func(c Ctx) error { | ||
| fh, err := c.FormFile("file") | ||
| require.NoError(t, err) | ||
|
|
||
| err = c.SaveFile(fh, targetPath) | ||
| require.Error(t, err) | ||
| return c.SendStatus(StatusOK) | ||
| }) | ||
|
Comment on lines
+4801
to
+4808
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion | 🟠 Major Move these traversal assertions out of the handler and lock the exported error down. These new RootDir traversal tests only check Based on learnings: In the Fiber codebase, the linter does not allow Also applies to: 5024-5031 🤖 Prompt for AI Agents |
||
|
|
||
| body := &bytes.Buffer{} | ||
| writer := multipart.NewWriter(body) | ||
| ioWriter, err := writer.CreateFormFile("file", "test") | ||
| require.NoError(t, err) | ||
| _, err = ioWriter.Write([]byte("hello world")) | ||
| require.NoError(t, err) | ||
| require.NoError(t, writer.Close()) | ||
|
|
||
| req := httptest.NewRequest(MethodPost, "/test", body) | ||
| req.Header.Set("Content-Type", writer.FormDataContentType()) | ||
| req.Header.Set("Content-Length", strconv.Itoa(len(body.Bytes()))) | ||
|
|
||
| resp, err := app.Test(req) | ||
| require.NoError(t, err, "app.Test(req)") | ||
| require.Equal(t, StatusOK, resp.StatusCode, "Status code") | ||
|
|
||
| expectedPath := targetPath | ||
| if !filepath.IsAbs(expectedPath) { | ||
| expectedPath = filepath.Join(rootDir, expectedPath) | ||
| } | ||
| expectedPath = filepath.Clean(expectedPath) | ||
| _, statErr := os.Stat(expectedPath) | ||
| require.Error(t, statErr) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func createMultipartFileHeader(t *testing.T, filename string, data []byte) *multipart.FileHeader { | ||
| t.Helper() | ||
|
|
||
|
|
@@ -4300,6 +4346,25 @@ func createMultipartFileHeader(t *testing.T, filename string, data []byte) *mult | |
| return files[0] | ||
| } | ||
|
|
||
| type recordingStorage struct { | ||
| *memory.Storage | ||
| setKeys []string | ||
| } | ||
|
|
||
| func newRecordingStorage() *recordingStorage { | ||
| return &recordingStorage{Storage: memory.New()} | ||
| } | ||
|
|
||
| func (s *recordingStorage) SetWithContext(ctx context.Context, key string, val []byte, exp time.Duration) error { | ||
| s.setKeys = append(s.setKeys, key) | ||
| return s.Storage.SetWithContext(ctx, key, val, exp) | ||
| } | ||
|
|
||
| func (s *recordingStorage) Set(key string, val []byte, exp time.Duration) error { | ||
| s.setKeys = append(s.setKeys, key) | ||
| return s.Storage.Set(key, val, exp) | ||
| } | ||
|
|
||
| // go test -run Test_Ctx_SaveFileToStorage | ||
| func Test_Ctx_SaveFileToStorage(t *testing.T) { | ||
| t.Parallel() | ||
|
|
@@ -4342,6 +4407,52 @@ func Test_Ctx_SaveFileToStorage(t *testing.T) { | |
| require.Equal(t, StatusOK, resp.StatusCode, "Status code") | ||
| } | ||
|
|
||
| // go test -run Test_Ctx_SaveFileToStorage_RootDirTraversal | ||
| func Test_Ctx_SaveFileToStorage_RootDirTraversal(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| tests := map[string]string{ | ||
| "traversal": filepath.Join("..", "outside"), | ||
| "absolute": filepath.Join(t.TempDir(), "abs"), | ||
| } | ||
|
|
||
| for name, targetPath := range tests { | ||
|
gaby marked this conversation as resolved.
|
||
| t.Run(name, func(t *testing.T) { | ||
| t.Parallel() | ||
| rootDir := t.TempDir() | ||
| storage := newRecordingStorage() | ||
| app := New(Config{RootDir: rootDir}) | ||
|
|
||
| app.Post("/test", func(c Ctx) error { | ||
| fh, err := c.FormFile("file") | ||
| require.NoError(t, err) | ||
|
|
||
| err = c.SaveFileToStorage(fh, targetPath, storage) | ||
| require.Error(t, err) | ||
| return c.SendStatus(StatusOK) | ||
| }) | ||
|
|
||
| body := &bytes.Buffer{} | ||
| writer := multipart.NewWriter(body) | ||
| ioWriter, err := writer.CreateFormFile("file", "test") | ||
| require.NoError(t, err) | ||
| _, err = ioWriter.Write([]byte("hello world")) | ||
| require.NoError(t, err) | ||
| require.NoError(t, writer.Close()) | ||
|
|
||
| req := httptest.NewRequest(MethodPost, "/test", body) | ||
| req.Header.Set("Content-Type", writer.FormDataContentType()) | ||
| req.Header.Set("Content-Length", strconv.Itoa(len(body.Bytes()))) | ||
|
|
||
| resp, err := app.Test(req) | ||
| require.NoError(t, err, "app.Test(req)") | ||
| require.Equal(t, StatusOK, resp.StatusCode, "Status code") | ||
|
|
||
| require.Empty(t, storage.setKeys) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func Test_Ctx_SaveFileToStorage_LargeUpload(t *testing.T) { | ||
| t.Parallel() | ||
| const ( | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.