fix(api/file): prevent path traversal in file API

Use os.OpenRoot to restrict file access to the application root,
preventing directory traversal attacks through the file download endpoint.

Also add test to verify path traversal attempts are blocked.
This commit is contained in:
yusing
2026-03-19 10:50:58 +08:00
parent f67ef3c519
commit a541d75bb5
2 changed files with 77 additions and 1 deletions

View File

@@ -1,6 +1,7 @@
package fileapi
import (
"io"
"net/http"
"os"
"path"
@@ -44,7 +45,14 @@ func Get(c *gin.Context) {
return
}
content, err := os.ReadFile(request.FileType.GetPath(request.Filename))
f, err := os.OpenInRoot(".", request.FileType.GetPath(request.Filename))
if err != nil {
c.Error(apitypes.InternalServerError(err, "failed to open root"))
return
}
defer f.Close()
content, err := io.ReadAll(f)
if err != nil {
c.Error(apitypes.InternalServerError(err, "failed to read file"))
return