frontend.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. apiPath, apiHandler := api.GetNewHandler(ex)
  67. log.Infof("API path is %s", apiPath)
  68. mux.Handle("/api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  69. fn := path.Base(r.URL.Path)
  70. // Translate /api/foo/bar to /api/bar - this preserves compatibility
  71. // with OliveTin 2k.
  72. r.URL.Path = apiPath + fn
  73. log.WithFields(log.Fields{
  74. "path": r.URL.Path,
  75. }).Tracef("SingleFrontend HTTP API Req URL after rewrite")
  76. logDebugRequest(cfg, "api", r)
  77. apiHandler.ServeHTTP(w, r)
  78. }))
  79. oauth2handler := otoauth2.NewOAuth2Handler(cfg)
  80. auth.AddAuthChainFunction(oauth2handler.CheckUserFromOAuth2Cookie)
  81. auth.RegisterOAuth2SessionRevoker(oauth2handler.RevokeSession)
  82. mux.HandleFunc("/oauth/login", oauth2handler.HandleOAuthLogin)
  83. mux.HandleFunc("/oauth/callback", oauth2handler.HandleOAuthCallback)
  84. mux.HandleFunc("/readyz", handleReadyz)
  85. webhookHandler := webhooks.NewWebhookHandler(cfg, ex)
  86. mux.HandleFunc("/webhooks", webhookHandler.HandleWebhook)
  87. mux.HandleFunc("/webhooks/", webhookHandler.HandleWebhook)
  88. webuiServer := NewWebUIServer(cfg)
  89. mux.HandleFunc("/theme.css", webuiServer.generateThemeCss)
  90. mux.Handle("/custom-webui/", webuiServer.handleCustomWebui())
  91. mux.HandleFunc("/", webuiServer.handleWebui)
  92. if cfg.Prometheus.Enabled {
  93. promURL, _ := url.Parse("http://" + cfg.ListenAddressPrometheus)
  94. promProxy := httputil.NewSingleHostReverseProxy(promURL)
  95. mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
  96. logDebugRequest(cfg, "prom", r)
  97. promProxy.ServeHTTP(w, r)
  98. })
  99. }
  100. srv := &http.Server{
  101. Addr: cfg.ListenAddressSingleHTTPFrontend,
  102. Handler: securityHeadersMiddleware(cfg, mux),
  103. }
  104. log.Fatal(srv.ListenAndServe())
  105. }
  106. func handleReadyz(w http.ResponseWriter, r *http.Request) {
  107. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  108. w.WriteHeader(http.StatusOK)
  109. _, err := w.Write([]byte("OK. Single HTTP Frontend is ready.\n"))
  110. if err != nil {
  111. log.WithFields(log.Fields{
  112. "error": err,
  113. }).Warnf("Failed to write readyz response")
  114. }
  115. }