git.iko.soy/typeable/oauth2-proxy
on master help sign in
Add static pages to PageWriter interface
9782fc7Joel Speed
pkg/app/pagewriter/pagewriter.go+8
@@ -13,12 +13,14 @@ type Writer interface {
13 WriteSignInPage(rw http.ResponseWriter, req *http.Request, redirectURL string)
13 WriteSignInPage(rw http.ResponseWriter, req *http.Request, redirectURL string)
14 WriteErrorPage(rw http.ResponseWriter, opts ErrorPageOpts)
14 WriteErrorPage(rw http.ResponseWriter, opts ErrorPageOpts)
15 ProxyErrorHandler(rw http.ResponseWriter, req *http.Request, proxyErr error)
15 ProxyErrorHandler(rw http.ResponseWriter, req *http.Request, proxyErr error)
16+ WriteRobotsTxt(rw http.ResponseWriter, req *http.Request)
16}
17}
17
18
18// pageWriter implements the Writer interface
19// pageWriter implements the Writer interface
19type pageWriter struct {
20type pageWriter struct {
20 *errorPageWriter
21 *errorPageWriter
21 *signInPageWriter
22 *signInPageWriter
23+ *staticPageWriter
22}
24}
23
25
24// Opts contains all options required to configure the template
26// Opts contains all options required to configure the template
@@ -88,8 +90,14 @@ func NewWriter(opts Opts) (Writer, error) {
88 logoData: logoData,
90 logoData: logoData,
89 }
91 }
90
92
93+ staticPages, err := newStaticPageWriter(opts.TemplatesPath, errorPage)
94+ if err != nil {
95+ return nil, fmt.Errorf("error loading static page writer: %v", err)
96+ }
97+
91 return &pageWriter{
98 return &pageWriter{
92 errorPageWriter: errorPage,
99 errorPageWriter: errorPage,
93 signInPageWriter: signInPage,
100 signInPageWriter: signInPage,
101+ staticPageWriter: staticPages,
94 }, nil
102 }, nil
95}
103}
pkg/app/pagewriter/robots.txtnew file+2
@@ -0,0 +1,2 @@
1+User-agent: *
2+Disallow: /
pkg/app/pagewriter/static_pages.gonew file+98
@@ -0,0 +1,98 @@
1+package pagewriter
2+
3+import (
4+ // Import embed to allow importing default page templates
5+ _ "embed"
6+ "fmt"
7+ "net/http"
8+ "os"
9+ "path/filepath"
10+
11+ middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
12+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
13+)
14+
15+const (
16+ robotsTxtName = "robots.txt"
17+)
18+
19+//go:embed robots.txt
20+var defaultRobotsTxt []byte
21+
22+// staticPageWriter is used to write static pages.
23+type staticPageWriter struct {
24+ pages map[string][]byte
25+ errorPageWriter *errorPageWriter
26+}
27+
28+// WriteRobotsTxt writes the robots.txt content to the response writer.
29+func (s *staticPageWriter) WriteRobotsTxt(rw http.ResponseWriter, req *http.Request) {
30+ s.writePage(rw, req, robotsTxtName)
31+}
32+
33+// writePage writes the content of the page to the response writer.
34+func (s *staticPageWriter) writePage(rw http.ResponseWriter, req *http.Request, pageName string) {
35+ content, ok := s.pages[pageName]
36+ if !ok {
37+ // If the page isn't regiested, something went wrong and there is a bug.
38+ // Tests should make sure this code path is never hit.
39+ panic(fmt.Sprintf("Static page %q not found", pageName))
40+ }
41+ _, err := rw.Write(content)
42+ if err != nil {
43+ logger.Printf("Error writing %q: %v", pageName, err)
44+ scope := middlewareapi.GetRequestScope(req)
45+ s.errorPageWriter.WriteErrorPage(rw, ErrorPageOpts{
46+ Status: http.StatusInternalServerError,
47+ RequestID: scope.RequestID,
48+ AppError: err.Error(),
49+ })
50+ return
51+ }
52+}
53+
54+func newStaticPageWriter(customDir string, errorWriter *errorPageWriter) (*staticPageWriter, error) {
55+ pages, err := loadStaticPages(customDir)
56+ if err != nil {
57+ return nil, fmt.Errorf("could not load static pages: %v", err)
58+ }
59+
60+ return &staticPageWriter{
61+ pages: pages,
62+ errorPageWriter: errorWriter,
63+ }, nil
64+}
65+
66+// loadStaticPages loads static page content from the custom directory provided.
67+// If any file is not provided in the custom directory, the default will be used
68+// instead.
69+// Statis files include:
70+// - robots.txt
71+func loadStaticPages(customDir string) (map[string][]byte, error) {
72+ pages := make(map[string][]byte)
73+
74+ if err := addStaticPage(pages, customDir, robotsTxtName, defaultRobotsTxt); err != nil {
75+ return nil, fmt.Errorf("could not add robots.txt: %v", err)
76+ }
77+
78+ return pages, nil
79+}
80+
81+// addStaticPage tries to load the named file from the custom directory.
82+// If no custom directory is provided, the default content is used instead.
83+func addStaticPage(pages map[string][]byte, customDir, fileName string, defaultContent []byte) error {
84+ filePath := filepath.Join(customDir, fileName)
85+ if customDir != "" && isFile(filePath) {
86+ content, err := os.ReadFile(filePath)
87+ if err != nil {
88+ return fmt.Errorf("could not read file: %v", err)
89+ }
90+
91+ pages[fileName] = content
92+ return nil
93+ }
94+
95+ // No custom content defined, use the default.
96+ pages[fileName] = defaultContent
97+ return nil
98+}
pkg/app/pagewriter/static_pages_test.gonew file+153
@@ -0,0 +1,153 @@
1+package pagewriter
2+
3+import (
4+ "errors"
5+ "html/template"
6+ "io/ioutil"
7+ "net/http"
8+ "net/http/httptest"
9+ "os"
10+ "path/filepath"
11+
12+ middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
13+ . "github.com/onsi/ginkgo"
14+ . "github.com/onsi/gomega"
15+)
16+
17+var _ = Describe("Static Pages", func() {
18+ var customDir string
19+ const customRobots = "I AM A ROBOT!!!"
20+ var errorPage *errorPageWriter
21+ var request *http.Request
22+
23+ BeforeEach(func() {
24+ errorTmpl, err := template.New("").Parse("{{.Title}}")
25+ Expect(err).ToNot(HaveOccurred())
26+ errorPage = &errorPageWriter{
27+ template: errorTmpl,
28+ }
29+
30+ customDir, err = ioutil.TempDir("", "oauth2-proxy-static-pages-test")
31+ Expect(err).ToNot(HaveOccurred())
32+
33+ robotsTxtFile := filepath.Join(customDir, robotsTxtName)
34+ Expect(ioutil.WriteFile(robotsTxtFile, []byte(customRobots), 0400)).To(Succeed())
35+
36+ request = httptest.NewRequest("", "http://127.0.0.1/", nil)
37+ request = middlewareapi.AddRequestScope(request, &middlewareapi.RequestScope{
38+ RequestID: testRequestID,
39+ })
40+ })
41+
42+ AfterEach(func() {
43+ Expect(os.RemoveAll(customDir)).To(Succeed())
44+ })
45+
46+ Context("Static Page Writer", func() {
47+ Context("With custom content", func() {
48+ var pageWriter *staticPageWriter
49+
50+ BeforeEach(func() {
51+ var err error
52+ pageWriter, err = newStaticPageWriter(customDir, errorPage)
53+ Expect(err).ToNot(HaveOccurred())
54+ })
55+
56+ Context("WriterRobotsTxt", func() {
57+ It("Should write the custom robots txt", func() {
58+ recorder := httptest.NewRecorder()
59+ pageWriter.WriteRobotsTxt(recorder, request)
60+
61+ body, err := ioutil.ReadAll(recorder.Result().Body)
62+ Expect(err).ToNot(HaveOccurred())
63+ Expect(string(body)).To(Equal(customRobots))
64+
65+ Expect(recorder.Result().StatusCode).To(Equal(http.StatusOK))
66+ })
67+ })
68+ })
69+
70+ Context("Without custom content", func() {
71+ var pageWriter *staticPageWriter
72+
73+ BeforeEach(func() {
74+ var err error
75+ pageWriter, err = newStaticPageWriter("", errorPage)
76+ Expect(err).ToNot(HaveOccurred())
77+ })
78+
79+ Context("WriterRobotsTxt", func() {
80+ It("Should write the custom robots txt", func() {
81+ recorder := httptest.NewRecorder()
82+ pageWriter.WriteRobotsTxt(recorder, request)
83+
84+ body, err := ioutil.ReadAll(recorder.Result().Body)
85+ Expect(err).ToNot(HaveOccurred())
86+ Expect(string(body)).To(Equal(string(defaultRobotsTxt)))
87+
88+ Expect(recorder.Result().StatusCode).To(Equal(http.StatusOK))
89+ })
90+
91+ It("Should serve an error if it cannot write the page", func() {
92+ recorder := &testBadResponseWriter{
93+ ResponseRecorder: httptest.NewRecorder(),
94+ }
95+ pageWriter.WriteRobotsTxt(recorder, request)
96+
97+ body, err := ioutil.ReadAll(recorder.Result().Body)
98+ Expect(err).ToNot(HaveOccurred())
99+ Expect(string(body)).To(Equal(string("Internal Server Error")))
100+
101+ Expect(recorder.Result().StatusCode).To(Equal(http.StatusInternalServerError))
102+ })
103+ })
104+ })
105+ })
106+
107+ Context("loadStaticPages", func() {
108+ Context("With custom content", func() {
109+ Context("And a custom robots txt", func() {
110+ It("Loads the custom content", func() {
111+ pages, err := loadStaticPages(customDir)
112+ Expect(err).ToNot(HaveOccurred())
113+ Expect(pages).To(HaveLen(1))
114+ Expect(pages).To(HaveKeyWithValue(robotsTxtName, []byte(customRobots)))
115+ })
116+ })
117+
118+ Context("And no custom robots txt", func() {
119+ It("returns the default content", func() {
120+ robotsTxtFile := filepath.Join(customDir, robotsTxtName)
121+ Expect(os.Remove(robotsTxtFile)).To(Succeed())
122+
123+ pages, err := loadStaticPages(customDir)
124+ Expect(err).ToNot(HaveOccurred())
125+ Expect(pages).To(HaveLen(1))
126+ Expect(pages).To(HaveKeyWithValue(robotsTxtName, defaultRobotsTxt))
127+ })
128+ })
129+ })
130+
131+ Context("Without custom content", func() {
132+ It("Loads the default content", func() {
133+ pages, err := loadStaticPages("")
134+ Expect(err).ToNot(HaveOccurred())
135+ Expect(pages).To(HaveLen(1))
136+ Expect(pages).To(HaveKeyWithValue(robotsTxtName, defaultRobotsTxt))
137+ })
138+ })
139+ })
140+})
141+
142+type testBadResponseWriter struct {
143+ *httptest.ResponseRecorder
144+ firstWriteCalled bool
145+}
146+
147+func (b *testBadResponseWriter) Write(buf []byte) (int, error) {
148+ if !b.firstWriteCalled {
149+ b.firstWriteCalled = true
150+ return 0, errors.New("write closed")
151+ }
152+ return b.ResponseRecorder.Write(buf)
153+}