Skip to content

Commit

Permalink
logging: set file mode when the file already exist (#6391)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ririsoft authored Jun 12, 2024
1 parent d85cc2e commit 8e0d3e1
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
12 changes: 11 additions & 1 deletion modules/logging/filewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
39 changes: 39 additions & 0 deletions modules/logging/filewriter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 8e0d3e1

Please sign in to comment.