frontend.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package httpservers
  2. /*
  3. This file implements a very simple, lightweight reverse proxy so that REST and
  4. the webui can be accessed from a single endpoint.
  5. This makes external reverse proxies (treafik, haproxy, etc) easier, CORS goes
  6. away, and several other issues.
  7. */
  8. import (
  9. "net/http"
  10. "net/http/httputil"
  11. "net/url"
  12. "path"
  13. "github.com/OliveTin/OliveTin/internal/api"
  14. "github.com/OliveTin/OliveTin/internal/auth"
  15. "github.com/OliveTin/OliveTin/internal/auth/otoauth2"
  16. config "github.com/OliveTin/OliveTin/internal/config"
  17. "github.com/OliveTin/OliveTin/internal/executor"
  18. "github.com/OliveTin/OliveTin/internal/webhooks"
  19. log "github.com/sirupsen/logrus"
  20. )
  21. func applySecurityHeaders(cfg *config.Config, w http.ResponseWriter) {
  22. applyCSP(cfg, w)
  23. applyXContentTypeOptions(cfg, w)
  24. applyXFrameOptions(cfg, w)
  25. }
  26. func applyCSP(cfg *config.Config, w http.ResponseWriter) {
  27. if !cfg.Security.HeaderContentSecurityPolicy || cfg.Security.ContentSecurityPolicy == "" {
  28. return
  29. }
  30. w.Header().Set("Content-Security-Policy", cfg.Security.ContentSecurityPolicy)
  31. }
  32. func applyXContentTypeOptions(cfg *config.Config, w http.ResponseWriter) {
  33. if !cfg.Security.HeaderXContentTypeOptions {
  34. return
  35. }
  36. w.Header().Set("X-Content-Type-Options", "nosniff")
  37. }
  38. func applyXFrameOptions(cfg *config.Config, w http.ResponseWriter) {
  39. if !cfg.Security.HeaderXFrameOptions || cfg.Security.XFrameOptions == "" {
  40. return
  41. }
  42. w.Header().Set("X-Frame-Options", cfg.Security.XFrameOptions)
  43. }
  44. func securityHeadersMiddleware(cfg *config.Config, next http.Handler) http.Handler {
  45. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  46. applySecurityHeaders(cfg, w)
  47. next.ServeHTTP(w, r)
  48. })
  49. }
  50. func logDebugRequest(cfg *config.Config, source string, r *http.Request) {
  51. if cfg.LogDebugOptions.SingleFrontendRequests {
  52. log.Debugf("SingleFrontend HTTP Req URL %v: %q", source, r.URL)
  53. if cfg.LogDebugOptions.SingleFrontendRequestHeaders {
  54. for name, values := range r.Header {
  55. log.Debugf("SingleFrontend HTTP Req Hdr: %v = %v", name, values)
  56. }
  57. }
  58. }
  59. }
  60. func StartFrontendMux(cfg *config.Config, ex *executor.Executor) {
  61. log.WithFields(log.Fields{
  62. "address": cfg.ListenAddressSingleHTTPFrontend,
  63. }).Info("Starting single HTTP frontend")
  64. go StartPrometheus(cfg)
  65. mux := http.NewServeMux()
  66. mux.HandleFunc("/api/upload/action-argument", api.GetActionArgumentUploadHandler(ex))
  67. apiPath, apiHandler := api.GetNewHandler(ex)
  68. log.Infof("API path is %s", apiPath)
  69. mux.Handle("/api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  70. fn := path.Base(r.URL.Path)
  71. // Translate /api/foo/bar to /api/bar - this preserves compatibility
  72. // with OliveTin 2k.
  73. r.URL.Path = apiPath + fn
  74. log.WithFields(log.Fields{
  75. "path": r.URL.Path,
  76. }).Tracef("SingleFrontend HTTP API Req URL after rewrite")
  77. logDebugRequest(cfg, "api", r)
  78. apiHandler.ServeHTTP(w, r)
  79. }))
  80. oauth2handler := otoauth2.NewOAuth2Handler(cfg)
  81. auth.AddAuthChainFunction(oauth2handler.CheckUserFromOAuth2Cookie)
  82. auth.RegisterOAuth2SessionRevoker(oauth2handler.RevokeSession)
  83. mux.HandleFunc("/oauth/login", oauth2handler.HandleOAuthLogin)
  84. mux.HandleFunc("/oauth/callback", oauth2handler.HandleOAuthCallback)
  85. mux.HandleFunc("/readyz", handleReadyz)
  86. webhookHandler := webhooks.NewWebhookHandler(cfg, ex)
  87. mux.HandleFunc("/webhooks", webhookHandler.HandleWebhook)
  88. mux.HandleFunc("/webhooks/", webhookHandler.HandleWebhook)
  89. webuiServer := NewWebUIServer(cfg)
  90. mux.HandleFunc("/theme.css", webuiServer.generateThemeCss)
  91. mux.Handle("/custom-webui/", webuiServer.handleCustomWebui())
  92. mux.HandleFunc("/", webuiServer.handleWebui)
  93. if cfg.Prometheus.Enabled {
  94. promURL, _ := url.Parse("http://" + cfg.ListenAddressPrometheus)
  95. promProxy := httputil.NewSingleHostReverseProxy(promURL)
  96. mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
  97. logDebugRequest(cfg, "prom", r)
  98. promProxy.ServeHTTP(w, r)
  99. })
  100. }
  101. srv := &http.Server{
  102. Addr: cfg.ListenAddressSingleHTTPFrontend,
  103. Handler: securityHeadersMiddleware(cfg, mux),
  104. }
  105. log.Fatal(srv.ListenAndServe())
  106. }
  107. func handleReadyz(w http.ResponseWriter, r *http.Request) {
  108. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  109. w.WriteHeader(http.StatusOK)
  110. _, err := w.Write([]byte("OK. Single HTTP Frontend is ready.\n"))
  111. if err != nil {
  112. log.WithFields(log.Fields{
  113. "error": err,
  114. }).Warnf("Failed to write readyz response")
  115. }
  116. }