git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge pull request #1028 from oauth2-proxy/templates

Refactor templates, update theme and provide styled error pages

commit9cdcd2b2d45726b6ae4485634624c54e0d8183a8 authorJoel Speed <Joel.speed@hotmail.co.uk> dateFri 12 Feb 2021, 21:02 (6 years ago) parent465789b881f43f
9 files changed+589−303
CHANGELOG.md+1 oauthproxy.go+58−35 pkg/apis/options/app.go+43 pkg/apis/options/options.go+14−19 pkg/app/app_suite_test.go+17 pkg/app/templates.go+257 pkg/app/templates_test.go+199 templates.go−187 templates_test.go−62
CHANGELOG.md+1
@@ -8,6 +8,7 @@
88
99## Changes since v7.0.1
1010
11+- [#1028](https://github.com/oauth2-proxy/oauth2-proxy/pull/1028) Refactor templates, update theme and provide styled error pages (@JoelSpeed)
1112- [#1039](https://github.com/oauth2-proxy/oauth2-proxy/pull/1039) Ensure errors in tests are logged to the GinkgoWriter (@JoelSpeed)
1213
1314# V7.0.1
oauthproxy.go+58−35
@@ -18,6 +18,7 @@ import (
1818 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
1919 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
2020 sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
21+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/app"
2122 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/basic"
2223 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/cookies"
2324 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
@@ -116,7 +117,10 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
116117 return nil, fmt.Errorf("error initialising session store: %v", err)
117118 }
118119
119− templates := loadTemplates(opts.CustomTemplatesDir)
120+ templates, err := app.LoadTemplates(opts.Templates.Path)
121+ if err != nil {
122+ return nil, fmt.Errorf("error loading templates: %v", err)
123+ }
120124 proxyErrorHandler := upstream.NewProxyErrorHandler(templates.Lookup("error.html"), opts.ProxyPrefix)
121125 upstreamProxy, err := upstream.NewProxy(opts.UpstreamServers, opts.GetSignatureData(), proxyErrorHandler)
122126 if err != nil {
@@ -211,12 +215,12 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
211215 SkipProviderButton: opts.SkipProviderButton,
212216 templates: templates,
213217 trustedIPs: trustedIPs,
214− Banner: opts.Banner,
215− Footer: opts.Footer,
218+ Banner: opts.Templates.Banner,
219+ Footer: opts.Templates.Footer,
216220 SignInMessage: buildSignInMessage(opts),
217221
218222 basicAuthValidator: basicAuthValidator,
219− displayHtpasswdForm: basicAuthValidator != nil && opts.DisplayHtpasswdForm,
223+ displayHtpasswdForm: basicAuthValidator != nil && opts.Templates.DisplayLoginForm,
220224 sessionChain: sessionChain,
221225 headersChain: headersChain,
222226 preAuthChain: preAuthChain,
@@ -301,11 +305,11 @@ func buildHeadersChain(opts *options.Options) (alice.Chain, error) {
301305
302306func buildSignInMessage(opts *options.Options) string {
303307 var msg string
304− if len(opts.Banner) >= 1 {
305− if opts.Banner == "-" {
308+ if len(opts.Templates.Banner) >= 1 {
309+ if opts.Templates.Banner == "-" {
306310 msg = ""
307311 } else {
308− msg = opts.Banner
312+ msg = opts.Templates.Banner
309313 }
310314 } else if len(opts.EmailDomains) != 0 && opts.AuthenticatedEmailsFile == "" {
311315 if len(opts.EmailDomains) > 1 {
@@ -478,7 +482,7 @@ func (p *OAuthProxy) serveHTTP(rw http.ResponseWriter, req *http.Request) {
478482
479483 switch path := req.URL.Path; {
480484 case path == p.RobotsPath:
481− p.RobotsTxt(rw)
485+ p.RobotsTxt(rw, req)
482486 case p.IsAllowedRequest(req):
483487 p.SkipAuthProxy(rw, req)
484488 case path == p.SignInPath:
@@ -499,30 +503,49 @@ func (p *OAuthProxy) serveHTTP(rw http.ResponseWriter, req *http.Request) {
499503}
500504
501505// RobotsTxt disallows scraping pages from the OAuthProxy
502−func (p *OAuthProxy) RobotsTxt(rw http.ResponseWriter) {
506+func (p *OAuthProxy) RobotsTxt(rw http.ResponseWriter, req *http.Request) {
503507 _, err := fmt.Fprintf(rw, "User-agent: *\nDisallow: /")
504508 if err != nil {
505509 logger.Printf("Error writing robots.txt: %v", err)
506− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
510+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
507511 return
508512 }
509513 rw.WriteHeader(http.StatusOK)
510514}
511515
512516// ErrorPage writes an error response
513−func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, code int, title string, message string) {
517+func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, req *http.Request, code int, title string, message string) {
518+ redirectURL, err := p.getAppRedirect(req)
519+ if err != nil {
520+ logger.Errorf("Error obtaining redirect: %v", err)
521+ }
522+ if redirectURL == p.SignInPath || redirectURL == "" {
523+ redirectURL = "/"
524+ }
525+
514526 rw.WriteHeader(code)
527+
528+ // We allow unescaped template.HTML since it is user configured options
529+ /* #nosec G203 */
515530 t := struct {
516531 Title string
517532 Message string
518533 ProxyPrefix string
534+ StatusCode int
535+ Redirect string
536+ Footer template.HTML
537+ Version string
519538 }{
520− Title: fmt.Sprintf("%d %s", code, title),
539+ Title: title,
521540 Message: message,
522541 ProxyPrefix: p.ProxyPrefix,
542+ StatusCode: code,
543+ Redirect: redirectURL,
544+ Footer: template.HTML(p.Footer),
545+ Version: VERSION,
523546 }
524− err := p.templates.ExecuteTemplate(rw, "error.html", t)
525− if err != nil {
547+
548+ if err := p.templates.ExecuteTemplate(rw, "error.html", t); err != nil {
526549 logger.Printf("Error rendering error.html template: %v", err)
527550 http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
528551 }
@@ -570,7 +593,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
570593 err := p.ClearSessionCookie(rw, req)
571594 if err != nil {
572595 logger.Printf("Error clearing session cookie: %v", err)
573− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
596+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
574597 return
575598 }
576599 rw.WriteHeader(code)
@@ -578,7 +601,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
578601 redirectURL, err := p.getAppRedirect(req)
579602 if err != nil {
580603 logger.Errorf("Error obtaining redirect: %v", err)
581− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
604+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
582605 return
583606 }
584607
@@ -611,7 +634,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
611634 err = p.templates.ExecuteTemplate(rw, "sign_in.html", t)
612635 if err != nil {
613636 logger.Printf("Error rendering sign_in.html template: %v", err)
614− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
637+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
615638 }
616639}
617640
@@ -639,7 +662,7 @@ func (p *OAuthProxy) SignIn(rw http.ResponseWriter, req *http.Request) {
639662 redirect, err := p.getAppRedirect(req)
640663 if err != nil {
641664 logger.Errorf("Error obtaining redirect: %v", err)
642− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
665+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
643666 return
644667 }
645668
@@ -649,7 +672,7 @@ func (p *OAuthProxy) SignIn(rw http.ResponseWriter, req *http.Request) {
649672 err = p.SaveSession(rw, req, session)
650673 if err != nil {
651674 logger.Printf("Error saving session: %v", err)
652− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
675+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
653676 return
654677 }
655678 http.Redirect(rw, req, redirect, http.StatusFound)
@@ -688,7 +711,7 @@ func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) {
688711 err = json.NewEncoder(rw).Encode(userInfo)
689712 if err != nil {
690713 logger.Printf("Error encoding user info: %v", err)
691− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
714+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
692715 }
693716}
694717
@@ -697,13 +720,13 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
697720 redirect, err := p.getAppRedirect(req)
698721 if err != nil {
699722 logger.Errorf("Error obtaining redirect: %v", err)
700− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
723+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
701724 return
702725 }
703726 err = p.ClearSessionCookie(rw, req)
704727 if err != nil {
705728 logger.Errorf("Error clearing session cookie: %v", err)
706− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
729+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
707730 return
708731 }
709732 http.Redirect(rw, req, redirect, http.StatusFound)
@@ -715,14 +738,14 @@ func (p *OAuthProxy) OAuthStart(rw http.ResponseWriter, req *http.Request) {
715738 nonce, err := encryption.Nonce()
716739 if err != nil {
717740 logger.Errorf("Error obtaining nonce: %v", err)
718− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
741+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
719742 return
720743 }
721744 p.SetCSRFCookie(rw, req, nonce)
722745 redirect, err := p.getAppRedirect(req)
723746 if err != nil {
724747 logger.Errorf("Error obtaining redirect: %v", err)
725− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
748+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
726749 return
727750 }
728751 redirectURI := p.getOAuthRedirectURI(req)
@@ -738,34 +761,34 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
738761 err := req.ParseForm()
739762 if err != nil {
740763 logger.Errorf("Error while parsing OAuth2 callback: %v", err)
741− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
764+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
742765 return
743766 }
744767 errorString := req.Form.Get("error")
745768 if errorString != "" {
746769 logger.Errorf("Error while parsing OAuth2 callback: %s", errorString)
747− p.ErrorPage(rw, http.StatusForbidden, "Permission Denied", errorString)
770+ p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", errorString)
748771 return
749772 }
750773
751774 session, err := p.redeemCode(req)
752775 if err != nil {
753776 logger.Errorf("Error redeeming code during OAuth2 callback: %v", err)
754− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
777+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
755778 return
756779 }
757780
758781 err = p.enrichSessionState(req.Context(), session)
759782 if err != nil {
760783 logger.Errorf("Error creating session during OAuth2 callback: %v", err)
761− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
784+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
762785 return
763786 }
764787
765788 state := strings.SplitN(req.Form.Get("state"), ":", 2)
766789 if len(state) != 2 {
767790 logger.Error("Error while parsing OAuth2 state: invalid length")
768− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", "Invalid State")
791+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", "Invalid State")
769792 return
770793 }
771794 nonce := state[0]
@@ -773,13 +796,13 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
773796 c, err := req.Cookie(p.CSRFCookieName)
774797 if err != nil {
775798 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unable to obtain CSRF cookie")
776− p.ErrorPage(rw, http.StatusForbidden, "Permission Denied", err.Error())
799+ p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", err.Error())
777800 return
778801 }
779802 p.ClearCSRFCookie(rw, req)
780803 if c.Value != nonce {
781804 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: CSRF token mismatch, potential attack")
782− p.ErrorPage(rw, http.StatusForbidden, "Permission Denied", "CSRF Failed")
805+ p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", "CSRF Failed")
783806 return
784807 }
785808
@@ -797,13 +820,13 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
797820 err := p.SaveSession(rw, req, session)
798821 if err != nil {
799822 logger.Errorf("Error saving session state for %s: %v", remoteAddr, err)
800− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
823+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
801824 return
802825 }
803826 http.Redirect(rw, req, redirect, http.StatusFound)
804827 } else {
805828 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unauthorized")
806− p.ErrorPage(rw, http.StatusForbidden, "Permission Denied", "Invalid Account")
829+ p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", "Invalid Account")
807830 }
808831}
809832
@@ -885,12 +908,12 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
885908 }
886909
887910 case ErrAccessDenied:
888− p.ErrorPage(rw, http.StatusUnauthorized, "Permission Denied", "Unauthorized")
911+ p.ErrorPage(rw, req, http.StatusUnauthorized, "Permission Denied", "Unauthorized")
889912
890913 default:
891914 // unknown error
892915 logger.Errorf("Unexpected internal error: %v", err)
893− p.ErrorPage(rw, http.StatusInternalServerError,
916+ p.ErrorPage(rw, req, http.StatusInternalServerError,
894917 "Internal Error", "Internal Error")
895918 }
896919}
pkg/apis/options/app.gonew file+43
@@ -0,0 +1,43 @@
1+package options
2+
3+import "github.com/spf13/pflag"
4+
5+// Templates includes options for configuring the sign in and error pages
6+// appearance.
7+type Templates struct {
8+ // Path is the path to a folder containing a sign_in.html and an error.html
9+ // template.
10+ // These files will be used instead of the default templates if present.
11+ // If either file is missing, the default will be used instead.
12+ Path string `flag:"custom-templates-dir" cfg:"custom_templates_dir"`
13+
14+ // Banner overides the default sign_in page banner text. If unspecified,
15+ // the message will give users a list of allowed email domains.
16+ Banner string `flag:"banner" cfg:"banner"`
17+
18+ // Footer overrides the default sign_in page footer text.
19+ Footer string `flag:"footer" cfg:"footer"`
20+
21+ // DisplayLoginForm determines whether the sign_in page should render a
22+ // password form if a static passwords file (htpasswd file) has been
23+ // configured.
24+ DisplayLoginForm bool `flag:"display-htpasswd-form" cfg:"display_htpasswd_form"`
25+}
26+
27+func templatesFlagSet() *pflag.FlagSet {
28+ flagSet := pflag.NewFlagSet("templates", pflag.ExitOnError)
29+
30+ flagSet.String("custom-templates-dir", "", "path to custom html templates")
31+ flagSet.String("banner", "", "custom banner string. Use \"-\" to disable default banner.")
32+ flagSet.String("footer", "", "custom footer string. Use \"-\" to disable default footer.")
33+ flagSet.Bool("display-htpasswd-form", true, "display username / password login form if an htpasswd file is provided")
34+
35+ return flagSet
36+}
37+
38+// templatesDefaults creates a Templates and populates it with any default values
39+func templatesDefaults() Templates {
40+ return Templates{
41+ DisplayLoginForm: true,
42+ }
43+}
pkg/apis/options/options.go+14−19
@@ -53,14 +53,11 @@ type Options struct {
5353 GoogleAdminEmail string `flag:"google-admin-email" cfg:"google_admin_email"`
5454 GoogleServiceAccountJSON string `flag:"google-service-account-json" cfg:"google_service_account_json"`
5555 HtpasswdFile string `flag:"htpasswd-file" cfg:"htpasswd_file"`
56− DisplayHtpasswdForm bool `flag:"display-htpasswd-form" cfg:"display_htpasswd_form"`
57− CustomTemplatesDir string `flag:"custom-templates-dir" cfg:"custom_templates_dir"`
58− Banner string `flag:"banner" cfg:"banner"`
59− Footer string `flag:"footer" cfg:"footer"`
6056
61− Cookie Cookie `cfg:",squash"`
62− Session SessionOptions `cfg:",squash"`
63− Logging Logging `cfg:",squash"`
57+ Cookie Cookie `cfg:",squash"`
58+ Session SessionOptions `cfg:",squash"`
59+ Logging Logging `cfg:",squash"`
60+ Templates Templates `cfg:",squash"`
6461
6562 // Not used in the legacy config, name not allowed to match an external key (upstreams)
6663 // TODO(JoelSpeed): Rename when legacy config is removed
@@ -135,16 +132,17 @@ func (o *Options) SetRealClientIPParser(s ipapi.RealClientIPParser) { o.realClie
135132// NewOptions constructs a new Options with defaulted values
136133func NewOptions() *Options {
137134 return &Options{
138− ProxyPrefix: "/oauth2",
139− ProviderType: "google",
140− PingPath: "/ping",
141− HTTPAddress: "127.0.0.1:4180",
142− HTTPSAddress: ":443",
143− RealClientIPHeader: "X-Real-IP",
144− ForceHTTPS: false,
145− DisplayHtpasswdForm: true,
135+ ProxyPrefix: "/oauth2",
136+ ProviderType: "google",
137+ PingPath: "/ping",
138+ HTTPAddress: "127.0.0.1:4180",
139+ HTTPSAddress: ":443",
140+ RealClientIPHeader: "X-Real-IP",
141+ ForceHTTPS: false,
142+
146143 Cookie: cookieDefaults(),
147144 Session: sessionOptionsDefaults(),
145+ Templates: templatesDefaults(),
148146 AzureTenant: "common",
149147 SkipAuthPreflight: false,
150148 Prompt: "", // Change to "login" when ApprovalPrompt officially deprecated
@@ -200,10 +198,6 @@ func NewFlagSet() *pflag.FlagSet {
200198 flagSet.String("client-secret-file", "", "the file with OAuth Client Secret")
201199 flagSet.String("authenticated-emails-file", "", "authenticate against emails via file (one per line)")
202200 flagSet.String("htpasswd-file", "", "additionally authenticate against a htpasswd file. Entries must be created with \"htpasswd -B\" for bcrypt encryption")
203− flagSet.Bool("display-htpasswd-form", true, "display username / password login form if an htpasswd file is provided")
204− flagSet.String("custom-templates-dir", "", "path to custom html templates")
205− flagSet.String("banner", "", "custom banner string. Use \"-\" to disable default banner.")
206− flagSet.String("footer", "", "custom footer string. Use \"-\" to disable default footer.")
207201 flagSet.String("proxy-prefix", "/oauth2", "the url root path that this proxy should be nested under (e.g. /<oauth2>/sign_in)")
208202 flagSet.String("ping-path", "/ping", "the ping endpoint that can be used for basic health checks")
209203 flagSet.String("ping-user-agent", "", "special User-Agent that will be used for basic health checks")
@@ -251,6 +245,7 @@ func NewFlagSet() *pflag.FlagSet {
251245
252246 flagSet.AddFlagSet(cookieFlagSet())
253247 flagSet.AddFlagSet(loggingFlagSet())
248+ flagSet.AddFlagSet(templatesFlagSet())
254249
255250 return flagSet
256251}
pkg/app/app_suite_test.gonew file+17
@@ -0,0 +1,17 @@
1+package app
2+
3+import (
4+ "testing"
5+
6+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
7+ . "github.com/onsi/ginkgo"
8+ . "github.com/onsi/gomega"
9+)
10+
11+func TestOptionsSuite(t *testing.T) {
12+ logger.SetOutput(GinkgoWriter)
13+ logger.SetErrOutput(GinkgoWriter)
14+
15+ RegisterFailHandler(Fail)
16+ RunSpecs(t, "App Suite")
17+}
pkg/app/templates.gonew file+257
@@ -0,0 +1,257 @@
1+package app
2+
3+import (
4+ "fmt"
5+ "html/template"
6+ "os"
7+ "path/filepath"
8+ "strings"
9+
10+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
11+)
12+
13+const (
14+ errorTemplateName = "error.html"
15+ signInTemplateName = "sign_in.html"
16+
17+ defaultErrorTemplate = `{{define "error.html"}}
18+<!DOCTYPE html>
19+<html lang="en" charset="utf-8">
20+<head>
21+ <meta charset="utf-8">
22+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
23+ <title>{{.StatusCode}} {{.Title}}</title>
24+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
25+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css">
26+
27+ <script type="text/javascript">
28+ document.addEventListener('DOMContentLoaded', function() {
29+ let cardToggles = document.getElementsByClassName('card-toggle');
30+ for (let i = 0; i < cardToggles.length; i++) {
31+ cardToggles[i].addEventListener('click', e => {
32+ e.currentTarget.parentElement.parentElement.childNodes[3].classList.toggle('is-hidden');
33+ });
34+ }
35+ });
36+ </script>
37+
38+ <style>
39+ body {
40+ height: 100vh;
41+ }
42+ .error-box {
43+ margin: 1.25rem auto;
44+ max-width: 600px;
45+ }
46+ .status-code {
47+ font-size: 12rem;
48+ font-weight: 600;
49+ }
50+ #more-info.card {
51+ border: 1px solid #f0f0f0;
52+ }
53+ footer a {
54+ text-decoration: underline;
55+ }
56+ </style>
57+</head>
58+<body class="has-background-light">
59+ <section class="section">
60+ <div class="box block error-box has-text-centered">
61+ <div class="status-code">{{.StatusCode}}</div>
62+ <div class="block">
63+ <h1 class="subtitle is-1">{{.Title}}</h1>
64+ </div>
65+
66+ {{ if .Message }}
67+ <div id="more-info" class="block card is-fullwidth is-shadowless">
68+ <header class="card-header is-shadowless">
69+ <p class="card-header-title">More Info</p>
70+ <a class="card-header-icon card-toggle">
71+ <i class="fa fa-angle-down"></i>
72+ </a>
73+ </header>
74+ <div class="card-content has-text-left is-hidden">
75+ <div class="content">
76+ {{.Message}}
77+ </div>
78+ </div>
79+ </div>
80+ {{ end }}
81+
82+ <hr>
83+
84+ <div class="columns">
85+ <div class="column">
86+ <form method="GET" action="{{.Redirect}}">
87+ <button type="submit" class="button is-danger is-fullwidth">Go back</button>
88+ </form>
89+ </div>
90+ <div class="column">
91+ <form method="GET" action="{{.ProxyPrefix}}/sign_in">
92+ <input type="hidden" name="rd" value="{{.Redirect}}">
93+ <button type="submit" class="button is-primary is-fullwidth">Sign in</button>
94+ </form>
95+ </div>
96+ </div>
97+
98+ </div>
99+ </section>
100+
101+ <footer class="footer has-text-grey has-background-light is-size-7">
102+ <div class="content has-text-centered">
103+ {{ if eq .Footer "-" }}
104+ {{ else if eq .Footer ""}}
105+ <p>Secured with <a href="https://github.com/oauth2-proxy/oauth2-proxy#oauth2_proxy" class="has-text-grey">OAuth2 Proxy</a> version {{.Version}}</p>
106+ {{ else }}
107+ <p>{{.Footer}}</p>
108+ {{ end }}
109+ </div>
110+ </footer>
111+
112+ </body>
113+</html>
114+{{end}}`
115+
116+ defaultSignInTemplate = `{{define "sign_in.html"}}
117+<!DOCTYPE html>
118+<html lang="en" charset="utf-8">
119+ <head>
120+ <meta charset="utf-8">
121+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
122+ <title>Sign In</title>
123+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
124+
125+ <style>
126+ body {
127+ height: 100vh;
128+ }
129+ .sign-in-box {
130+ max-width: 400px;
131+ margin: 1.25rem auto;
132+ }
133+ footer a {
134+ text-decoration: underline;
135+ }
136+ </style>
137+
138+ <script>
139+ if (window.location.hash) {
140+ (function() {
141+ var inputs = document.getElementsByName('rd');
142+ for (var i = 0; i < inputs.length; i++) {
143+ // Add hash, but make sure it is only added once
144+ var idx = inputs[i].value.indexOf('#');
145+ if (idx >= 0) {
146+ // Remove existing hash from URL
147+ inputs[i].value = inputs[i].value.substr(0, idx);
148+ }
149+ inputs[i].value += window.location.hash;
150+ }
151+ })();
152+ }
153+ </script>
154+ </head>
155+ <body class="has-background-light">
156+ <section class="section">
157+ <div class="box block sign-in-box has-text-centered">
158+ <form method="GET" action="{{.ProxyPrefix}}/start">
159+ <input type="hidden" name="rd" value="{{.Redirect}}">
160+ {{ if .SignInMessage }}
161+ <p class="block">{{.SignInMessage}}</p>
162+ {{ end}}
163+ <button type="submit" class="button block is-primary">Sign in with {{.ProviderName}}</button>
164+ </form>
165+
166+ {{ if .CustomLogin }}
167+ <hr>
168+
169+ <form method="POST" action="{{.ProxyPrefix}}/sign_in" class="block">
170+ <input type="hidden" name="rd" value="{{.Redirect}}">
171+
172+ <div class="field">
173+ <label class="label" for="username">Username</label>
174+ <div class="control">
175+ <input class="input" type="email" placeholder="e.g. userx@example.com" name="username" id="username">
176+ </div>
177+ </div>
178+
179+ <div class="field">
180+ <label class="label" for="password">Password</label>
181+ <div class="control">
182+ <input class="input" type="password" placeholder="********" name="password" id="password">
183+ </div>
184+ </div>
185+ <button class="button is-primary">Sign in</button>
186+ {{ end }}
187+ </form>
188+ </div>
189+ </section>
190+
191+ <footer class="footer has-text-grey has-background-light is-size-7">
192+ <div class="content has-text-centered">
193+ {{ if eq .Footer "-" }}
194+ {{ else if eq .Footer ""}}
195+ <p>Secured with <a href="https://github.com/oauth2-proxy/oauth2-proxy#oauth2_proxy" class="has-text-grey">OAuth2 Proxy</a> version {{.Version}}</p>
196+ {{ else }}
197+ <p>{{.Footer}}</p>
198+ {{ end }}
199+ </div>
200+ </footer>
201+
202+ </body>
203+</html>
204+{{end}}`
205+)
206+
207+// LoadTemplates adds the Sign In and Error templates from the custom template
208+// directory, or uses the defaults if they do not exist or the custom directory
209+// is not provided.
210+func LoadTemplates(customDir string) (*template.Template, error) {
211+ t := template.New("").Funcs(template.FuncMap{
212+ "ToUpper": strings.ToUpper,
213+ "ToLower": strings.ToLower,
214+ })
215+ var err error
216+ t, err = addTemplate(t, customDir, signInTemplateName, defaultSignInTemplate)
217+ if err != nil {
218+ return nil, fmt.Errorf("could not add Sign In template: %v", err)
219+ }
220+ t, err = addTemplate(t, customDir, errorTemplateName, defaultErrorTemplate)
221+ if err != nil {
222+ return nil, fmt.Errorf("could not add Error template: %v", err)
223+ }
224+
225+ return t, nil
226+}
227+
228+// addTemplate will add the template from the custom directory if provided,
229+// else it will add the default template.
230+func addTemplate(t *template.Template, customDir, fileName, defaultTemplate string) (*template.Template, error) {
231+ filePath := filepath.Join(customDir, fileName)
232+ if customDir != "" && isFile(filePath) {
233+ t, err := t.ParseFiles(filePath)
234+ if err != nil {
235+ return nil, fmt.Errorf("failed to parse template %s: %v", filePath, err)
236+ }
237+ return t, nil
238+ }
239+ t, err := t.Parse(defaultTemplate)
240+ if err != nil {
241+ // This should not happen.
242+ // Default templates should be tested and so should never fail to parse.
243+ logger.Panic("Could not parse defaultTemplate: ", err)
244+ }
245+ return t, nil
246+}
247+
248+// isFile checks if the file exists and checks whether it is a regular file.
249+// If either of these fail then it cannot be used as a template file.
250+func isFile(fileName string) bool {
251+ info, err := os.Stat(fileName)
252+ if err != nil {
253+ logger.Errorf("Could not load file %s: %v, will use default template", fileName, err)
254+ return false
255+ }
256+ return info.Mode().IsRegular()
257+}
pkg/app/templates_test.gonew file+199
@@ -0,0 +1,199 @@
1+package app
2+
3+import (
4+ "bytes"
5+ "html/template"
6+ "io/ioutil"
7+ "os"
8+ "path/filepath"
9+
10+ . "github.com/onsi/ginkgo"
11+ . "github.com/onsi/gomega"
12+)
13+
14+var _ = Describe("Templates", func() {
15+ var customDir string
16+
17+ BeforeEach(func() {
18+ var err error
19+ customDir, err = ioutil.TempDir("", "oauth2-proxy-templates-test")
20+ Expect(err).ToNot(HaveOccurred())
21+
22+ templateHTML := `{{.TestString}} {{.TestString | ToLower}} {{.TestString | ToUpper}}`
23+ signInFile := filepath.Join(customDir, signInTemplateName)
24+ Expect(ioutil.WriteFile(signInFile, []byte(templateHTML), 0666)).To(Succeed())
25+ errorFile := filepath.Join(customDir, errorTemplateName)
26+ Expect(ioutil.WriteFile(errorFile, []byte(templateHTML), 0666)).To(Succeed())
27+ })
28+
29+ AfterEach(func() {
30+ Expect(os.RemoveAll(customDir)).To(Succeed())
31+ })
32+
33+ Context("LoadTemplates", func() {
34+ var data interface{}
35+ var t *template.Template
36+
37+ BeforeEach(func() {
38+ data = struct {
39+ // For default templates
40+ ProxyPrefix string
41+ Redirect string
42+ Footer string
43+
44+ // For default sign_in template
45+ SignInMessage string
46+ ProviderName string
47+ CustomLogin bool
48+
49+ // For default error template
50+ StatusCode int
51+ Title string
52+ Message string
53+
54+ // For custom templates
55+ TestString string
56+ }{
57+ ProxyPrefix: "<proxy-prefix>",
58+ Redirect: "<redirect>",
59+ Footer: "<footer>",
60+
61+ SignInMessage: "<sign-in-message>",
62+ ProviderName: "<provider-name>",
63+ CustomLogin: false,
64+
65+ StatusCode: 404,
66+ Title: "<title>",
67+ Message: "<message>",
68+
69+ TestString: "Testing",
70+ }
71+ })
72+
73+ Context("With no custom directory", func() {
74+ BeforeEach(func() {
75+ var err error
76+ t, err = LoadTemplates("")
77+ Expect(err).ToNot(HaveOccurred())
78+ })
79+
80+ It("Use the default sign_in page", func() {
81+ buf := bytes.NewBuffer([]byte{})
82+ Expect(t.ExecuteTemplate(buf, signInTemplateName, data)).To(Succeed())
83+ Expect(buf.String()).To(HavePrefix("\n<!DOCTYPE html>"))
84+ })
85+
86+ It("Use the default error page", func() {
87+ buf := bytes.NewBuffer([]byte{})
88+ Expect(t.ExecuteTemplate(buf, errorTemplateName, data)).To(Succeed())
89+ Expect(buf.String()).To(HavePrefix("\n<!DOCTYPE html>"))
90+ })
91+ })
92+
93+ Context("With a custom directory", func() {
94+ Context("With both templates", func() {
95+ BeforeEach(func() {
96+ var err error
97+ t, err = LoadTemplates(customDir)
98+ Expect(err).ToNot(HaveOccurred())
99+ })
100+
101+ It("Use the custom sign_in page", func() {
102+ buf := bytes.NewBuffer([]byte{})
103+ Expect(t.ExecuteTemplate(buf, signInTemplateName, data)).To(Succeed())
104+ Expect(buf.String()).To(Equal("Testing testing TESTING"))
105+ })
106+
107+ It("Use the custom error page", func() {
108+ buf := bytes.NewBuffer([]byte{})
109+ Expect(t.ExecuteTemplate(buf, errorTemplateName, data)).To(Succeed())
110+ Expect(buf.String()).To(Equal("Testing testing TESTING"))
111+ })
112+ })
113+
114+ Context("With no error template", func() {
115+ BeforeEach(func() {
116+ Expect(os.Remove(filepath.Join(customDir, errorTemplateName))).To(Succeed())
117+
118+ var err error
119+ t, err = LoadTemplates(customDir)
120+ Expect(err).ToNot(HaveOccurred())
121+ })
122+
123+ It("Use the custom sign_in page", func() {
124+ buf := bytes.NewBuffer([]byte{})
125+ Expect(t.ExecuteTemplate(buf, signInTemplateName, data)).To(Succeed())
126+ Expect(buf.String()).To(Equal("Testing testing TESTING"))
127+ })
128+
129+ It("Use the default error page", func() {
130+ buf := bytes.NewBuffer([]byte{})
131+ Expect(t.ExecuteTemplate(buf, errorTemplateName, data)).To(Succeed())
132+ Expect(buf.String()).To(HavePrefix("\n<!DOCTYPE html>"))
133+ })
134+ })
135+
136+ Context("With no sign_in template", func() {
137+ BeforeEach(func() {
138+ Expect(os.Remove(filepath.Join(customDir, signInTemplateName))).To(Succeed())
139+
140+ var err error
141+ t, err = LoadTemplates(customDir)
142+ Expect(err).ToNot(HaveOccurred())
143+ })
144+
145+ It("Use the default sign_in page", func() {
146+ buf := bytes.NewBuffer([]byte{})
147+ Expect(t.ExecuteTemplate(buf, signInTemplateName, data)).To(Succeed())
148+ Expect(buf.String()).To(HavePrefix("\n<!DOCTYPE html>"))
149+ })
150+
151+ It("Use the custom error page", func() {
152+ buf := bytes.NewBuffer([]byte{})
153+ Expect(t.ExecuteTemplate(buf, errorTemplateName, data)).To(Succeed())
154+ Expect(buf.String()).To(Equal("Testing testing TESTING"))
155+ })
156+ })
157+
158+ Context("With an invalid sign_in template", func() {
159+ BeforeEach(func() {
160+ signInFile := filepath.Join(customDir, signInTemplateName)
161+ Expect(ioutil.WriteFile(signInFile, []byte("{{"), 0666))
162+ })
163+
164+ It("Should return an error when loading templates", func() {
165+ t, err := LoadTemplates(customDir)
166+ Expect(err).To(MatchError(HavePrefix("could not add Sign In template:")))
167+ Expect(t).To(BeNil())
168+ })
169+ })
170+
171+ Context("With an invalid error template", func() {
172+ BeforeEach(func() {
173+ errorFile := filepath.Join(customDir, errorTemplateName)
174+ Expect(ioutil.WriteFile(errorFile, []byte("{{"), 0666))
175+ })
176+
177+ It("Should return an error when loading templates", func() {
178+ t, err := LoadTemplates(customDir)
179+ Expect(err).To(MatchError(HavePrefix("could not add Error template:")))
180+ Expect(t).To(BeNil())
181+ })
182+ })
183+ })
184+ })
185+
186+ Context("isFile", func() {
187+ It("with a valid file", func() {
188+ Expect(isFile(filepath.Join(customDir, signInTemplateName))).To(BeTrue())
189+ })
190+
191+ It("with a directory", func() {
192+ Expect(isFile(customDir)).To(BeFalse())
193+ })
194+
195+ It("with an invalid file", func() {
196+ Expect(isFile(filepath.Join(customDir, "does_not_exist.html"))).To(BeFalse())
197+ })
198+ })
199+})
templates.godeleted−187
@@ -1,187 +0,0 @@
1−package main
2−
3−import (
4− "html/template"
5− "path"
6− "strings"
7−
8− "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
9−)
10−
11−func loadTemplates(dir string) *template.Template {
12− if dir == "" {
13− return getTemplates()
14− }
15− logger.Printf("using custom template directory %q", dir)
16− funcMap := template.FuncMap{
17− "ToUpper": strings.ToUpper,
18− "ToLower": strings.ToLower,
19− }
20− t, err := template.New("").Funcs(funcMap).ParseFiles(path.Join(dir, "sign_in.html"), path.Join(dir, "error.html"))
21− if err != nil {
22− logger.Fatalf("failed parsing template %s", err)
23− }
24− return t
25−}
26−
27−func getTemplates() *template.Template {
28− t, err := template.New("foo").Parse(`{{define "sign_in.html"}}
29−<!DOCTYPE html>
30−<html lang="en" charset="utf-8">
31−<head>
32− <title>Sign In</title>
33− <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
34− <style>
35− body {
36− font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
37− font-size: 14px;
38− line-height: 1.42857143;
39− color: #333;
40− background: #f0f0f0;
41− }
42− .signin {
43− display:block;
44− margin:20px auto;
45− max-width:400px;
46− background: #fff;
47− border:1px solid #ccc;
48− border-radius: 10px;
49− padding: 20px;
50− }
51− .center {
52− text-align:center;
53− }
54− .btn {
55− color: #fff;
56− background-color: #428bca;
57− border: 1px solid #357ebd;
58− -webkit-border-radius: 4;
59− -moz-border-radius: 4;
60− border-radius: 4px;
61− font-size: 14px;
62− padding: 6px 12px;
63− text-decoration: none;
64− cursor: pointer;
65− }
66−
67− .btn:hover {
68− background-color: #3071a9;
69− border-color: #285e8e;
70− text-decoration: none;
71− }
72− label {
73− display: inline-block;
74− max-width: 100%;
75− margin-bottom: 5px;
76− font-weight: 700;
77− }
78− input {
79− display: block;
80− width: 100%;
81− height: 34px;
82− padding: 6px 12px;
83− font-size: 14px;
84− line-height: 1.42857143;
85− color: #555;
86− background-color: #fff;
87− background-image: none;
88− border: 1px solid #ccc;
89− border-radius: 4px;
90− -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
91− box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
92− -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
93− -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
94− transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
95− margin:0;
96− box-sizing: border-box;
97− }
98− footer {
99− display:block;
100− font-size:10px;
101− color:#aaa;
102− text-align:center;
103− margin-bottom:10px;
104− }
105− footer a {
106− display:inline-block;
107− height:25px;
108− line-height:25px;
109− color:#aaa;
110− text-decoration:underline;
111− }
112− footer a:hover {
113− color:#aaa;
114− }
115− </style>
116−</head>
117−<body>
118− <div class="signin center">
119− <form method="GET" action="{{.ProxyPrefix}}/start">
120− <input type="hidden" name="rd" value="{{.Redirect}}">
121− {{ if .SignInMessage }}
122− <p>{{.SignInMessage}}</p>
123− {{ end}}
124− <button type="submit" class="btn">Sign in with {{.ProviderName}}</button><br/>
125− </form>
126− </div>
127−
128− {{ if .CustomLogin }}
129− <div class="signin">
130− <form method="POST" action="{{.ProxyPrefix}}/sign_in">
131− <input type="hidden" name="rd" value="{{.Redirect}}">
132− <label for="username">Username:</label><input type="text" name="username" id="username" size="10"><br/>
133− <label for="password">Password:</label><input type="password" name="password" id="password" size="10"><br/>
134− <button type="submit" class="btn">Sign In</button>
135− </form>
136− </div>
137− {{ end }}
138− <script>
139− if (window.location.hash) {
140− (function() {
141− var inputs = document.getElementsByName('rd');
142− for (var i = 0; i < inputs.length; i++) {
143− // Add hash, but make sure it is only added once
144− var idx = inputs[i].value.indexOf('#');
145− if (idx >= 0) {
146− // Remove existing hash from URL
147− inputs[i].value = inputs[i].value.substr(0, idx);
148− }
149− inputs[i].value += window.location.hash;
150− }
151− })();
152− }
153− </script>
154− <footer>
155− {{ if eq .Footer "-" }}
156− {{ else if eq .Footer ""}}
157− Secured with <a href="https://github.com/oauth2-proxy/oauth2-proxy#oauth2_proxy">OAuth2 Proxy</a> version {{.Version}}
158− {{ else }}
159− {{.Footer}}
160− {{ end }}
161− </footer>
162−</body>
163−</html>
164−{{end}}`)
165− if err != nil {
166− logger.Fatalf("failed parsing template %s", err)
167− }
168−
169− t, err = t.Parse(`{{define "error.html"}}
170−<!DOCTYPE html>
171−<html lang="en" charset="utf-8">
172−<head>
173− <title>{{.Title}}</title>
174− <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
175−</head>
176−<body>
177− <h2>{{.Title}}</h2>
178− <p>{{.Message}}</p>
179− <hr>
180− <p><a href="{{.ProxyPrefix}}/sign_in">Sign In</a></p>
181−</body>
182−</html>{{end}}`)
183− if err != nil {
184− logger.Fatalf("failed parsing template %s", err)
185− }
186− return t
187−}
templates_test.godeleted−62
@@ -1,62 +0,0 @@
1−package main
2−
3−import (
4− "bytes"
5− "io/ioutil"
6− "log"
7− "os"
8− "path/filepath"
9− "testing"
10−
11− "github.com/stretchr/testify/assert"
12−)
13−
14−func TestLoadTemplates(t *testing.T) {
15− data := struct {
16− TestString string
17− }{
18− TestString: "Testing",
19− }
20−
21− templates := loadTemplates("")
22− assert.NotEqual(t, templates, nil)
23−
24− var defaultSignin bytes.Buffer
25− templates.ExecuteTemplate(&defaultSignin, "sign_in.html", data)
26− assert.Equal(t, "\n<!DOCTYPE html>", defaultSignin.String()[0:16])
27−
28− var defaultError bytes.Buffer
29− templates.ExecuteTemplate(&defaultError, "error.html", data)
30− assert.Equal(t, "\n<!DOCTYPE html>", defaultError.String()[0:16])
31−
32− dir, err := ioutil.TempDir("", "templatetest")
33− if err != nil {
34− log.Fatal(err)
35− }
36− defer os.RemoveAll(dir)
37−
38− templateHTML := `{{.TestString}} {{.TestString | ToLower}} {{.TestString | ToUpper}}`
39− signInFile := filepath.Join(dir, "sign_in.html")
40− if err := ioutil.WriteFile(signInFile, []byte(templateHTML), 0666); err != nil {
41− log.Fatal(err)
42− }
43− errorFile := filepath.Join(dir, "error.html")
44− if err := ioutil.WriteFile(errorFile, []byte(templateHTML), 0666); err != nil {
45− log.Fatal(err)
46− }
47− templates = loadTemplates(dir)
48− assert.NotEqual(t, templates, nil)
49−
50− var sitpl bytes.Buffer
51− templates.ExecuteTemplate(&sitpl, "sign_in.html", data)
52− assert.Equal(t, "Testing testing TESTING", sitpl.String())
53−
54− var errtpl bytes.Buffer
55− templates.ExecuteTemplate(&errtpl, "error.html", data)
56− assert.Equal(t, "Testing testing TESTING", errtpl.String())
57−}
58−
59−func TestTemplatesCompile(t *testing.T) {
60− templates := getTemplates()
61− assert.NotEqual(t, templates, nil)
62−}