2020-05-05 09:53:42 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"flag"
|
2021-09-14 11:17:49 +02:00
|
|
|
"fmt"
|
2020-05-05 09:53:42 +02:00
|
|
|
"net/http"
|
|
|
|
"net/http/httputil"
|
|
|
|
"net/url"
|
2020-05-16 10:59:30 +02:00
|
|
|
"os"
|
2022-03-18 17:31:58 +01:00
|
|
|
"strings"
|
2021-11-09 18:18:27 +01:00
|
|
|
"sync"
|
2020-05-05 09:53:42 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/buildinfo"
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/envflag"
|
2020-12-03 20:40:30 +01:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/flagutil"
|
2020-05-05 09:53:42 +02:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/httpserver"
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/procutil"
|
2022-07-21 18:58:22 +02:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/pushmetrics"
|
2021-05-18 01:23:53 +02:00
|
|
|
"github.com/VictoriaMetrics/metrics"
|
2020-05-05 09:53:42 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2023-01-27 08:08:35 +01:00
|
|
|
httpListenAddr = flag.String("httpListenAddr", ":8427", "TCP address to listen for http connections. See also -httpListenAddr.useProxyProtocol")
|
|
|
|
useProxyProtocol = flag.Bool("httpListenAddr.useProxyProtocol", false, "Whether to use proxy protocol for connections accepted at -httpListenAddr . "+
|
|
|
|
"See https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt")
|
2021-05-14 17:10:19 +02:00
|
|
|
maxIdleConnsPerBackend = flag.Int("maxIdleConnsPerBackend", 100, "The maximum number of idle connections vmauth can open per each backend host")
|
2021-05-20 17:46:12 +02:00
|
|
|
reloadAuthKey = flag.String("reloadAuthKey", "", "Auth key for /-/reload http endpoint. It must be passed as authKey=...")
|
2021-09-14 11:17:49 +02:00
|
|
|
logInvalidAuthTokens = flag.Bool("logInvalidAuthTokens", false, "Whether to log requests with invalid auth tokens. "+
|
2021-10-19 14:29:07 +02:00
|
|
|
`Such requests are always counted at vmauth_http_request_errors_total{reason="invalid_auth_token"} metric, which is exposed at /metrics page`)
|
2020-05-05 09:53:42 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
2020-05-16 10:59:30 +02:00
|
|
|
// Write flags and help message to stdout, since it is easier to grep or pipe.
|
|
|
|
flag.CommandLine.SetOutput(os.Stdout)
|
2020-06-05 09:39:46 +02:00
|
|
|
flag.Usage = usage
|
2020-05-05 09:53:42 +02:00
|
|
|
envflag.Parse()
|
|
|
|
buildinfo.Init()
|
|
|
|
logger.Init()
|
2022-07-22 12:35:58 +02:00
|
|
|
pushmetrics.Init()
|
|
|
|
|
2020-05-05 09:53:42 +02:00
|
|
|
logger.Infof("starting vmauth at %q...", *httpListenAddr)
|
|
|
|
startTime := time.Now()
|
|
|
|
initAuthConfig()
|
2023-01-27 08:08:35 +01:00
|
|
|
go httpserver.Serve(*httpListenAddr, *useProxyProtocol, requestHandler)
|
2020-05-05 09:53:42 +02:00
|
|
|
logger.Infof("started vmauth in %.3f seconds", time.Since(startTime).Seconds())
|
|
|
|
|
|
|
|
sig := procutil.WaitForSigterm()
|
|
|
|
logger.Infof("received signal %s", sig)
|
|
|
|
|
|
|
|
startTime = time.Now()
|
|
|
|
logger.Infof("gracefully shutting down webservice at %q", *httpListenAddr)
|
|
|
|
if err := httpserver.Stop(*httpListenAddr); err != nil {
|
|
|
|
logger.Fatalf("cannot stop the webservice: %s", err)
|
|
|
|
}
|
|
|
|
logger.Infof("successfully shut down the webservice in %.3f seconds", time.Since(startTime).Seconds())
|
|
|
|
stopAuthConfig()
|
|
|
|
logger.Infof("successfully stopped vmauth in %.3f seconds", time.Since(startTime).Seconds())
|
|
|
|
}
|
|
|
|
|
|
|
|
func requestHandler(w http.ResponseWriter, r *http.Request) bool {
|
2021-05-18 01:23:53 +02:00
|
|
|
switch r.URL.Path {
|
|
|
|
case "/-/reload":
|
2023-01-11 00:51:55 +01:00
|
|
|
if !httpserver.CheckAuthFlag(w, r, *reloadAuthKey, "reloadAuthKey") {
|
2021-05-20 17:46:12 +02:00
|
|
|
return true
|
|
|
|
}
|
2021-05-18 01:23:53 +02:00
|
|
|
configReloadRequests.Inc()
|
|
|
|
procutil.SelfSIGHUP()
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
return true
|
|
|
|
}
|
2021-04-02 21:14:53 +02:00
|
|
|
authToken := r.Header.Get("Authorization")
|
|
|
|
if authToken == "" {
|
2020-08-09 08:38:41 +02:00
|
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
2021-04-02 21:14:53 +02:00
|
|
|
http.Error(w, "missing `Authorization` request header", http.StatusUnauthorized)
|
2020-05-05 09:53:42 +02:00
|
|
|
return true
|
|
|
|
}
|
2022-03-18 17:31:58 +01:00
|
|
|
if strings.HasPrefix(authToken, "Token ") {
|
|
|
|
// Handle InfluxDB's proprietary token authentication scheme as a bearer token authentication
|
|
|
|
// See https://docs.influxdata.com/influxdb/v2.0/api/
|
|
|
|
authToken = strings.Replace(authToken, "Token", "Bearer", 1)
|
|
|
|
}
|
2020-05-05 09:53:42 +02:00
|
|
|
ac := authConfig.Load().(map[string]*UserInfo)
|
2021-04-02 21:14:53 +02:00
|
|
|
ui := ac[authToken]
|
|
|
|
if ui == nil {
|
2021-09-14 11:17:49 +02:00
|
|
|
invalidAuthTokenRequests.Inc()
|
|
|
|
if *logInvalidAuthTokens {
|
|
|
|
httpserver.Errorf(w, r, "cannot find the provided auth token %q in config", authToken)
|
|
|
|
} else {
|
|
|
|
errStr := fmt.Sprintf("cannot find the provided auth token %q in config", authToken)
|
|
|
|
http.Error(w, errStr, http.StatusBadRequest)
|
|
|
|
}
|
2020-05-05 09:53:42 +02:00
|
|
|
return true
|
|
|
|
}
|
2021-02-11 11:40:59 +01:00
|
|
|
ui.requests.Inc()
|
2021-10-22 18:08:06 +02:00
|
|
|
targetURL, headers, err := createTargetURL(ui, r.URL)
|
2021-02-11 11:40:59 +01:00
|
|
|
if err != nil {
|
|
|
|
httpserver.Errorf(w, r, "cannot determine targetURL: %s", err)
|
|
|
|
return true
|
|
|
|
}
|
2021-04-21 09:55:29 +02:00
|
|
|
r.Header.Set("vm-target-url", targetURL.String())
|
2021-10-22 18:08:06 +02:00
|
|
|
for _, h := range headers {
|
|
|
|
r.Header.Set(h.Name, h.Value)
|
|
|
|
}
|
2021-06-11 11:50:22 +02:00
|
|
|
proxyRequest(w, r)
|
2020-05-05 09:53:42 +02:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2021-06-11 11:50:22 +02:00
|
|
|
func proxyRequest(w http.ResponseWriter, r *http.Request) {
|
|
|
|
defer func() {
|
|
|
|
err := recover()
|
|
|
|
if err == nil || err == http.ErrAbortHandler {
|
|
|
|
// Suppress http.ErrAbortHandler panic.
|
|
|
|
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1353
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Forward other panics to the caller.
|
|
|
|
panic(err)
|
|
|
|
}()
|
2021-11-09 18:18:27 +01:00
|
|
|
getReverseProxy().ServeHTTP(w, r)
|
2021-06-11 11:50:22 +02:00
|
|
|
}
|
|
|
|
|
2021-09-14 11:17:49 +02:00
|
|
|
var (
|
2021-10-19 14:29:07 +02:00
|
|
|
configReloadRequests = metrics.NewCounter(`vmauth_http_requests_total{path="/-/reload"}`)
|
|
|
|
invalidAuthTokenRequests = metrics.NewCounter(`vmauth_http_request_errors_total{reason="invalid_auth_token"}`)
|
|
|
|
missingRouteRequests = metrics.NewCounter(`vmauth_http_request_errors_total{reason="missing_route"}`)
|
2021-09-14 11:17:49 +02:00
|
|
|
)
|
2021-05-18 01:23:53 +02:00
|
|
|
|
2021-11-09 18:18:27 +01:00
|
|
|
var (
|
|
|
|
reverseProxy *httputil.ReverseProxy
|
|
|
|
reverseProxyOnce sync.Once
|
|
|
|
)
|
|
|
|
|
|
|
|
func getReverseProxy() *httputil.ReverseProxy {
|
|
|
|
reverseProxyOnce.Do(initReverseProxy)
|
|
|
|
return reverseProxy
|
|
|
|
}
|
|
|
|
|
|
|
|
// initReverseProxy must be called after flag.Parse(), since it uses command-line flags.
|
|
|
|
func initReverseProxy() {
|
|
|
|
reverseProxy = &httputil.ReverseProxy{
|
|
|
|
Director: func(r *http.Request) {
|
|
|
|
targetURL := r.Header.Get("vm-target-url")
|
|
|
|
target, err := url.Parse(targetURL)
|
|
|
|
if err != nil {
|
|
|
|
logger.Panicf("BUG: unexpected error when parsing targetURL=%q: %s", targetURL, err)
|
|
|
|
}
|
|
|
|
r.URL = target
|
|
|
|
},
|
|
|
|
Transport: func() *http.Transport {
|
|
|
|
tr := http.DefaultTransport.(*http.Transport).Clone()
|
|
|
|
// Automatic compression must be disabled in order to fix https://github.com/VictoriaMetrics/VictoriaMetrics/issues/535
|
|
|
|
tr.DisableCompression = true
|
|
|
|
// Disable HTTP/2.0, since VictoriaMetrics components don't support HTTP/2.0 (because there is no sense in this).
|
|
|
|
tr.ForceAttemptHTTP2 = false
|
|
|
|
tr.MaxIdleConnsPerHost = *maxIdleConnsPerBackend
|
|
|
|
if tr.MaxIdleConns != 0 && tr.MaxIdleConns < tr.MaxIdleConnsPerHost {
|
|
|
|
tr.MaxIdleConns = tr.MaxIdleConnsPerHost
|
|
|
|
}
|
|
|
|
return tr
|
|
|
|
}(),
|
|
|
|
FlushInterval: time.Second,
|
|
|
|
ErrorLog: logger.StdErrorLogger(),
|
|
|
|
}
|
2020-05-05 09:53:42 +02:00
|
|
|
}
|
2020-06-05 09:39:46 +02:00
|
|
|
|
|
|
|
func usage() {
|
|
|
|
const s = `
|
|
|
|
vmauth authenticates and authorizes incoming requests and proxies them to VictoriaMetrics.
|
|
|
|
|
2021-04-20 19:16:17 +02:00
|
|
|
See the docs at https://docs.victoriametrics.com/vmauth.html .
|
2020-06-05 09:39:46 +02:00
|
|
|
`
|
2020-12-03 20:40:30 +01:00
|
|
|
flagutil.Usage(s)
|
2020-06-05 09:39:46 +02:00
|
|
|
}
|