How to handle gosec linter warning: Potential file inclusion via variable
No one said the linter was smart. Looking at the function in isolation, it's impossible to say if there's a security issue. If the function is called with a filePath
that's user-supplied and insufficiently validated, and it runs in a context where it can read files that the user would not be able to otherwise (e.g. in a program with elevated privileges, or on a remote server), then there is a probably issue. Otherwise, the only thing to do about the warning is to suppress or ignore it.
Where does the path come from? If you’re not absolutely sure it can never have user input, best to clean it before use and use a known prefix, e.g.:
filePath = filepath.Join(basePath,filepath.Clean(filePath))
f, err := os.Open(filePath)
That should fix the complaint. This is a reasonable precaution anyway even if you think it is safe now, in case later someone uses your function with user data.
If you specify the file path with a variable, there is a risk that an unintended file path will be specified. Therefore, you should use filepath.Clean()
to clean up possible bad paths.
an easy solution:
f,err := os.Open(filepath.Clean(fname))