|
| 1 | +package dashboard |
| 2 | + |
| 3 | +import ( |
| 4 | + "io/fs" |
| 5 | + "net/http" |
| 6 | + "net/url" |
| 7 | + |
| 8 | + "github.com/gorilla/mux" |
| 9 | + "github.com/traefik/traefik/v2/webui" |
| 10 | +) |
| 11 | + |
| 12 | +// Handler expose dashboard routes. |
| 13 | +type Handler struct { |
| 14 | + assets fs.FS // optional assets, to override the webui.FS default |
| 15 | +} |
| 16 | + |
| 17 | +// Append adds dashboard routes on the given router, optionally using the given |
| 18 | +// assets (or webui.FS otherwise). |
| 19 | +func Append(router *mux.Router, customAssets fs.FS) { |
| 20 | + assets := customAssets |
| 21 | + if assets == nil { |
| 22 | + assets = webui.FS |
| 23 | + } |
| 24 | + // Expose dashboard |
| 25 | + router.Methods(http.MethodGet). |
| 26 | + Path("/"). |
| 27 | + HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { |
| 28 | + http.Redirect(resp, req, safePrefix(req)+"/dashboard/", http.StatusFound) |
| 29 | + }) |
| 30 | + |
| 31 | + router.Methods(http.MethodGet). |
| 32 | + PathPrefix("/dashboard/"). |
| 33 | + HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 34 | + // allow iframes from our domains only |
| 35 | + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-src |
| 36 | + w.Header().Set("Content-Security-Policy", "frame-src 'self' https://traefik.io https://*.traefik.io;") |
| 37 | + http.StripPrefix("/dashboard/", http.FileServer(http.FS(assets))).ServeHTTP(w, r) |
| 38 | + }) |
| 39 | +} |
| 40 | + |
| 41 | +func (g Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 42 | + assets := g.assets |
| 43 | + if assets == nil { |
| 44 | + assets = webui.FS |
| 45 | + } |
| 46 | + // allow iframes from our domains only |
| 47 | + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-src |
| 48 | + w.Header().Set("Content-Security-Policy", "frame-src 'self' https://traefik.io https://*.traefik.io;") |
| 49 | + http.FileServer(http.FS(assets)).ServeHTTP(w, r) |
| 50 | +} |
| 51 | + |
| 52 | +func safePrefix(req *http.Request) string { |
| 53 | + prefix := req.Header.Get("X-Forwarded-Prefix") |
| 54 | + if prefix == "" { |
| 55 | + return "" |
| 56 | + } |
| 57 | + |
| 58 | + parse, err := url.Parse(prefix) |
| 59 | + if err != nil { |
| 60 | + return "" |
| 61 | + } |
| 62 | + |
| 63 | + if parse.Host != "" { |
| 64 | + return "" |
| 65 | + } |
| 66 | + |
| 67 | + return parse.Path |
| 68 | +} |
0 commit comments