git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge pull request #1029 from oauth2-proxy/error-pages

Refactor error page rendering and allow debug messages on error

commit1e3d8547d78b9245b27b1cba11ca38d56a3f7a52 authorJoel Speed <Joel.speed@hotmail.co.uk> dateSat 13 Feb 2021, 10:52 (6 years ago) parent9cdcd2b9e8c2af
10 files changed+254−80
CHANGELOG.md+1 docs/docs/configuration/overview.md+1 oauthproxy.go+38−52 oauthproxy_test.go+1−1 pkg/apis/options/app.go+7 pkg/app/error_page.go+97 pkg/app/error_page_test.go+101 pkg/app/templates.go+2 pkg/upstream/proxy.go−22 pkg/upstream/proxy_test.go+6−5
CHANGELOG.md+1
@@ -8,6 +8,7 @@
88
99## Changes since v7.0.1
1010
11+- [#1029](https://github.com/oauth2-proxy/oauth2-proxy/pull/1029) Refactor error page rendering and allow debug messages on error (@JoelSpeed)
1112- [#1028](https://github.com/oauth2-proxy/oauth2-proxy/pull/1028) Refactor templates, update theme and provide styled error pages (@JoelSpeed)
1213- [#1039](https://github.com/oauth2-proxy/oauth2-proxy/pull/1039) Ensure errors in tests are logged to the GinkgoWriter (@JoelSpeed)
1314
docs/docs/configuration/overview.md+1
@@ -115,6 +115,7 @@ An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/
115115| `--set-xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false |
116116| `--set-authorization-header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false |
117117| `--set-basic-auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false |
118+| `--show-debug-on-error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false |
118119| `--signature-key` | string | GAP-Signature request signature key (algorithm:secretkey) | |
119120| `--silence-ping-logging` | bool | disable logging of requests to ping endpoint | false |
120121| `--skip-auth-preflight` | bool | will skip authentication for OPTIONS requests | false |
oauthproxy.go+38−52
@@ -108,6 +108,7 @@ type OAuthProxy struct {
108108 sessionChain alice.Chain
109109 headersChain alice.Chain
110110 preAuthChain alice.Chain
111+ errorPage *app.ErrorPage
111112}
112113
113114// NewOAuthProxy creates a new instance of OAuthProxy from the options provided
@@ -121,8 +122,16 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
121122 if err != nil {
122123 return nil, fmt.Errorf("error loading templates: %v", err)
123124 }
124− proxyErrorHandler := upstream.NewProxyErrorHandler(templates.Lookup("error.html"), opts.ProxyPrefix)
125− upstreamProxy, err := upstream.NewProxy(opts.UpstreamServers, opts.GetSignatureData(), proxyErrorHandler)
125+
126+ errorPage := &app.ErrorPage{
127+ Template: templates.Lookup("error.html"),
128+ ProxyPrefix: opts.ProxyPrefix,
129+ Footer: opts.Templates.Footer,
130+ Version: VERSION,
131+ Debug: opts.Templates.Debug,
132+ }
133+
134+ upstreamProxy, err := upstream.NewProxy(opts.UpstreamServers, opts.GetSignatureData(), errorPage.ProxyErrorHandler)
126135 if err != nil {
127136 return nil, fmt.Errorf("error initialising upstream proxy: %v", err)
128137 }
@@ -224,6 +233,7 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
224233 sessionChain: sessionChain,
225234 headersChain: headersChain,
226235 preAuthChain: preAuthChain,
236+ errorPage: errorPage,
227237 }, nil
228238}
229239
@@ -507,14 +517,14 @@ func (p *OAuthProxy) RobotsTxt(rw http.ResponseWriter, req *http.Request) {
507517 _, err := fmt.Fprintf(rw, "User-agent: *\nDisallow: /")
508518 if err != nil {
509519 logger.Printf("Error writing robots.txt: %v", err)
510− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
520+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
511521 return
512522 }
513523 rw.WriteHeader(http.StatusOK)
514524}
515525
516526// ErrorPage writes an error response
517−func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, req *http.Request, code int, title string, message string) {
527+func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, req *http.Request, code int, appError string, messages ...interface{}) {
518528 redirectURL, err := p.getAppRedirect(req)
519529 if err != nil {
520530 logger.Errorf("Error obtaining redirect: %v", err)
@@ -523,32 +533,7 @@ func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, req *http.Request, code i
523533 redirectURL = "/"
524534 }
525535
526− rw.WriteHeader(code)
527−
528− // We allow unescaped template.HTML since it is user configured options
529− /* #nosec G203 */
530− t := struct {
531− Title string
532− Message string
533− ProxyPrefix string
534− StatusCode int
535− Redirect string
536− Footer template.HTML
537− Version string
538− }{
539− Title: title,
540− Message: message,
541− ProxyPrefix: p.ProxyPrefix,
542− StatusCode: code,
543− Redirect: redirectURL,
544− Footer: template.HTML(p.Footer),
545− Version: VERSION,
546− }
547−
548− if err := p.templates.ExecuteTemplate(rw, "error.html", t); err != nil {
549− logger.Printf("Error rendering error.html template: %v", err)
550− http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
551− }
536+ p.errorPage.Render(rw, code, redirectURL, appError, messages...)
552537}
553538
554539// IsAllowedRequest is used to check if auth should be skipped for this request
@@ -593,7 +578,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
593578 err := p.ClearSessionCookie(rw, req)
594579 if err != nil {
595580 logger.Printf("Error clearing session cookie: %v", err)
596− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
581+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
597582 return
598583 }
599584 rw.WriteHeader(code)
@@ -601,7 +586,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
601586 redirectURL, err := p.getAppRedirect(req)
602587 if err != nil {
603588 logger.Errorf("Error obtaining redirect: %v", err)
604− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
589+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
605590 return
606591 }
607592
@@ -634,7 +619,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
634619 err = p.templates.ExecuteTemplate(rw, "sign_in.html", t)
635620 if err != nil {
636621 logger.Printf("Error rendering sign_in.html template: %v", err)
637− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
622+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
638623 }
639624}
640625
@@ -662,7 +647,7 @@ func (p *OAuthProxy) SignIn(rw http.ResponseWriter, req *http.Request) {
662647 redirect, err := p.getAppRedirect(req)
663648 if err != nil {
664649 logger.Errorf("Error obtaining redirect: %v", err)
665− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
650+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
666651 return
667652 }
668653
@@ -672,7 +657,7 @@ func (p *OAuthProxy) SignIn(rw http.ResponseWriter, req *http.Request) {
672657 err = p.SaveSession(rw, req, session)
673658 if err != nil {
674659 logger.Printf("Error saving session: %v", err)
675− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
660+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
676661 return
677662 }
678663 http.Redirect(rw, req, redirect, http.StatusFound)
@@ -711,7 +696,7 @@ func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) {
711696 err = json.NewEncoder(rw).Encode(userInfo)
712697 if err != nil {
713698 logger.Printf("Error encoding user info: %v", err)
714− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
699+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
715700 }
716701}
717702
@@ -720,13 +705,13 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
720705 redirect, err := p.getAppRedirect(req)
721706 if err != nil {
722707 logger.Errorf("Error obtaining redirect: %v", err)
723− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
708+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
724709 return
725710 }
726711 err = p.ClearSessionCookie(rw, req)
727712 if err != nil {
728713 logger.Errorf("Error clearing session cookie: %v", err)
729− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
714+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
730715 return
731716 }
732717 http.Redirect(rw, req, redirect, http.StatusFound)
@@ -738,14 +723,14 @@ func (p *OAuthProxy) OAuthStart(rw http.ResponseWriter, req *http.Request) {
738723 nonce, err := encryption.Nonce()
739724 if err != nil {
740725 logger.Errorf("Error obtaining nonce: %v", err)
741− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
726+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
742727 return
743728 }
744729 p.SetCSRFCookie(rw, req, nonce)
745730 redirect, err := p.getAppRedirect(req)
746731 if err != nil {
747732 logger.Errorf("Error obtaining redirect: %v", err)
748− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
733+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
749734 return
750735 }
751736 redirectURI := p.getOAuthRedirectURI(req)
@@ -761,34 +746,36 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
761746 err := req.ParseForm()
762747 if err != nil {
763748 logger.Errorf("Error while parsing OAuth2 callback: %v", err)
764− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
749+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
765750 return
766751 }
767752 errorString := req.Form.Get("error")
768753 if errorString != "" {
769754 logger.Errorf("Error while parsing OAuth2 callback: %s", errorString)
770− p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", errorString)
755+ message := fmt.Sprintf("Login Failed: The upstream identity provider returned an error: %s", errorString)
756+ // Set the debug message and override the non debug message to be the same for this case
757+ p.ErrorPage(rw, req, http.StatusForbidden, message, message)
771758 return
772759 }
773760
774761 session, err := p.redeemCode(req)
775762 if err != nil {
776763 logger.Errorf("Error redeeming code during OAuth2 callback: %v", err)
777− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
764+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
778765 return
779766 }
780767
781768 err = p.enrichSessionState(req.Context(), session)
782769 if err != nil {
783770 logger.Errorf("Error creating session during OAuth2 callback: %v", err)
784− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
771+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
785772 return
786773 }
787774
788775 state := strings.SplitN(req.Form.Get("state"), ":", 2)
789776 if len(state) != 2 {
790777 logger.Error("Error while parsing OAuth2 state: invalid length")
791− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", "Invalid State")
778+ p.ErrorPage(rw, req, http.StatusInternalServerError, "State paremeter did not have expected length", "Login Failed: Invalid State after login.")
792779 return
793780 }
794781 nonce := state[0]
@@ -796,13 +783,13 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
796783 c, err := req.Cookie(p.CSRFCookieName)
797784 if err != nil {
798785 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unable to obtain CSRF cookie")
799− p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", err.Error())
786+ p.ErrorPage(rw, req, http.StatusForbidden, err.Error(), "Login Failed: Unable to find a valid CSRF token. Please try again.")
800787 return
801788 }
802789 p.ClearCSRFCookie(rw, req)
803790 if c.Value != nonce {
804791 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: CSRF token mismatch, potential attack")
805− p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", "CSRF Failed")
792+ p.ErrorPage(rw, req, http.StatusForbidden, "CSRF token mismatch, potential attack", "Login Failed: Unable to find a valid CSRF token. Please try again.")
806793 return
807794 }
808795
@@ -820,13 +807,13 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
820807 err := p.SaveSession(rw, req, session)
821808 if err != nil {
822809 logger.Errorf("Error saving session state for %s: %v", remoteAddr, err)
823− p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
810+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
824811 return
825812 }
826813 http.Redirect(rw, req, redirect, http.StatusFound)
827814 } else {
828815 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unauthorized")
829− p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", "Invalid Account")
816+ p.ErrorPage(rw, req, http.StatusForbidden, "Invalid session: unauthorized")
830817 }
831818}
832819
@@ -908,13 +895,12 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
908895 }
909896
910897 case ErrAccessDenied:
911− p.ErrorPage(rw, req, http.StatusUnauthorized, "Permission Denied", "Unauthorized")
898+ p.ErrorPage(rw, req, http.StatusForbidden, "The session failed authorization checks")
912899
913900 default:
914901 // unknown error
915902 logger.Errorf("Unexpected internal error: %v", err)
916− p.ErrorPage(rw, req, http.StatusInternalServerError,
917− "Internal Error", "Internal Error")
903+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
918904 }
919905}
920906
oauthproxy_test.go+1−1
@@ -2815,7 +2815,7 @@ func TestProxyAllowedGroups(t *testing.T) {
28152815 test.proxy.ServeHTTP(test.rw, test.req)
28162816
28172817 if tt.expectUnauthorized {
2818− assert.Equal(t, http.StatusUnauthorized, test.rw.Code)
2818+ assert.Equal(t, http.StatusForbidden, test.rw.Code)
28192819 } else {
28202820 assert.Equal(t, http.StatusOK, test.rw.Code)
28212821 }
pkg/apis/options/app.go+7
@@ -22,6 +22,12 @@ type Templates struct {
2222 // password form if a static passwords file (htpasswd file) has been
2323 // configured.
2424 DisplayLoginForm bool `flag:"display-htpasswd-form" cfg:"display_htpasswd_form"`
25+
26+ // Debug renders detailed errors when an error page is shown.
27+ // It is not advised to use this in production as errors may contain sensitive
28+ // information.
29+ // Use only for diagnosing backend errors.
30+ Debug bool `flag:"show-debug-on-error" cfg:"show-debug-on-error"`
2531}
2632
2733func templatesFlagSet() *pflag.FlagSet {
@@ -31,6 +37,7 @@ func templatesFlagSet() *pflag.FlagSet {
3137 flagSet.String("banner", "", "custom banner string. Use \"-\" to disable default banner.")
3238 flagSet.String("footer", "", "custom footer string. Use \"-\" to disable default footer.")
3339 flagSet.Bool("display-htpasswd-form", true, "display username / password login form if an htpasswd file is provided")
40+ flagSet.Bool("show-debug-on-error", false, "show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production)")
3441
3542 return flagSet
3643}
pkg/app/error_page.gonew file+97
@@ -0,0 +1,97 @@
1+package app
2+
3+import (
4+ "fmt"
5+ "html/template"
6+ "net/http"
7+
8+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
9+)
10+
11+// errorMessages are default error messages for each of the the different
12+// http status codes expected to be rendered in the error page.
13+var errorMessages = map[int]string{
14+ http.StatusInternalServerError: "Oops! Something went wrong. For more information contact your server administrator.",
15+ http.StatusNotFound: "We could not find the resource you were looking for.",
16+ http.StatusForbidden: "You do not have permission to access this resource.",
17+ http.StatusUnauthorized: "You need to be logged in to access this resource.",
18+}
19+
20+// ErrorPage is used to render error pages.
21+type ErrorPage struct {
22+ // Template is the error page HTML template.
23+ Template *template.Template
24+
25+ // ProxyPrefix is the prefix under which OAuth2 Proxy pages are served.
26+ ProxyPrefix string
27+
28+ // Footer is the footer to be displayed at the bottom of the page.
29+ // If not set, a default footer will be used.
30+ Footer string
31+
32+ // Version is the OAuth2 Proxy version to be used in the default footer.
33+ Version string
34+
35+ // Debug determines whether errors pages should be rendered with detailed
36+ // errors.
37+ Debug bool
38+}
39+
40+// Render writes an error page to the given response writer.
41+// It uses the passed redirectURL to give users the option to go back to where
42+// they originally came from or try signing in again.
43+func (e *ErrorPage) Render(rw http.ResponseWriter, status int, redirectURL string, appError string, messages ...interface{}) {
44+ rw.WriteHeader(status)
45+
46+ // We allow unescaped template.HTML since it is user configured options
47+ /* #nosec G203 */
48+ data := struct {
49+ Title string
50+ Message string
51+ ProxyPrefix string
52+ StatusCode int
53+ Redirect string
54+ Footer template.HTML
55+ Version string
56+ }{
57+ Title: http.StatusText(status),
58+ Message: e.getMessage(status, appError, messages...),
59+ ProxyPrefix: e.ProxyPrefix,
60+ StatusCode: status,
61+ Redirect: redirectURL,
62+ Footer: template.HTML(e.Footer),
63+ Version: e.Version,
64+ }
65+
66+ if err := e.Template.Execute(rw, data); err != nil {
67+ logger.Printf("Error rendering error template: %v", err)
68+ http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
69+ }
70+}
71+
72+// ProxyErrorHandler is used by the upstream ReverseProxy to render error pages
73+// when there are issues with upstream servers.
74+// It is expected to always render a bad gateway error.
75+func (e *ErrorPage) ProxyErrorHandler(rw http.ResponseWriter, req *http.Request, proxyErr error) {
76+ logger.Errorf("Error proxying to upstream server: %v", proxyErr)
77+ e.Render(rw, http.StatusBadGateway, "", proxyErr.Error(), "There was a problem connecting to the upstream server.")
78+}
79+
80+// getMessage creates the message for the template parameters.
81+// If the ErrorPage.Debug is enabled, the application error takes precedence.
82+// Otherwise, any messages will be used.
83+// The first message is expected to be a format string.
84+// If no messages are supplied, a default error message will be used.
85+func (e *ErrorPage) getMessage(status int, appError string, messages ...interface{}) string {
86+ if e.Debug {
87+ return appError
88+ }
89+ if len(messages) > 0 {
90+ format := fmt.Sprintf("%v", messages[0])
91+ return fmt.Sprintf(format, messages[1:]...)
92+ }
93+ if msg, ok := errorMessages[status]; ok {
94+ return msg
95+ }
96+ return "Unknown error"
97+}
pkg/app/error_page_test.gonew file+101
@@ -0,0 +1,101 @@
1+package app
2+
3+import (
4+ "errors"
5+ "html/template"
6+ "io/ioutil"
7+ "net/http/httptest"
8+
9+ . "github.com/onsi/ginkgo"
10+ . "github.com/onsi/gomega"
11+)
12+
13+var _ = Describe("Error Page", func() {
14+ var errorPage *ErrorPage
15+
16+ BeforeEach(func() {
17+ tmpl, err := template.New("").Parse("{{.Title}} {{.Message}} {{.ProxyPrefix}} {{.StatusCode}} {{.Redirect}} {{.Footer}} {{.Version}}")
18+ Expect(err).ToNot(HaveOccurred())
19+
20+ errorPage = &ErrorPage{
21+ Template: tmpl,
22+ ProxyPrefix: "/prefix/",
23+ Footer: "Custom Footer Text",
24+ Version: "v0.0.0-test",
25+ }
26+ })
27+
28+ Context("Render", func() {
29+ It("Writes the template to the response writer", func() {
30+ recorder := httptest.NewRecorder()
31+ errorPage.Render(recorder, 403, "/redirect", "Access Denied")
32+
33+ body, err := ioutil.ReadAll(recorder.Result().Body)
34+ Expect(err).ToNot(HaveOccurred())
35+ Expect(string(body)).To(Equal("Forbidden You do not have permission to access this resource. /prefix/ 403 /redirect Custom Footer Text v0.0.0-test"))
36+ })
37+
38+ It("With a different code, uses the stock message for the correct code", func() {
39+ recorder := httptest.NewRecorder()
40+ errorPage.Render(recorder, 500, "/redirect", "Access Denied")
41+
42+ body, err := ioutil.ReadAll(recorder.Result().Body)
43+ Expect(err).ToNot(HaveOccurred())
44+ Expect(string(body)).To(Equal("Internal Server Error Oops! Something went wrong. For more information contact your server administrator. /prefix/ 500 /redirect Custom Footer Text v0.0.0-test"))
45+ })
46+
47+ It("With a message override, uses the message", func() {
48+ recorder := httptest.NewRecorder()
49+ errorPage.Render(recorder, 403, "/redirect", "Access Denied", "An extra message: %s", "with more context.")
50+
51+ body, err := ioutil.ReadAll(recorder.Result().Body)
52+ Expect(err).ToNot(HaveOccurred())
53+ Expect(string(body)).To(Equal("Forbidden An extra message: with more context. /prefix/ 403 /redirect Custom Footer Text v0.0.0-test"))
54+ })
55+ })
56+
57+ Context("ProxyErrorHandler", func() {
58+ It("Writes a bad gateway error the response writer", func() {
59+ req := httptest.NewRequest("", "/bad-gateway", nil)
60+ recorder := httptest.NewRecorder()
61+ errorPage.ProxyErrorHandler(recorder, req, errors.New("some upstream error"))
62+
63+ body, err := ioutil.ReadAll(recorder.Result().Body)
64+ Expect(err).ToNot(HaveOccurred())
65+ Expect(string(body)).To(Equal("Bad Gateway There was a problem connecting to the upstream server. /prefix/ 502 Custom Footer Text v0.0.0-test"))
66+ })
67+ })
68+
69+ Context("With Debug enabled", func() {
70+ BeforeEach(func() {
71+ tmpl, err := template.New("").Parse("{{.Message}}")
72+ Expect(err).ToNot(HaveOccurred())
73+
74+ errorPage.Template = tmpl
75+ errorPage.Debug = true
76+ })
77+
78+ Context("Render", func() {
79+ It("Writes the detailed error in place of the message", func() {
80+ recorder := httptest.NewRecorder()
81+ errorPage.Render(recorder, 403, "/redirect", "Debug error")
82+
83+ body, err := ioutil.ReadAll(recorder.Result().Body)
84+ Expect(err).ToNot(HaveOccurred())
85+ Expect(string(body)).To(Equal("Debug error"))
86+ })
87+ })
88+
89+ Context("ProxyErrorHandler", func() {
90+ It("Writes a bad gateway error the response writer", func() {
91+ req := httptest.NewRequest("", "/bad-gateway", nil)
92+ recorder := httptest.NewRecorder()
93+ errorPage.ProxyErrorHandler(recorder, req, errors.New("some upstream error"))
94+
95+ body, err := ioutil.ReadAll(recorder.Result().Body)
96+ Expect(err).ToNot(HaveOccurred())
97+ Expect(string(body)).To(Equal("some upstream error"))
98+ })
99+ })
100+ })
101+})
pkg/app/templates.go+2
@@ -79,6 +79,7 @@ const (
7979 </div>
8080 {{ end }}
8181
82+ {{ if .Redirect }}
8283 <hr>
8384
8485 <div class="columns">
@@ -94,6 +95,7 @@ const (
9495 </form>
9596 </div>
9697 </div>
98+ {{ end }}
9799
98100 </div>
99101 </section>
pkg/upstream/proxy.go−22
@@ -2,7 +2,6 @@ package upstream
22
33import (
44 "fmt"
5− "html/template"
65 "net/http"
76 "net/url"
87
@@ -71,24 +70,3 @@ func (m *multiUpstreamProxy) registerHTTPUpstreamProxy(upstream options.Upstream
7170 logger.Printf("mapping path %q => upstream %q", upstream.Path, upstream.URI)
7271 m.serveMux.Handle(upstream.Path, newHTTPUpstreamProxy(upstream, u, sigData, errorHandler))
7372}
74−
75−// NewProxyErrorHandler creates a ProxyErrorHandler using the template given.
76−func NewProxyErrorHandler(errorTemplate *template.Template, proxyPrefix string) ProxyErrorHandler {
77− return func(rw http.ResponseWriter, req *http.Request, proxyErr error) {
78− logger.Errorf("Error proxying to upstream server: %v", proxyErr)
79− rw.WriteHeader(http.StatusBadGateway)
80− data := struct {
81− Title string
82− Message string
83− ProxyPrefix string
84− }{
85− Title: "Bad Gateway",
86− Message: "Error proxying to upstream server",
87− ProxyPrefix: proxyPrefix,
88− }
89− err := errorTemplate.Execute(rw, data)
90− if err != nil {
91− http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
92− }
93− }
94−}
pkg/upstream/proxy_test.go+6−5
@@ -4,7 +4,6 @@ import (
44 "crypto"
55 "encoding/json"
66 "fmt"
7− "html/template"
87 "net/http"
98 "net/http/httptest"
109
@@ -20,9 +19,10 @@ var _ = Describe("Proxy Suite", func() {
2019 BeforeEach(func() {
2120 sigData := &options.SignatureData{Hash: crypto.SHA256, Key: "secret"}
2221
23− tmpl, err := template.New("").Parse("{{ .Title }}\n{{ .Message }}\n{{ .ProxyPrefix }}")
24− Expect(err).ToNot(HaveOccurred())
25− errorHandler := NewProxyErrorHandler(tmpl, "prefix")
22+ errorHandler := func(rw http.ResponseWriter, _ *http.Request, _ error) {
23+ rw.WriteHeader(502)
24+ rw.Write([]byte("Proxy Error"))
25+ }
2626
2727 ok := http.StatusOK
2828
@@ -56,6 +56,7 @@ var _ = Describe("Proxy Suite", func() {
5656 },
5757 }
5858
59+ var err error
5960 upstreamServer, err = NewProxy(upstreams, sigData, errorHandler)
6061 Expect(err).ToNot(HaveOccurred())
6162 })
@@ -143,7 +144,7 @@ var _ = Describe("Proxy Suite", func() {
143144 gapUpstream: {"bad-http-backend"},
144145 },
145146 // This tests the error handler
146− raw: "Bad Gateway\nError proxying to upstream server\nprefix",
147+ raw: "Proxy Error",
147148 },
148149 }),
149150 Entry("with a request to the to an unregistered path", &proxyTableInput{