valyala / fasthttp

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
MIT License
21.89k stars 1.76k forks source link

serving a compress enabled public folder without +w permissions results in a 404 #1766

Closed rhabichl closed 6 months ago

rhabichl commented 6 months ago

Original bug gofiber/fiber#2940

The problem is in fs.go in the following function: openIndexFile()

func (h *fsHandler) openIndexFile(ctx *RequestCtx, dirPath string, mustCompress bool, fileEncoding string) (*fsFile, error) {
    for _, indexName := range h.indexNames {
        indexFilePath := dirPath + "/" + indexName
        ff, err := h.openFSFile(indexFilePath, mustCompress, fileEncoding)
        if err == nil {
            return ff, nil
        }
        if !errors.Is(err, fs.ErrNotExist) {
            return nil, fmt.Errorf("cannot open file %q: %w", indexFilePath, err)
        }
    }

    if !h.generateIndexPages {
        return nil, fmt.Errorf("cannot access directory without index page. Directory %q", dirPath)
    }

    return h.createDirIndex(ctx, dirPath, mustCompress, fileEncoding)
}

Because nowhere is checked if h.openFSFile() returns an error because the compressed file can't be written to the filesystem. The solution would be to check for the error like in handleRequest() and retry without compression:

func (h *fsHandler) handleRequest(ctx *RequestCtx) {
...
                var err error
        ff, err = h.openFSFile(filePath, mustCompress, fileEncoding)
        if mustCompress && err == errNoCreatePermission {
            ctx.Logger().Printf("insufficient permissions for saving compressed file for %q. Serving uncompressed file. "+
                "Allow write access to the directory with this file in order to improve fasthttp performance", filePath)
            mustCompress = false
            ff, err = h.openFSFile(filePath, mustCompress, fileEncoding)
        }
...
}
erikdubbelboer commented 6 months ago

Fixed in https://github.com/valyala/fasthttp/pull/1767