Skip to content
Myr

fix(context): skip chmod on pre-existing dirs in SaveUploadedFile (#4702)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix: skip chmod on pre-existing dirs in SaveUploadedFile Fixes #4622 Prior to this change, SaveUploadedFile unconditionally called os.Chmod(dir, mode) after os.MkdirAll, even when the target directory already existed. This caused 'operation not permitted' errors when saving files into system-owned directories like /tmp that the current process does not own. The fix uses os.Stat before MkdirAll to detect whether the directory already exists, and only calls os.Chmod when the directory was freshly created by MkdirAll. This restores the behaviour from v1.10.1 where only os.MkdirAll was used (which correctly skips permission changes on existing dirs) while preserving the custom permission feature added in v1.12.0. Regression test added: TestSaveUploadedFileToExistingDir saves a file into os.TempDir() (a pre-existing system directory) and asserts no error is returned. * test: make SaveUploadedFile #4622 regression test platform-independent The regression test relied on os.Chmod failing on a pre-existing directory, which only happens for a non-owner, non-root process. When tests run as root (common in containers/CI) or with a user-owned $TMPDIR, the buggy chmod succeeds, so the test passed even against the unfixed code. Assert the actual contract instead: a pre-existing directory's permissions are left unchanged. This catches the regression deterministically on every platform. Also tighten the SaveUploadedFile doc/comments: the requested perm is enforced only on the newly created destination directory, not on every directory in the path. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> ---------

authored by Muhammad Ardy Junata · committed by GitHub · parent da1e108 · Browse files · 2 files+59 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
  • Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Diff stats

2 files+59 added−2 removed

  • other:+59 added−2 removed

2 files+59 added−2 removed

modified:context_test.go+44 added
272 unmodified lines
273 dst := filepath.Join(t.TempDir(), "test", "permission_test")274 require.Error(t, c.SaveUploadedFile(f, dst, mode))275}276277// TestSaveUploadedFileToExistingDir is a regression test for issue #4622.278// SaveUploadedFile must not call os.Chmod on a directory that already exists,279// because the process may not own it (e.g. /tmp on Linux/macOS), where chmod280// fails with "operation not permitted". This asserts the behavioral contract281// directly — a pre-existing directory's permissions are left unchanged — so it282// catches the regression on every platform, including environments (root/CI,283// user-owned $TMPDIR) where chmod on the temp dir would otherwise succeed.284func TestSaveUploadedFileToExistingDir(t *testing.T) {285 buf := new(bytes.Buffer)286 mw := multipart.NewWriter(buf)287 w, err := mw.CreateFormFile("file", "existing_dir_test")288 require.NoError(t, err)289 _, err = w.Write([]byte("existing_dir_test"))290 require.NoError(t, err)291 mw.Close()292293 c, _ := CreateTestContext(httptest.NewRecorder())294 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)295 c.Request.Header.Set("Content-Type", mw.FormDataContentType())296 f, err := c.FormFile("file")297 require.NoError(t, err)298299 // A pre-existing directory owned by this process, set to a known mode.300 dir := t.TempDir()301 require.NoError(t, os.Chmod(dir, 0o700))302303 // Pass a perm that differs from the directory's current mode. The fix must304 // not apply it to the pre-existing directory; the old code chmod'd it305 // unconditionally, which also failed outright on unowned dirs like /tmp.306 dst := filepath.Join(dir, "existing_dir_test.txt")307 require.NoError(t, c.SaveUploadedFile(f, dst, 0o755))308309 // The pre-existing directory's permissions must be unchanged.310 info, err := os.Stat(dir)311 require.NoError(t, err)312 assert.Equal(t, os.FileMode(0o700), info.Mode().Perm(),313 "permissions of a pre-existing directory must not be modified")314315 // The file must still be written with the correct content.316 content, err := os.ReadFile(dst)317 require.NoError(t, err)318 assert.Equal(t, "existing_dir_test", string(content))319}320321func TestContextReset(t *testing.T) {322 router := New()323 c := router.allocateContext(0)324 assert.Equal(t, c.engine, router)
3633 unmodified lines
modified:context.go+15 added-2 removed
724 unmodified lines
725 return c.Request.MultipartForm, err726}727728// SaveUploadedFile uploads the form file to specific dst.729// An optional perm argument specifies the permission bits used when creating730// the destination directory. If not provided, the default is 0750. The exact731// permission is enforced only on the destination directory and only when it is732// newly created by this call; pre-existing directories (e.g. /tmp) are not733// modified.734func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string, perm ...fs.FileMode) error {735 src, err := file.Open()736 if err != nil {737 return err
4 unmodified lines
742 if len(perm) > 0 {743 mode = perm[0]744 }745 dir := filepath.Dir(dst)746 // Record whether the destination directory exists before MkdirAll, so we747 // only chmod a directory we just created. Chmod'ing a pre-existing directory748 // the process does not own (e.g. /tmp) fails with "operation not permitted"749 // (#4622). A non-ErrNotExist stat error also skips chmod and lets MkdirAll750 // surface the underlying failure.751 _, statErr := os.Stat(dir)752 if err = os.MkdirAll(dir, mode); err != nil {753 return err754 }755 if errors.Is(statErr, os.ErrNotExist) {744 if err = os.Chmod(dir, mode); err != nil {745 return err756 if err = os.Chmod(dir, mode); err != nil {757 return err758 }759 }760761 out, err := os.Create(dst)762 if err != nil {
777 unmodified lines