Move pkg/kubectl/proxy to staging

Kubernetes-commit: 18c7ee81146c940237a6e2be23da076f165a6bcb
This commit is contained in:
Sean Sullivan 2019-07-25 12:01:00 -07:00 committed by Kubernetes Publisher
parent 3874cf7989
commit 401a0f794d
4 changed files with 766 additions and 17 deletions

23
go.mod
View File

@ -25,13 +25,13 @@ require (
golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f
gopkg.in/yaml.v2 v2.2.2
gotest.tools v2.2.0+incompatible // indirect
k8s.io/api v0.0.0-20190726022912-69e1bce1dad5
k8s.io/apimachinery v0.0.0-20190730182816-1f8faeb81191
k8s.io/cli-runtime v0.0.0-20190726024606-74a61cd71909
k8s.io/client-go v0.0.0-20190730183158-f725dd354080
k8s.io/api v0.0.0
k8s.io/apimachinery v0.0.0
k8s.io/cli-runtime v0.0.0
k8s.io/client-go v0.0.0
k8s.io/klog v0.3.1
k8s.io/kube-openapi v0.0.0-20190709113604-33be087ad058
k8s.io/metrics v0.0.0-20190730184553-de57e7cebcdb
k8s.io/metrics v0.0.0
k8s.io/utils v0.0.0-20190607212802-c55fbcfc754a
sigs.k8s.io/yaml v1.1.0
)
@ -43,10 +43,11 @@ replace (
golang.org/x/sys => golang.org/x/sys v0.0.0-20190209173611-3b5209105503
golang.org/x/text => golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db
golang.org/x/tools => golang.org/x/tools v0.0.0-20190313210603-aa82965741a9
k8s.io/api => k8s.io/api v0.0.0-20190726022912-69e1bce1dad5
k8s.io/apimachinery => k8s.io/apimachinery v0.0.0-20190730182816-1f8faeb81191
k8s.io/cli-runtime => k8s.io/cli-runtime v0.0.0-20190726024606-74a61cd71909
k8s.io/client-go => k8s.io/client-go v0.0.0-20190730183158-f725dd354080
k8s.io/code-generator => k8s.io/code-generator v0.0.0-20190726022633-14ba7d03f06f
k8s.io/metrics => k8s.io/metrics v0.0.0-20190730184553-de57e7cebcdb
k8s.io/api => ../api
k8s.io/apimachinery => ../apimachinery
k8s.io/cli-runtime => ../cli-runtime
k8s.io/client-go => ../client-go
k8s.io/code-generator => ../code-generator
k8s.io/kubectl => ../kubectl
k8s.io/metrics => ../metrics
)

7
go.sum
View File

@ -116,6 +116,7 @@ github.com/modern-go/reflect2 v0.0.0-20180320133207-05fbef0ca5da/go.mod h1:bx2lN
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f h1:y5//uYreIhSUg3J1GEMiLbxo1LJaP8RfCpH6pymGZus=
github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw=
github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
@ -196,11 +197,6 @@ gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
k8s.io/api v0.0.0-20190726022912-69e1bce1dad5/go.mod h1:V6cpJ9D7WqSy0wqcE096gcbj+W//rshgQgmj1Shdwi8=
k8s.io/apimachinery v0.0.0-20190730182816-1f8faeb81191/go.mod h1:eXR4ljjmbwK6Ng0PKsXRySPXnTUy/qBUa6kPDeckhQ0=
k8s.io/cli-runtime v0.0.0-20190726024606-74a61cd71909/go.mod h1:bk/fSEmINmKG2jHCCbqbXmwEJgE6kHVMkOC1U9dclzo=
k8s.io/client-go v0.0.0-20190730183158-f725dd354080/go.mod h1:+iYgk4mu6OkvV0vtp2KBcr9zwvjQWBoCddVilNxp68Q=
k8s.io/code-generator v0.0.0-20190726022633-14ba7d03f06f/go.mod h1:kr7tMYxZEaP3mrijPwXnhxOvPyqdJw6TZH87KfFboQ0=
k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0=
k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk=
k8s.io/klog v0.3.0/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk=
@ -208,7 +204,6 @@ k8s.io/klog v0.3.1 h1:RVgyDHY/kFKtLqh67NvEWIgkMneNoIrdkN0CxDSQc68=
k8s.io/klog v0.3.1/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk=
k8s.io/kube-openapi v0.0.0-20190709113604-33be087ad058 h1:di3XCwddOR9cWBNpfgXaskhh6cgJuwcK54rvtwUaC10=
k8s.io/kube-openapi v0.0.0-20190709113604-33be087ad058/go.mod h1:nfDlWeOsu3pUf4yWGL+ERqohP4YsZcBJXWMK+gkzOA4=
k8s.io/metrics v0.0.0-20190730184553-de57e7cebcdb/go.mod h1:J8Zr6F3wvUSoRqunTHFiMQ1Df8Or/ObLZ1urbb0g5yI=
k8s.io/utils v0.0.0-20190607212802-c55fbcfc754a h1:2jUDc9gJja832Ftp+QbDV0tVhQHMISFn01els+2ZAcw=
k8s.io/utils v0.0.0-20190607212802-c55fbcfc754a/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew=
modernc.org/cc v1.0.0/go.mod h1:1Sk4//wdnYJiUIxnW8ddKpaOJCF37yAdqYnkxUpaYxw=

264
pkg/proxy/proxy_server.go Normal file
View File

@ -0,0 +1,264 @@
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package proxy
import (
"fmt"
"net"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/proxy"
"k8s.io/client-go/rest"
"k8s.io/client-go/transport"
"k8s.io/klog"
"k8s.io/kubectl/pkg/util"
)
const (
// DefaultHostAcceptRE is the default value for which hosts to accept.
DefaultHostAcceptRE = "^localhost$,^127\\.0\\.0\\.1$,^\\[::1\\]$"
// DefaultPathAcceptRE is the default path to accept.
DefaultPathAcceptRE = "^.*"
// DefaultPathRejectRE is the default set of paths to reject.
DefaultPathRejectRE = "^/api/.*/pods/.*/exec,^/api/.*/pods/.*/attach"
// DefaultMethodRejectRE is the set of HTTP methods to reject by default.
DefaultMethodRejectRE = "^$"
)
// FilterServer rejects requests which don't match one of the specified regular expressions
type FilterServer struct {
// Only paths that match this regexp will be accepted
AcceptPaths []*regexp.Regexp
// Paths that match this regexp will be rejected, even if they match the above
RejectPaths []*regexp.Regexp
// Hosts are required to match this list of regexp
AcceptHosts []*regexp.Regexp
// Methods that match this regexp are rejected
RejectMethods []*regexp.Regexp
// The delegate to call to handle accepted requests.
delegate http.Handler
}
// MakeRegexpArray splits a comma separated list of regexps into an array of Regexp objects.
func MakeRegexpArray(str string) ([]*regexp.Regexp, error) {
parts := strings.Split(str, ",")
result := make([]*regexp.Regexp, len(parts))
for ix := range parts {
re, err := regexp.Compile(parts[ix])
if err != nil {
return nil, err
}
result[ix] = re
}
return result, nil
}
// MakeRegexpArrayOrDie creates an array of regular expression objects from a string or exits.
func MakeRegexpArrayOrDie(str string) []*regexp.Regexp {
result, err := MakeRegexpArray(str)
if err != nil {
klog.Fatalf("Error compiling re: %v", err)
}
return result
}
func matchesRegexp(str string, regexps []*regexp.Regexp) bool {
for _, re := range regexps {
if re.MatchString(str) {
klog.V(6).Infof("%v matched %s", str, re)
return true
}
}
return false
}
func (f *FilterServer) accept(method, path, host string) bool {
if matchesRegexp(path, f.RejectPaths) {
return false
}
if matchesRegexp(method, f.RejectMethods) {
return false
}
if matchesRegexp(path, f.AcceptPaths) && matchesRegexp(host, f.AcceptHosts) {
return true
}
return false
}
// HandlerFor makes a shallow copy of f which passes its requests along to the
// new delegate.
func (f *FilterServer) HandlerFor(delegate http.Handler) *FilterServer {
f2 := *f
f2.delegate = delegate
return &f2
}
// Get host from a host header value like "localhost" or "localhost:8080"
func extractHost(header string) (host string) {
host, _, err := net.SplitHostPort(header)
if err != nil {
host = header
}
return host
}
func (f *FilterServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
host := extractHost(req.Host)
if f.accept(req.Method, req.URL.Path, host) {
klog.V(3).Infof("Filter accepting %v %v %v", req.Method, req.URL.Path, host)
f.delegate.ServeHTTP(rw, req)
return
}
klog.V(3).Infof("Filter rejecting %v %v %v", req.Method, req.URL.Path, host)
http.Error(rw, http.StatusText(http.StatusForbidden), http.StatusForbidden)
}
// Server is a http.Handler which proxies Kubernetes APIs to remote API server.
type Server struct {
handler http.Handler
}
type responder struct{}
func (r *responder) Error(w http.ResponseWriter, req *http.Request, err error) {
klog.Errorf("Error while proxying request: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// makeUpgradeTransport creates a transport that explicitly bypasses HTTP2 support
// for proxy connections that must upgrade.
func makeUpgradeTransport(config *rest.Config, keepalive time.Duration) (proxy.UpgradeRequestRoundTripper, error) {
transportConfig, err := config.TransportConfig()
if err != nil {
return nil, err
}
tlsConfig, err := transport.TLSConfigFor(transportConfig)
if err != nil {
return nil, err
}
rt := utilnet.SetOldTransportDefaults(&http.Transport{
TLSClientConfig: tlsConfig,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: keepalive,
}).DialContext,
})
upgrader, err := transport.HTTPWrappersForConfig(transportConfig, proxy.MirrorRequest)
if err != nil {
return nil, err
}
return proxy.NewUpgradeRequestRoundTripper(rt, upgrader), nil
}
// NewServer creates and installs a new Server.
// 'filter', if non-nil, protects requests to the api only.
func NewServer(filebase string, apiProxyPrefix string, staticPrefix string, filter *FilterServer, cfg *rest.Config, keepalive time.Duration) (*Server, error) {
host := cfg.Host
if !strings.HasSuffix(host, "/") {
host = host + "/"
}
target, err := url.Parse(host)
if err != nil {
return nil, err
}
responder := &responder{}
transport, err := rest.TransportFor(cfg)
if err != nil {
return nil, err
}
upgradeTransport, err := makeUpgradeTransport(cfg, keepalive)
if err != nil {
return nil, err
}
proxy := proxy.NewUpgradeAwareHandler(target, transport, false, false, responder)
proxy.UpgradeTransport = upgradeTransport
proxy.UseRequestLocation = true
proxyServer := http.Handler(proxy)
if filter != nil {
proxyServer = filter.HandlerFor(proxyServer)
}
if !strings.HasPrefix(apiProxyPrefix, "/api") {
proxyServer = stripLeaveSlash(apiProxyPrefix, proxyServer)
}
mux := http.NewServeMux()
mux.Handle(apiProxyPrefix, proxyServer)
if filebase != "" {
// Require user to explicitly request this behavior rather than
// serving their working directory by default.
mux.Handle(staticPrefix, newFileHandler(staticPrefix, filebase))
}
return &Server{handler: mux}, nil
}
// Listen is a simple wrapper around net.Listen.
func (s *Server) Listen(address string, port int) (net.Listener, error) {
return net.Listen("tcp", fmt.Sprintf("%s:%d", address, port))
}
// ListenUnix does net.Listen for a unix socket
func (s *Server) ListenUnix(path string) (net.Listener, error) {
// Remove any socket, stale or not, but fall through for other files
fi, err := os.Stat(path)
if err == nil && (fi.Mode()&os.ModeSocket) != 0 {
os.Remove(path)
}
// Default to only user accessible socket, caller can open up later if desired
oldmask, _ := util.Umask(0077)
l, err := net.Listen("unix", path)
util.Umask(oldmask)
return l, err
}
// ServeOnListener starts the server using given listener, loops forever.
func (s *Server) ServeOnListener(l net.Listener) error {
server := http.Server{
Handler: s.handler,
}
return server.Serve(l)
}
func newFileHandler(prefix, base string) http.Handler {
return http.StripPrefix(prefix, http.FileServer(http.Dir(base)))
}
// like http.StripPrefix, but always leaves an initial slash. (so that our
// regexps will work.)
func stripLeaveSlash(prefix string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
p := strings.TrimPrefix(req.URL.Path, prefix)
if len(p) >= len(req.URL.Path) {
http.NotFound(w, req)
return
}
if len(p) > 0 && p[:1] != "/" {
p = "/" + p
}
req.URL.Path = p
h.ServeHTTP(w, req)
})
}

View File

@ -0,0 +1,489 @@
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package proxy
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"k8s.io/apimachinery/pkg/util/proxy"
"k8s.io/client-go/rest"
)
func TestAccept(t *testing.T) {
tests := []struct {
name string
acceptPaths string
rejectPaths string
acceptHosts string
rejectMethods string
path string
host string
method string
expectAccept bool
}{
{
name: "test1",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "",
host: "127.0.0.1",
method: "GET",
expectAccept: true,
},
{
name: "test2",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/pods",
host: "127.0.0.1",
method: "GET",
expectAccept: true,
},
{
name: "test3",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/pods",
host: "localhost",
method: "GET",
expectAccept: true,
},
{
name: "test4",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/namespaces/default/pods/foo",
host: "localhost",
method: "GET",
expectAccept: true,
},
{
name: "test5",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/namespaces/default/pods/attachfoo",
host: "localhost",
method: "GET",
expectAccept: true,
},
{
name: "test7",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/namespaces/default/pods/execfoo",
host: "localhost",
method: "GET",
expectAccept: true,
},
{
name: "test8",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/namespaces/default/pods/foo/exec",
host: "127.0.0.1",
method: "GET",
expectAccept: false,
},
{
name: "test9",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/namespaces/default/pods/foo/attach",
host: "127.0.0.1",
method: "GET",
expectAccept: false,
},
{
name: "test10",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/pods",
host: "evil.com",
method: "GET",
expectAccept: false,
},
{
name: "test11",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/pods",
host: "localhost.evil.com",
method: "GET",
expectAccept: false,
},
{
name: "test12",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/pods",
host: "127a0b0c1",
method: "GET",
expectAccept: false,
},
{
name: "test13",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/ui",
host: "localhost",
method: "GET",
expectAccept: true,
},
{
name: "test14",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/pods",
host: "localhost",
method: "POST",
expectAccept: true,
},
{
name: "test15",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/namespaces/default/pods/somepod",
host: "localhost",
method: "PUT",
expectAccept: true,
},
{
name: "test16",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: DefaultMethodRejectRE,
path: "/api/v1/namespaces/default/pods/somepod",
host: "localhost",
method: "PATCH",
expectAccept: true,
},
{
name: "test17",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: "GET",
path: "/api/v1/pods",
host: "127.0.0.1",
method: "GET",
expectAccept: false,
},
{
name: "test18",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: "POST",
path: "/api/v1/pods",
host: "localhost",
method: "POST",
expectAccept: false,
},
{
name: "test19",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: "PUT",
path: "/api/v1/namespaces/default/pods/somepod",
host: "localhost",
method: "PUT",
expectAccept: false,
},
{
name: "test20",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: "PATCH",
path: "/api/v1/namespaces/default/pods/somepod",
host: "localhost",
method: "PATCH",
expectAccept: false,
},
{
name: "test21",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: "POST,PUT,PATCH",
path: "/api/v1/namespaces/default/pods/somepod",
host: "localhost",
method: "PATCH",
expectAccept: false,
},
{
name: "test22",
acceptPaths: DefaultPathAcceptRE,
rejectPaths: DefaultPathRejectRE,
acceptHosts: DefaultHostAcceptRE,
rejectMethods: "POST,PUT,PATCH",
path: "/api/v1/namespaces/default/pods/somepod",
host: "localhost",
method: "PUT",
expectAccept: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
filter := &FilterServer{
AcceptPaths: MakeRegexpArrayOrDie(tt.acceptPaths),
RejectPaths: MakeRegexpArrayOrDie(tt.rejectPaths),
AcceptHosts: MakeRegexpArrayOrDie(tt.acceptHosts),
RejectMethods: MakeRegexpArrayOrDie(tt.rejectMethods),
}
accept := filter.accept(tt.method, tt.path, tt.host)
if accept != tt.expectAccept {
t.Errorf("expected: %v, got %v for %#v", tt.expectAccept, accept, tt)
}
})
}
}
func TestRegexpMatch(t *testing.T) {
tests := []struct {
name string
str string
regexps string
expectMatch bool
}{
{
name: "test1",
str: "foo",
regexps: "bar,.*",
expectMatch: true,
},
{
name: "test2",
str: "foo",
regexps: "bar,fo.*",
expectMatch: true,
},
{
name: "test3",
str: "bar",
regexps: "bar,fo.*",
expectMatch: true,
},
{
name: "test4",
str: "baz",
regexps: "bar,fo.*",
expectMatch: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
match := matchesRegexp(tt.str, MakeRegexpArrayOrDie(tt.regexps))
if tt.expectMatch != match {
t.Errorf("expected: %v, found: %v, for %s and %v", tt.expectMatch, match, tt.str, tt.regexps)
}
})
}
}
func TestFileServing(t *testing.T) {
const (
fname = "test.txt"
data = "This is test data"
)
dir, err := ioutil.TempDir("", "data")
if err != nil {
t.Fatalf("error creating tmp dir: %v", err)
}
defer os.RemoveAll(dir)
if err := ioutil.WriteFile(filepath.Join(dir, fname), []byte(data), 0755); err != nil {
t.Fatalf("error writing tmp file: %v", err)
}
const prefix = "/foo/"
handler := newFileHandler(prefix, dir)
server := httptest.NewServer(handler)
defer server.Close()
url := server.URL + prefix + fname
res, err := http.Get(url)
if err != nil {
t.Fatalf("http.Get(%q) error: %v", url, err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("res.StatusCode = %d; want %d", res.StatusCode, http.StatusOK)
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("error reading resp body: %v", err)
}
if string(b) != data {
t.Errorf("have %q; want %q", string(b), data)
}
}
func newProxy(target *url.URL) http.Handler {
p := proxy.NewUpgradeAwareHandler(target, http.DefaultTransport, false, false, &responder{})
p.UseRequestLocation = true
return p
}
func TestAPIRequests(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%s %s %s", r.Method, r.RequestURI, string(b))
}))
defer ts.Close()
// httptest.NewServer should always generate a valid URL.
target, _ := url.Parse(ts.URL)
target.Path = "/"
proxy := newProxy(target)
tests := []struct{ name, method, body string }{
{"test1", "GET", ""},
{"test2", "DELETE", ""},
{"test3", "POST", "test payload"},
{"test4", "PUT", "test payload"},
}
const path = "/api/test?fields=ID%3Dfoo&labels=key%3Dvalue"
for i, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r, err := http.NewRequest(tt.method, path, strings.NewReader(tt.body))
if err != nil {
t.Errorf("error creating request: %v", err)
return
}
w := httptest.NewRecorder()
proxy.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("%d: proxy.ServeHTTP w.Code = %d; want %d", i, w.Code, http.StatusOK)
}
want := strings.Join([]string{tt.method, path, tt.body}, " ")
if w.Body.String() != want {
t.Errorf("%d: response body = %q; want %q", i, w.Body.String(), want)
}
})
}
}
func TestPathHandling(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.URL.Path)
}))
defer ts.Close()
table := []struct {
name string
prefix string
reqPath string
expectPath string
}{
{"test1", "/api/", "/metrics", "404 page not found\n"},
{"test2", "/api/", "/api/metrics", "/api/metrics"},
{"test3", "/api/", "/api/v1/pods/", "/api/v1/pods/"},
{"test4", "/", "/metrics", "/metrics"},
{"test5", "/", "/api/v1/pods/", "/api/v1/pods/"},
{"test6", "/custom/", "/metrics", "404 page not found\n"},
{"test7", "/custom/", "/api/metrics", "404 page not found\n"},
{"test8", "/custom/", "/api/v1/pods/", "404 page not found\n"},
{"test9", "/custom/", "/custom/api/metrics", "/api/metrics"},
{"test10", "/custom/", "/custom/api/v1/pods/", "/api/v1/pods/"},
}
cc := &rest.Config{
Host: ts.URL,
}
for _, tt := range table {
t.Run(tt.name, func(t *testing.T) {
p, err := NewServer("", tt.prefix, "/not/used/for/this/test", nil, cc, 0)
if err != nil {
t.Fatalf("%#v: %v", tt, err)
}
pts := httptest.NewServer(p.handler)
defer pts.Close()
r, err := http.Get(pts.URL + tt.reqPath)
if err != nil {
t.Fatalf("%#v: %v", tt, err)
}
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
t.Fatalf("%#v: %v", tt, err)
}
if e, a := tt.expectPath, string(body); e != a {
t.Errorf("%#v: Wanted %q, got %q", tt, e, a)
}
})
}
}
func TestExtractHost(t *testing.T) {
fixtures := map[string]string{
"localhost:8085": "localhost",
"marmalade": "marmalade",
}
for header, expected := range fixtures {
host := extractHost(header)
if host != expected {
t.Fatalf("%s != %s", host, expected)
}
}
}