gosec icon indicating copy to clipboard operation
gosec copied to clipboard

G307: Readonly files also a problem?

Open tehsphinx opened this issue 4 years ago • 1 comments

I understand that G307 is a valid concern on writable files.

But what about files that are opened ReadOnly? E.g. os.Open opens files in readonly mode. Using Write on it will error immediately with bad file descriptor. So the arguments mentioned in https://www.joeshaw.org/dont-defer-close-on-writable-files/ won't hold for readonly file descriptors.

Shouldn't gosec make that distinction as well?

Especially when using defer on Close, the open file function is usually in the same function as the Close. Then it should be possible to discern that.

tehsphinx avatar Feb 21 '21 10:02 tehsphinx

This is a good point. gosec should handle this case.

ccojocar avatar Feb 24 '21 20:02 ccojocar

Just tripped over this one with code that calls defer resp.Body.Close() which is a very common pattern.

G307: Deferring unsafe method "Close" on type "io.ReadCloser" (gosec)

For the time being I've added an exclusion for this in .golangci.yml to avoid this false positive.

issues:
  exclude:
  - Deferring unsafe method "Close" on type "io\.ReadCloser"

stevenh avatar Feb 23 '23 11:02 stevenh