git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge pull request #110 from timothy-spencer/gcphealthcheck

added an option to enable GCP healthcheck endpoints

commite9d4f6e0a13b0a498507f61d31aa37f99dac2f8c authorJoel Speed <Joel.speed@hotmail.co.uk> dateWed 27 Mar 2019, 11:58 (8 years ago) parentda0d4ac6bb32c8
7 files changed+167−6
CHANGELOG.md+1 README.md+2−1 http.go+39 http_test.go+105 main.go+9−1 options.go+5−4 options_test.go+6
CHANGELOG.md+1
@@ -2,6 +2,7 @@
22
33## Changes since v3.1.0
44
5+- [#110](https://github.com/pusher/oauth2_proxy/pull/110) Added GCP healthcheck option (@timothy-spencer)
56- [#112](https://github.com/pusher/oauth2_proxy/pull/112) Improve websocket support (@gyson)
67- [#63](https://github.com/pusher/oauth2_proxy/pull/63) Use encoding/json for SessionState serialization (@yaegashi)
78 - Use JSON to encode session state to be stored in browser cookies
README.md+2−1
@@ -48,7 +48,7 @@ Valid providers are :
4848- [GitHub](#github-auth-provider)
4949- [GitLab](#gitlab-auth-provider)
5050- [LinkedIn](#linkedin-auth-provider)
51−- [login.gov](#login.gov-provider)
51+- [login.gov](#logingov-provider)
5252
5353The provider can be selected using the `provider` configuration value.
5454
@@ -272,6 +272,7 @@ Usage of oauth2_proxy:
272272 -email-domain value: authenticate emails with the specified domain (may be given multiple times). Use * to authenticate any email
273273 -flush-interval: period between flushing response buffers when streaming responses (default "1s")
274274 -footer string: custom footer string. Use "-" to disable default footer.
275+ -gcp-healthchecks: will enable /liveness_check, /readiness_check, and / (with the proper user-agent) endpoints that will make it work well with GCP App Engine and GKE Ingresses (default false)
275276 -github-org string: restrict logins to members of this organisation
276277 -github-team string: restrict logins to members of any of these teams (slug), separated by a comma
277278 -google-admin-email string: the google admin to impersonate for api calls
http.go+39
@@ -24,6 +24,45 @@ func (s *Server) ListenAndServe() {
2424 }
2525}
2626
27+// Used with gcpHealthcheck()
28+const userAgentHeader = "User-Agent"
29+const googleHealthCheckUserAgent = "GoogleHC/1.0"
30+const rootPath = "/"
31+
32+// gcpHealthcheck handles healthcheck queries from GCP.
33+func gcpHealthcheck(h http.Handler) http.Handler {
34+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
35+ // Check for liveness and readiness: used for Google App Engine
36+ if r.URL.EscapedPath() == "/liveness_check" {
37+ w.WriteHeader(http.StatusOK)
38+ w.Write([]byte("OK"))
39+ return
40+ }
41+ if r.URL.EscapedPath() == "/readiness_check" {
42+ w.WriteHeader(http.StatusOK)
43+ w.Write([]byte("OK"))
44+ return
45+ }
46+
47+ // Check for GKE ingress healthcheck: The ingress requires the root
48+ // path of the target to return a 200 (OK) to indicate the service's good health. This can be quite a challenging demand
49+ // depending on the application's path structure. This middleware filters out the requests from the health check by
50+ //
51+ // 1. checking that the request path is indeed the root path
52+ // 2. ensuring that the User-Agent is "GoogleHC/1.0", the health checker
53+ // 3. ensuring the request method is "GET"
54+ if r.URL.Path == rootPath &&
55+ r.Header.Get(userAgentHeader) == googleHealthCheckUserAgent &&
56+ r.Method == http.MethodGet {
57+
58+ w.WriteHeader(http.StatusOK)
59+ return
60+ }
61+
62+ h.ServeHTTP(w, r)
63+ })
64+}
65+
2766// ServeHTTP constructs a net.Listener and starts handling HTTP requests
2867func (s *Server) ServeHTTP() {
2968 HTTPAddress := s.Opts.HTTPAddress
http_test.gonew file+105
@@ -0,0 +1,105 @@
1+package main
2+
3+import (
4+ "net/http"
5+ "net/http/httptest"
6+ "testing"
7+
8+ "github.com/stretchr/testify/assert"
9+)
10+
11+func TestGCPHealthcheckLiveness(t *testing.T) {
12+ handler := func(w http.ResponseWriter, req *http.Request) {
13+ w.Write([]byte("test"))
14+ }
15+
16+ h := gcpHealthcheck(http.HandlerFunc(handler))
17+ rw := httptest.NewRecorder()
18+ r, _ := http.NewRequest("GET", "/liveness_check", nil)
19+ r.RemoteAddr = "127.0.0.1"
20+ r.Host = "test-server"
21+ h.ServeHTTP(rw, r)
22+
23+ assert.Equal(t, 200, rw.Code)
24+ assert.Equal(t, "OK", rw.Body.String())
25+}
26+
27+func TestGCPHealthcheckReadiness(t *testing.T) {
28+ handler := func(w http.ResponseWriter, req *http.Request) {
29+ w.Write([]byte("test"))
30+ }
31+
32+ h := gcpHealthcheck(http.HandlerFunc(handler))
33+ rw := httptest.NewRecorder()
34+ r, _ := http.NewRequest("GET", "/readiness_check", nil)
35+ r.RemoteAddr = "127.0.0.1"
36+ r.Host = "test-server"
37+ h.ServeHTTP(rw, r)
38+
39+ assert.Equal(t, 200, rw.Code)
40+ assert.Equal(t, "OK", rw.Body.String())
41+}
42+
43+func TestGCPHealthcheckNotHealthcheck(t *testing.T) {
44+ handler := func(w http.ResponseWriter, req *http.Request) {
45+ w.Write([]byte("test"))
46+ }
47+
48+ h := gcpHealthcheck(http.HandlerFunc(handler))
49+ rw := httptest.NewRecorder()
50+ r, _ := http.NewRequest("GET", "/not_any_check", nil)
51+ r.RemoteAddr = "127.0.0.1"
52+ r.Host = "test-server"
53+ h.ServeHTTP(rw, r)
54+
55+ assert.Equal(t, "test", rw.Body.String())
56+}
57+
58+func TestGCPHealthcheckIngress(t *testing.T) {
59+ handler := func(w http.ResponseWriter, req *http.Request) {
60+ w.Write([]byte("test"))
61+ }
62+
63+ h := gcpHealthcheck(http.HandlerFunc(handler))
64+ rw := httptest.NewRecorder()
65+ r, _ := http.NewRequest("GET", "/", nil)
66+ r.RemoteAddr = "127.0.0.1"
67+ r.Host = "test-server"
68+ r.Header.Set(userAgentHeader, googleHealthCheckUserAgent)
69+ h.ServeHTTP(rw, r)
70+
71+ assert.Equal(t, 200, rw.Code)
72+ assert.Equal(t, "", rw.Body.String())
73+}
74+
75+func TestGCPHealthcheckNotIngress(t *testing.T) {
76+ handler := func(w http.ResponseWriter, req *http.Request) {
77+ w.Write([]byte("test"))
78+ }
79+
80+ h := gcpHealthcheck(http.HandlerFunc(handler))
81+ rw := httptest.NewRecorder()
82+ r, _ := http.NewRequest("GET", "/foo", nil)
83+ r.RemoteAddr = "127.0.0.1"
84+ r.Host = "test-server"
85+ r.Header.Set(userAgentHeader, googleHealthCheckUserAgent)
86+ h.ServeHTTP(rw, r)
87+
88+ assert.Equal(t, "test", rw.Body.String())
89+}
90+
91+func TestGCPHealthcheckNotIngressPut(t *testing.T) {
92+ handler := func(w http.ResponseWriter, req *http.Request) {
93+ w.Write([]byte("test"))
94+ }
95+
96+ h := gcpHealthcheck(http.HandlerFunc(handler))
97+ rw := httptest.NewRecorder()
98+ r, _ := http.NewRequest("PUT", "/", nil)
99+ r.RemoteAddr = "127.0.0.1"
100+ r.Host = "test-server"
101+ r.Header.Set(userAgentHeader, googleHealthCheckUserAgent)
102+ h.ServeHTTP(rw, r)
103+
104+ assert.Equal(t, "test", rw.Body.String())
105+}
main.go+9−1
@@ -5,6 +5,7 @@ import (
55 "fmt"
66 "log"
77 "math/rand"
8+ "net/http"
89 "os"
910 "runtime"
1011 "strings"
@@ -92,6 +93,7 @@ func main() {
9293 flagSet.String("acr-values", "http://idmanagement.gov/ns/assurance/loa/1", "acr values string: optional, used by login.gov")
9394 flagSet.String("jwt-key", "", "private key used to sign JWT: required by login.gov")
9495 flagSet.String("pubjwk-url", "", "JWK pubkey access endpoint: required by login.gov")
96+ flagSet.Bool("gcp-healthchecks", false, "Enable GCP/GKE healthcheck endpoints")
9597
9698 flagSet.Parse(os.Args[1:])
9799
@@ -139,8 +141,14 @@ func main() {
139141
140142 rand.Seed(time.Now().UnixNano())
141143
144+ var handler http.Handler
145+ if opts.GCPHealthChecks {
146+ handler = gcpHealthcheck(LoggingHandler(os.Stdout, oauthproxy, opts.RequestLogging, opts.RequestLoggingFormat))
147+ } else {
148+ handler = LoggingHandler(os.Stdout, oauthproxy, opts.RequestLogging, opts.RequestLoggingFormat)
149+ }
142150 s := &Server{
143− Handler: LoggingHandler(os.Stdout, oauthproxy, opts.RequestLogging, opts.RequestLoggingFormat),
151+ Handler: handler,
144152 Opts: opts,
145153 }
146154 s.ListenAndServe()
options.go+5−4
@@ -86,10 +86,11 @@ type Options struct {
8686 RequestLogging bool `flag:"request-logging" cfg:"request_logging" env:"OAUTH2_PROXY_REQUEST_LOGGING"`
8787 RequestLoggingFormat string `flag:"request-logging-format" cfg:"request_logging_format" env:"OAUTH2_PROXY_REQUEST_LOGGING_FORMAT"`
8888
89− SignatureKey string `flag:"signature-key" cfg:"signature_key" env:"OAUTH2_PROXY_SIGNATURE_KEY"`
90− AcrValues string `flag:"acr-values" cfg:"acr_values" env:"OAUTH2_PROXY_ACR_VALUES"`
91− JWTKey string `flag:"jwt-key" cfg:"jwt_key" env:"OAUTH2_PROXY_JWT_KEY"`
92− PubJWKURL string `flag:"pubjwk-url" cfg:"pubjwk_url" env:"OAUTH2_PROXY_PUBJWK_URL"`
89+ SignatureKey string `flag:"signature-key" cfg:"signature_key" env:"OAUTH2_PROXY_SIGNATURE_KEY"`
90+ AcrValues string `flag:"acr-values" cfg:"acr_values" env:"OAUTH2_PROXY_ACR_VALUES"`
91+ JWTKey string `flag:"jwt-key" cfg:"jwt_key" env:"OAUTH2_PROXY_JWT_KEY"`
92+ PubJWKURL string `flag:"pubjwk-url" cfg:"pubjwk_url" env:"OAUTH2_PROXY_PUBJWK_URL"`
93+ GCPHealthChecks bool `flag:"gcp-healthchecks" cfg:"gcp_healthchecks" env:"OAUTH2_PROXY_GCP_HEALTHCHECKS"`
9394
9495 // internal values that are set after config validation
9596 redirectURL *url.URL
options_test.go+6
@@ -268,3 +268,9 @@ func TestSkipOIDCDiscovery(t *testing.T) {
268268
269269 assert.Equal(t, nil, o.Validate())
270270}
271+
272+func TestGCPHealthcheck(t *testing.T) {
273+ o := testOptions()
274+ o.GCPHealthChecks = true
275+ assert.Equal(t, nil, o.Validate())
276+}