frontend.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. "strings"
  14. "time"
  15. "github.com/OliveTin/OliveTin/internal/api"
  16. "github.com/OliveTin/OliveTin/internal/auth"
  17. "github.com/OliveTin/OliveTin/internal/auth/otoauth2"
  18. config "github.com/OliveTin/OliveTin/internal/config"
  19. "github.com/OliveTin/OliveTin/internal/executor"
  20. "github.com/OliveTin/OliveTin/internal/webhooks"
  21. log "github.com/sirupsen/logrus"
  22. )
  23. func applySecurityHeaders(cfg *config.Config, w http.ResponseWriter) {
  24. applyCSP(cfg, w)
  25. applyXContentTypeOptions(cfg, w)
  26. applyXFrameOptions(cfg, w)
  27. }
  28. func applyCSP(cfg *config.Config, w http.ResponseWriter) {
  29. if !cfg.Security.HeaderContentSecurityPolicy || cfg.Security.ContentSecurityPolicy == "" {
  30. return
  31. }
  32. w.Header().Set("Content-Security-Policy", cfg.Security.ContentSecurityPolicy)
  33. }
  34. func applyXContentTypeOptions(cfg *config.Config, w http.ResponseWriter) {
  35. if !cfg.Security.HeaderXContentTypeOptions {
  36. return
  37. }
  38. w.Header().Set("X-Content-Type-Options", "nosniff")
  39. }
  40. func applyXFrameOptions(cfg *config.Config, w http.ResponseWriter) {
  41. if !cfg.Security.HeaderXFrameOptions || cfg.Security.XFrameOptions == "" {
  42. return
  43. }
  44. w.Header().Set("X-Frame-Options", cfg.Security.XFrameOptions)
  45. }
  46. func securityHeadersMiddleware(cfg *config.Config, next http.Handler) http.Handler {
  47. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  48. applySecurityHeaders(cfg, w)
  49. next.ServeHTTP(w, r)
  50. })
  51. }
  52. func isSensitiveLogHeaderName(name string) bool {
  53. switch strings.ToLower(name) {
  54. case "authorization", "cookie", "x-forwarded-access-token":
  55. return true
  56. default:
  57. return false
  58. }
  59. }
  60. func redactHeaderValuesForLog(name string, values []string) []string {
  61. if !isSensitiveLogHeaderName(name) {
  62. return values
  63. }
  64. out := make([]string, len(values))
  65. for i := range values {
  66. out[i] = "[redacted]"
  67. }
  68. return out
  69. }
  70. func logDebugRequest(cfg *config.Config, source string, r *http.Request) {
  71. if cfg.LogDebugOptions.SingleFrontendRequests {
  72. log.Debugf("SingleFrontend HTTP Req URL %v: %q", source, r.URL)
  73. if cfg.LogDebugOptions.SingleFrontendRequestHeaders {
  74. for name, values := range r.Header {
  75. log.Debugf("SingleFrontend HTTP Req Hdr: %v = %v", name, redactHeaderValuesForLog(name, values))
  76. }
  77. }
  78. }
  79. }
  80. func StartFrontendMux(cfg *config.Config, ex *executor.Executor) {
  81. log.WithFields(log.Fields{
  82. "address": cfg.ListenAddressSingleHTTPFrontend,
  83. }).Info("Starting single HTTP frontend")
  84. go StartPrometheus(cfg)
  85. mux := http.NewServeMux()
  86. apiPath, apiHandler := api.GetNewHandler(ex)
  87. log.Infof("API path is %s", apiPath)
  88. mux.Handle("/api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  89. fn := path.Base(r.URL.Path)
  90. // Translate /api/foo/bar to /api/bar - this preserves compatibility
  91. // with OliveTin 2k.
  92. r.URL.Path = apiPath + fn
  93. log.WithFields(log.Fields{
  94. "path": r.URL.Path,
  95. }).Tracef("SingleFrontend HTTP API Req URL after rewrite")
  96. logDebugRequest(cfg, "api", r)
  97. apiHandler.ServeHTTP(w, r)
  98. }))
  99. oauth2handler := otoauth2.NewOAuth2Handler(cfg)
  100. auth.AddAuthChainFunction(oauth2handler.CheckUserFromOAuth2Cookie)
  101. auth.RegisterOAuth2SessionRevoker(oauth2handler.RevokeSession)
  102. mux.HandleFunc("/oauth/login", oauth2handler.HandleOAuthLogin)
  103. mux.HandleFunc("/oauth/callback", oauth2handler.HandleOAuthCallback)
  104. mux.HandleFunc("/readyz", handleReadyz)
  105. webhookHandler := webhooks.NewWebhookHandler(cfg, ex)
  106. mux.HandleFunc("/webhooks", webhookHandler.HandleWebhook)
  107. mux.HandleFunc("/webhooks/", webhookHandler.HandleWebhook)
  108. webuiServer := NewWebUIServer(cfg)
  109. mux.HandleFunc("/theme.css", webuiServer.generateThemeCss)
  110. mux.Handle("/custom-webui/", webuiServer.handleCustomWebui())
  111. mux.HandleFunc("/", webuiServer.handleWebui)
  112. if cfg.Prometheus.Enabled {
  113. promURL, _ := url.Parse("http://" + cfg.ListenAddressPrometheus)
  114. promProxy := httputil.NewSingleHostReverseProxy(promURL)
  115. mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
  116. logDebugRequest(cfg, "prom", r)
  117. promProxy.ServeHTTP(w, r)
  118. })
  119. }
  120. srv := &http.Server{
  121. Addr: cfg.ListenAddressSingleHTTPFrontend,
  122. Handler: securityHeadersMiddleware(cfg, mux),
  123. ReadHeaderTimeout: 10 * time.Second,
  124. ReadTimeout: 30 * time.Second,
  125. IdleTimeout: 120 * time.Second,
  126. // WriteTimeout intentionally unset: EventStream and StartActionAndWait need long-lived writes.
  127. }
  128. log.Fatal(srv.ListenAndServe())
  129. }
  130. func handleReadyz(w http.ResponseWriter, r *http.Request) {
  131. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  132. w.WriteHeader(http.StatusOK)
  133. _, err := w.Write([]byte("OK. Single HTTP Frontend is ready.\n"))
  134. if err != nil {
  135. log.WithFields(log.Fields{
  136. "error": err,
  137. }).Warnf("Failed to write readyz response")
  138. }
  139. }