Skip to content

Commit c37a3be

Browse files
authored
Plugins: Serve static assets directly instead of through middleware handler (#32779)
* removed static routes from macaron * move path src to plugins pkg * use plugin details * remove dead code * fixes * use clean from std lib * reformat imports * remove caching headers + add security checks * revert using no cache header middleware * add cache-control headers * add 404 check * use new var for subsequent file handling
1 parent 7e2bf4f commit c37a3be

4 files changed

Lines changed: 79 additions & 9 deletions

File tree

‎pkg/api/api.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,9 @@ func (hs *HTTPServer) registerRoutes() {
131131
// api renew session based on cookie
132132
r.Get("/api/login/ping", quota("session"), routing.Wrap(hs.LoginAPIPing))
133133

134+
// expose plugin file system assets
135+
r.Get("/public/plugins/:pluginId/*", hs.GetPluginAssets)
136+
134137
// authed api
135138
r.Group("/api", func(apiRoute routing.RouteRegister) {
136139
// user (signed in)

‎pkg/api/http_server.go‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -329,12 +329,6 @@ func (hs *HTTPServer) addMiddlewaresAndStaticRoutes() {
329329

330330
m.Use(middleware.Recovery(hs.Cfg))
331331

332-
for _, route := range hs.PluginManager.StaticRoutes() {
333-
pluginRoute := path.Join("/public/plugins/", route.PluginId)
334-
hs.log.Debug("Plugins: Adding route", "route", pluginRoute, "dir", route.Directory)
335-
hs.mapStatic(m, route.Directory, "", pluginRoute)
336-
}
337-
338332
hs.mapStatic(m, hs.Cfg.StaticRootPath, "build", "public/build")
339333
hs.mapStatic(m, hs.Cfg.StaticRootPath, "", "public")
340334
hs.mapStatic(m, hs.Cfg.StaticRootPath, "robots.txt", "robots.txt")

‎pkg/api/plugins.go‎

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,15 @@ import (
44
"encoding/json"
55
"errors"
66
"net/http"
7+
"os"
8+
"path/filepath"
79
"sort"
10+
"strings"
811

9-
"github.com/grafana/grafana-plugin-sdk-go/backend"
12+
"github.com/grafana/grafana/pkg/setting"
13+
"gopkg.in/macaron.v1"
1014

15+
"github.com/grafana/grafana-plugin-sdk-go/backend"
1116
"github.com/grafana/grafana/pkg/api/dtos"
1217
"github.com/grafana/grafana/pkg/api/response"
1318
"github.com/grafana/grafana/pkg/bus"
@@ -235,6 +240,64 @@ func (hs *HTTPServer) CollectPluginMetrics(c *models.ReqContext) response.Respon
235240
return response.CreateNormalResponse(headers, resp.PrometheusMetrics, http.StatusOK)
236241
}
237242

243+
// GetPluginAssets returns public plugin assets (images, JS, etc.)
244+
//
245+
// /public/plugins/:pluginId/*
246+
func (hs *HTTPServer) GetPluginAssets(c *models.ReqContext) {
247+
pluginID := c.Params("pluginId")
248+
plugin := hs.PluginManager.GetPlugin(pluginID)
249+
if plugin == nil {
250+
c.Handle(hs.Cfg, 404, "Plugin not found", nil)
251+
return
252+
}
253+
254+
requestedFile := filepath.Clean(c.Params("*"))
255+
pluginFilePath := filepath.Join(plugin.PluginDir, requestedFile)
256+
257+
// It's safe to ignore gosec warning G304 since we already clean the requested file path and subsequently
258+
// use this with a prefix of the plugin's directory, which is set during plugin loading
259+
// nolint:gosec
260+
f, err := os.Open(pluginFilePath)
261+
if err != nil {
262+
if os.IsNotExist(err) {
263+
c.Handle(hs.Cfg, 404, "Could not find plugin file", err)
264+
return
265+
}
266+
c.Handle(hs.Cfg, 500, "Could not open plugin file", err)
267+
return
268+
}
269+
defer func() {
270+
if err := f.Close(); err != nil {
271+
hs.log.Error("Failed to close file", "err", err)
272+
}
273+
}()
274+
275+
fi, err := f.Stat()
276+
if err != nil {
277+
c.Handle(hs.Cfg, 500, "Plugin file exists but could not open", err)
278+
return
279+
}
280+
281+
if shouldExclude(fi) {
282+
c.Handle(hs.Cfg, 404, "Plugin file not found", nil)
283+
return
284+
}
285+
286+
headers := func(c *macaron.Context) {
287+
c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
288+
}
289+
290+
if hs.Cfg.Env == setting.Dev {
291+
headers = func(c *macaron.Context) {
292+
c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
293+
}
294+
}
295+
296+
headers(c.Context)
297+
298+
http.ServeContent(c.Resp, c.Req.Request, pluginFilePath, fi.ModTime(), f)
299+
}
300+
238301
// CheckHealth returns the health of a plugin.
239302
// /api/plugins/:pluginId/health
240303
func (hs *HTTPServer) CheckHealth(c *models.ReqContext) response.Response {
@@ -317,3 +380,13 @@ func translatePluginRequestErrorToAPIError(err error) response.Response {
317380

318381
return response.Error(500, "Plugin request failed", err)
319382
}
383+
384+
func shouldExclude(fi os.FileInfo) bool {
385+
normalizedFilename := strings.ToLower(fi.Name())
386+
387+
isUnixExecutable := fi.Mode()&0111 == 0111
388+
isWindowsExecutable := strings.HasSuffix(normalizedFilename, ".exe")
389+
isScript := strings.HasSuffix(normalizedFilename, ".sh")
390+
391+
return isUnixExecutable || isWindowsExecutable || isScript
392+
}

‎pkg/api/static/static.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,12 +165,12 @@ func staticHandler(ctx *macaron.Context, log *log.Logger, opt StaticOptions) boo
165165
}
166166

167167
file = path.Join(file, opt.IndexFile)
168-
f, err = opt.FileSystem.Open(file)
168+
indexFile, err := opt.FileSystem.Open(file)
169169
if err != nil {
170170
return false // Discard error.
171171
}
172172
defer func() {
173-
if err := f.Close(); err != nil {
173+
if err := indexFile.Close(); err != nil {
174174
log.Printf("Failed to close file: %s", err)
175175
}
176176
}()

0 commit comments

Comments
 (0)