zrok/endpoints/frontend/http.go

277 lines
7.7 KiB
Go
Raw Normal View History

2022-08-31 20:49:41 +02:00
package frontend
2022-07-19 22:15:54 +02:00
import (
2022-08-10 21:15:35 +02:00
"context"
"fmt"
2022-09-07 18:22:22 +02:00
"github.com/openziti-test-kitchen/zrok/endpoints/frontend/health_ui"
2022-09-07 20:17:08 +02:00
"github.com/openziti-test-kitchen/zrok/endpoints/frontend/notfound_ui"
2022-08-15 23:29:31 +02:00
"github.com/openziti-test-kitchen/zrok/model"
2022-07-20 20:36:14 +02:00
"github.com/openziti-test-kitchen/zrok/util"
"github.com/openziti-test-kitchen/zrok/zrokdir"
2022-07-20 20:16:01 +02:00
"github.com/openziti/sdk-golang/ziti"
"github.com/openziti/sdk-golang/ziti/config"
2022-08-15 23:52:24 +02:00
"github.com/openziti/sdk-golang/ziti/edge"
2022-07-20 20:16:01 +02:00
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
2022-08-10 21:15:35 +02:00
"net"
2022-07-19 22:15:54 +02:00
"net/http"
2022-08-10 21:15:35 +02:00
"net/http/httputil"
"net/url"
2022-07-26 23:30:06 +02:00
"strings"
2022-07-19 22:15:54 +02:00
)
2022-08-18 22:57:38 +02:00
type httpListen struct {
cfg *Config
zCtx ziti.Context
handler http.Handler
2022-10-10 22:56:01 +02:00
metrics *metricsAgent
2022-08-18 22:57:38 +02:00
}
func NewHTTP(cfg *Config) (*httpListen, error) {
ma, err := newMetricsAgent(cfg.Identity)
if err != nil {
return nil, err
}
2022-10-10 22:56:01 +02:00
go ma.run()
zCfgPath, err := zrokdir.ZitiIdentityFile(cfg.Identity)
if err != nil {
return nil, errors.Wrapf(err, "error getting ziti identity '%v' from zrokdir", cfg.Identity)
}
zCfg, err := config.NewFromFile(zCfgPath)
2022-07-20 20:16:01 +02:00
if err != nil {
2022-08-18 22:57:38 +02:00
return nil, errors.Wrap(err, "error loading config")
2022-07-20 20:16:01 +02:00
}
2022-08-15 23:29:31 +02:00
zCfg.ConfigTypes = []string{model.ZrokProxyConfig}
2022-07-20 20:16:01 +02:00
zCtx := ziti.NewContextWithConfig(zCfg)
2022-10-10 22:56:01 +02:00
zDialCtx := zitiDialContext{ctx: zCtx, updates: ma.updates}
2022-07-21 21:26:44 +02:00
zTransport := http.DefaultTransport.(*http.Transport).Clone()
zTransport.DialContext = zDialCtx.Dial
2022-07-21 21:46:14 +02:00
proxy, err := newServiceProxy(cfg, zCtx)
2022-07-20 20:36:14 +02:00
if err != nil {
2022-08-18 22:57:38 +02:00
return nil, err
2022-07-20 20:36:14 +02:00
}
2022-07-21 21:46:14 +02:00
proxy.Transport = zTransport
2022-09-07 18:22:22 +02:00
handler := authHandler(util.NewProxyHandler(proxy), "zrok", cfg, zCtx)
2022-08-18 22:57:38 +02:00
return &httpListen{
cfg: cfg,
zCtx: zCtx,
handler: handler,
2022-10-10 22:56:01 +02:00
metrics: ma,
2022-08-18 22:57:38 +02:00
}, nil
}
2022-08-18 22:57:38 +02:00
func (self *httpListen) Run() error {
return http.ListenAndServe(self.cfg.Address, self.handler)
}
2022-08-10 21:15:35 +02:00
2022-08-18 23:09:38 +02:00
type zitiDialContext struct {
2022-10-10 22:56:01 +02:00
ctx ziti.Context
updates chan metricsUpdate
2022-08-10 21:15:35 +02:00
}
2022-08-18 23:09:38 +02:00
func (self *zitiDialContext) Dial(_ context.Context, _ string, addr string) (net.Conn, error) {
2022-08-15 21:18:40 +02:00
svcName := strings.Split(addr, ":")[0] // ignore :port (we get passed 'host:port')
conn, err := self.ctx.Dial(svcName)
if err != nil {
return conn, err
}
2022-10-10 22:56:01 +02:00
return newMetricsConn(svcName, conn, self.updates), nil
2022-08-10 21:15:35 +02:00
}
func newServiceProxy(cfg *Config, ctx ziti.Context) (*httputil.ReverseProxy, error) {
proxy := hostTargetReverseProxy(cfg, ctx)
2022-08-10 21:15:35 +02:00
director := proxy.Director
proxy.Director = func(req *http.Request) {
director(req)
req.Header.Set("X-Proxy", "zrok")
}
proxy.ModifyResponse = func(resp *http.Response) error {
return nil
}
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
logrus.Errorf("error proxying: %v", err)
2022-09-07 20:32:05 +02:00
notfound_ui.WriteNotFound(w)
2022-08-10 21:15:35 +02:00
}
return proxy, nil
}
func hostTargetReverseProxy(cfg *Config, ctx ziti.Context) *httputil.ReverseProxy {
2022-08-10 21:15:35 +02:00
director := func(req *http.Request) {
targetSvc := resolveService(cfg.HostMatch, req.Host)
2022-08-15 23:52:24 +02:00
if svc, found := getRefreshedService(targetSvc, ctx); found {
if cfg, found := svc.Configs[model.ZrokProxyConfig]; found {
logrus.Debugf("auth model: %v", cfg)
2022-08-10 21:15:35 +02:00
} else {
2022-08-15 23:52:24 +02:00
logrus.Warn("no config!")
2022-08-10 21:15:35 +02:00
}
2022-08-15 23:52:24 +02:00
if target, err := url.Parse(fmt.Sprintf("http://%v", targetSvc)); err == nil {
logrus.Infof("[%v] -> %v", targetSvc, req.URL)
2022-08-15 23:52:24 +02:00
targetQuery := target.RawQuery
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
} else {
logrus.Errorf("error proxying: %v", err)
2022-08-10 21:15:35 +02:00
}
}
}
return &httputil.ReverseProxy{Director: director}
}
func joinURLPath(a, b *url.URL) (path, rawpath string) {
if a.RawPath == "" && b.RawPath == "" {
return singleJoiningSlash(a.Path, b.Path), ""
}
// Same as singleJoiningSlash, but uses EscapedPath to determine
// whether a slash should be added
apath := a.EscapedPath()
bpath := b.EscapedPath()
aslash := strings.HasSuffix(apath, "/")
bslash := strings.HasPrefix(bpath, "/")
switch {
case aslash && bslash:
return a.Path + b.Path[1:], apath + bpath[1:]
case !aslash && !bslash:
return a.Path + "/" + b.Path, apath + "/" + bpath
}
return a.Path + b.Path, apath + bpath
}
func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}
2022-08-15 23:52:24 +02:00
2022-09-07 18:22:22 +02:00
func authHandler(handler http.Handler, realm string, cfg *Config, ctx ziti.Context) http.HandlerFunc {
2022-08-16 17:27:31 +02:00
return func(w http.ResponseWriter, r *http.Request) {
svcName := resolveService(cfg.HostMatch, r.Host)
if svcName != "" {
if svc, found := getRefreshedService(svcName, ctx); found {
if cfg, found := svc.Configs[model.ZrokProxyConfig]; found {
if scheme, found := cfg["auth_scheme"]; found {
switch scheme {
case string(model.None):
logrus.Debugf("auth scheme none '%v'", svcName)
handler.ServeHTTP(w, r)
return
case string(model.Basic):
logrus.Debugf("auth scheme basic '%v", svcName)
inUser, inPass, ok := r.BasicAuth()
if !ok {
writeUnauthorizedResponse(w, realm)
return
}
authed := false
if v, found := cfg["basic_auth"]; found {
if basicAuth, ok := v.(map[string]interface{}); ok {
if v, found := basicAuth["users"]; found {
if arr, ok := v.([]interface{}); ok {
for _, v := range arr {
if um, ok := v.(map[string]interface{}); ok {
username := ""
if v, found := um["username"]; found {
if un, ok := v.(string); ok {
username = un
}
}
password := ""
if v, found := um["password"]; found {
if pw, ok := v.(string); ok {
password = pw
}
}
if username == inUser && password == inPass {
authed = true
break
}
}
}
}
}
}
}
if !authed {
writeUnauthorizedResponse(w, realm)
return
}
2022-09-07 18:22:22 +02:00
handler.ServeHTTP(w, r)
default:
logrus.Infof("invalid auth scheme '%v'", scheme)
writeUnauthorizedResponse(w, realm)
return
}
} else {
2022-09-09 16:01:24 +02:00
logrus.Warnf("%v -> no auth scheme for '%v'", r.RemoteAddr, svcName)
2022-09-07 20:17:08 +02:00
notfound_ui.WriteNotFound(w)
}
} else {
2022-09-09 16:01:24 +02:00
logrus.Warnf("%v -> no proxy config for '%v'", r.RemoteAddr, svcName)
2022-09-07 20:17:08 +02:00
notfound_ui.WriteNotFound(w)
}
} else {
2022-09-09 16:01:24 +02:00
logrus.Warnf("%v -> service '%v' not found", r.RemoteAddr, svcName)
2022-09-07 20:17:08 +02:00
notfound_ui.WriteNotFound(w)
2022-08-16 17:27:31 +02:00
}
} else {
2022-09-09 16:01:24 +02:00
logrus.Debugf("host '%v' did not match host match, returning health check", r.Host)
2022-09-07 18:22:22 +02:00
health_ui.WriteHealthOk(w)
2022-08-16 17:27:31 +02:00
}
}
}
func writeUnauthorizedResponse(w http.ResponseWriter, realm string) {
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
w.WriteHeader(401)
w.Write([]byte("No Authorization\n"))
}
2022-08-18 22:57:38 +02:00
func resolveService(hostMatch string, host string) string {
2022-08-18 22:57:38 +02:00
logrus.Debugf("host = '%v'", host)
2022-09-07 18:22:22 +02:00
if hostMatch == "" || strings.Contains(host, hostMatch) {
tokens := strings.Split(host, ".")
if len(tokens) > 0 {
return tokens[0]
}
2022-08-18 22:57:38 +02:00
}
return ""
2022-08-18 22:57:38 +02:00
}
2022-08-18 23:09:38 +02:00
func getRefreshedService(name string, ctx ziti.Context) (*edge.Service, bool) {
svc, found := ctx.GetService(name)
if !found {
if err := ctx.RefreshServices(); err != nil {
logrus.Errorf("error refreshing services: %v", err)
return nil, false
}
return ctx.GetService(name)
}
return svc, found
}