Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions pkg/server/api_discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func apiDiscoveryHandler(k8sProxy *proxy.Proxy) http.HandlerFunc {
}

// k8sViaProxy makes an in-process GET request through the k8s proxy.
func k8sViaProxy(k8sProxy *proxy.Proxy, path string, originalReq *http.Request) ([]byte, error) {
func k8sViaProxy(handler http.Handler, path string, originalReq *http.Request) (body []byte, err error) {
req, err := http.NewRequestWithContext(originalReq.Context(), "GET", path, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request for %s", path)
Expand All @@ -111,7 +111,18 @@ func k8sViaProxy(k8sProxy *proxy.Proxy, path string, originalReq *http.Request)
req.Header = originalReq.Header.Clone()

rec := httptest.NewRecorder()
k8sProxy.ServeHTTP(rec, req)

defer func() {
if p := recover(); p != nil {
if p == http.ErrAbortHandler {
err = fmt.Errorf("request aborted for %s", path)
} else {
panic(p)
}
}
}()

handler.ServeHTTP(rec, req)

if rec.Code != http.StatusOK {
return nil, fmt.Errorf("unexpected status %d for %s", rec.Code, path)
Expand Down
38 changes: 38 additions & 0 deletions pkg/server/api_discovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,44 @@ func TestApiDiscoveryHandler_AllResourceListsFail(t *testing.T) {
}
}

func TestK8sViaProxy_RecoversAbortPanic(t *testing.T) {
t.Run("ErrAbortHandler is recovered", func(t *testing.T) {
panicHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic(http.ErrAbortHandler)
})

req := httptest.NewRequest(http.MethodGet, "/apis/test/v1", nil)
_, err := k8sViaProxy(panicHandler, "/apis/test/v1", req)

if err == nil {
t.Fatal("expected error from aborted request, got nil")
}
if !strings.Contains(err.Error(), "request aborted") {
t.Errorf("expected 'request aborted' error, got: %v", err)
}
})

t.Run("unexpected panic is not swallowed", func(t *testing.T) {
sentinel := "unexpected failure"
panicHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic(sentinel)
})

defer func() {
p := recover()
if p == nil {
t.Fatal("expected panic to propagate, but it was swallowed")
}
if p != sentinel {
t.Fatalf("expected panic value %q, got %v", sentinel, p)
}
}()

req := httptest.NewRequest(http.MethodGet, "/apis/test/v1", nil)
k8sViaProxy(panicHandler, "/apis/test/v1", req)
})
}

func TestApiDiscoveryHandler_PartialFailure(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
Expand Down