From d6b3847fbd28d7d0f6eaa5377027c9bf56255dfd Mon Sep 17 00:00:00 2001 From: Alex Ellis Date: Fri, 7 Jun 2019 10:11:40 +0100 Subject: [PATCH] Add body from basic auth plugin. Fixes issue by adding unit test to make sure the body from the plugin is written correctly and proxied to the client. Signed-off-by: Alex Ellis --- gateway/handlers/external_auth.go | 5 +++++ gateway/handlers/external_auth_test.go | 31 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/gateway/handlers/external_auth.go b/gateway/handlers/external_auth.go index 74214454..cf433ae4 100644 --- a/gateway/handlers/external_auth.go +++ b/gateway/handlers/external_auth.go @@ -2,6 +2,7 @@ package handlers import ( "context" + "io" "net/http" "time" ) @@ -36,5 +37,9 @@ func MakeExternalAuthHandler(next http.HandlerFunc, upstreamTimeout time.Duratio copyHeaders(w.Header(), &res.Header) w.WriteHeader(res.StatusCode) + + if res.Body != nil { + io.Copy(w, res.Body) + } } } diff --git a/gateway/handlers/external_auth_test.go b/gateway/handlers/external_auth_test.go index f68cd1ae..a4237f53 100644 --- a/gateway/handlers/external_auth_test.go +++ b/gateway/handlers/external_auth_test.go @@ -1,6 +1,7 @@ package handlers import ( + "bytes" "net/http" "net/http/httptest" "testing" @@ -30,6 +31,36 @@ func Test_External_Auth_Wrapper_FailsInvalidAuth(t *testing.T) { } } +func Test_External_Auth_Wrapper_FailsInvalidAuth_WritesBody(t *testing.T) { + + wantBody := []byte(`invalid credentials`) + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + w.Write(wantBody) + })) + + defer s.Close() + + next := func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) + } + + passBody := false + handler := MakeExternalAuthHandler(next, time.Second*5, s.URL, passBody) + + req := httptest.NewRequest(http.MethodGet, s.URL, nil) + rr := httptest.NewRecorder() + handler(rr, req) + + if rr.Code == http.StatusOK { + t.Errorf("Status incorrect, did not want: %d, but got %d", http.StatusOK, rr.Code) + } + + if bytes.Compare(rr.Body.Bytes(), wantBody) != 0 { + t.Errorf("Body incorrect, want: %s, but got %s", []byte(wantBody), rr.Body) + } +} + func Test_External_Auth_Wrapper_PassesValidAuth(t *testing.T) { s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {