diff options
author | Ririsoft <[email protected]> | 2024-06-12 23:17:46 +0200 |
---|---|---|
committer | GitHub <[email protected]> | 2024-06-12 15:17:46 -0600 |
commit | 8e0d3e1ec56cd349f02c9d201234c56373688ddd (patch) | |
tree | 21097c685d125ce4ffe8e23c7764ea7d2b27430f | |
parent | d85cc2ec103de72658c55ba74197337c99bd1f74 (diff) | |
download | caddy-8e0d3e1ec56cd349f02c9d201234c56373688ddd.tar.gz caddy-8e0d3e1ec56cd349f02c9d201234c56373688ddd.zip |
logging: set file mode when the file already exist (#6391)
101d3e7 introduced a configuration option to set the log file mode.
This option was not taken into account if the file already exists,
making users having to delete their logs to have new logs created
with the right mode.
-rw-r--r-- | modules/logging/filewriter.go | 12 | ||||
-rw-r--r-- | modules/logging/filewriter_test.go | 39 |
2 files changed, 50 insertions, 1 deletions
diff --git a/modules/logging/filewriter.go b/modules/logging/filewriter.go index 09cea1b4e..44c0feb67 100644 --- a/modules/logging/filewriter.go +++ b/modules/logging/filewriter.go @@ -167,8 +167,18 @@ func (fw FileWriter) OpenWriter() (io.WriteCloser, error) { fw.RollKeepDays = 90 } - f_tmp, _ := os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(fw.Mode)) + // create the file if it does not exist with the right mode. + // lumberjack will reuse the file mode across log rotation. + f_tmp, err := os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(fw.Mode)) + if err != nil { + return nil, err + } f_tmp.Close() + // ensure already existing files have the right mode, + // since OpenFile will not set the mode in such case. + if err = os.Chmod(fw.Filename, os.FileMode(fw.Mode)); err != nil { + return nil, err + } return &lumberjack.Logger{ Filename: fw.Filename, diff --git a/modules/logging/filewriter_test.go b/modules/logging/filewriter_test.go index ab403930c..0c54a6590 100644 --- a/modules/logging/filewriter_test.go +++ b/modules/logging/filewriter_test.go @@ -345,3 +345,42 @@ func TestFileModeToJSON(t *testing.T) { }) } } + +func TestFileModeModification(t *testing.T) { + m := syscall.Umask(0o000) + defer syscall.Umask(m) + + dir, err := os.MkdirTemp("", "caddytest") + if err != nil { + t.Fatalf("failed to create tempdir: %v", err) + } + defer os.RemoveAll(dir) + + fpath := path.Join(dir, "test.log") + f_tmp, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(0600)) + if err != nil { + t.Fatalf("failed to create test file: %v", err) + } + f_tmp.Close() + + fw := FileWriter{ + Mode: 0o666, + Filename: fpath, + } + + logger, err := fw.OpenWriter() + if err != nil { + t.Fatalf("failed to create file: %v", err) + } + defer logger.Close() + + st, err := os.Stat(fpath) + if err != nil { + t.Fatalf("failed to check file permissions: %v", err) + } + + want := os.FileMode(fw.Mode) + if st.Mode() != want { + t.Errorf("file mode is %v, want %v", st.Mode(), want) + } +} |