From 8e0d3e1ec56cd349f02c9d201234c56373688ddd Mon Sep 17 00:00:00 2001 From: Ririsoft Date: Wed, 12 Jun 2024 23:17:46 +0200 Subject: [PATCH] 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. --- modules/logging/filewriter.go | 12 ++++++++- modules/logging/filewriter_test.go | 39 ++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/modules/logging/filewriter.go b/modules/logging/filewriter.go index 09cea1b4..44c0feb6 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 ab403930..0c54a659 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) + } +}