如何处理gosec linter警告:可能通过变量包含文件

How do I solve the following warning from gosec linter:

::warning: Potential file inclusion via variable,MEDIUM,HIGH (gosec)

The linter is warning me on the first line of this function:

func File2lines(filePath string) ([]string, error) {
    f, err := os.Open(filePath) //Warning here
    if err != nil {
        return nil, err
    }
    defer f.Close()
    return linesFromReader(f)
}

I have tried reading up on local file inclusion, but cannot see how that would be applicable here.

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.

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.