Allow a health/ping request to be identified by User-Agent (#567)

* Add an option to allow health checks based on User-Agent.

* Formatting fix

* Rename field and avoid unnecessary interface.

* Skip the redirect fix so it can be put into a different PR.

* Add CHANGELOG entry

* Adding a couple tests for the PingUserAgent option.
This commit is contained in:
Christopher Kohnert
2020-06-12 14:56:31 +01:00
committed by GitHub
parent 160bbaf98e
commit 2c851fcd4f
6 changed files with 89 additions and 3 deletions
+21 -1
View File
@@ -82,6 +82,8 @@ type OAuthProxy struct {
RobotsPath string
PingPath string
PingUserAgent string
SilencePings bool
SignInPath string
SignOutPath string
OAuthStartPath string
@@ -312,6 +314,8 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) *OAuthPro
RobotsPath: "/robots.txt",
PingPath: opts.PingPath,
PingUserAgent: opts.PingUserAgent,
SilencePings: opts.Logging.SilencePing,
SignInPath: fmt.Sprintf("%s/sign_in", opts.ProxyPrefix),
SignOutPath: fmt.Sprintf("%s/sign_out", opts.ProxyPrefix),
OAuthStartPath: fmt.Sprintf("%s/start", opts.ProxyPrefix),
@@ -466,6 +470,11 @@ func (p *OAuthProxy) RobotsTxt(rw http.ResponseWriter) {
// PingPage responds 200 OK to requests
func (p *OAuthProxy) PingPage(rw http.ResponseWriter) {
if p.SilencePings {
if rl, ok := rw.(*responseLogger); ok {
rl.silent = true
}
}
rw.WriteHeader(http.StatusOK)
fmt.Fprintf(rw, "OK")
}
@@ -675,6 +684,17 @@ func prepareNoCache(w http.ResponseWriter) {
}
}
// IsPingRequest will check if the request appears to be performing a health check
// either via the path it's requesting or by a special User-Agent configuration.
func (p *OAuthProxy) IsPingRequest(req *http.Request) bool {
if req.URL.EscapedPath() == p.PingPath {
return true
}
return p.PingUserAgent != "" && req.Header.Get("User-Agent") == p.PingUserAgent
}
func (p *OAuthProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.URL.Path, p.ProxyPrefix) {
prepareNoCache(rw)
@@ -683,7 +703,7 @@ func (p *OAuthProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
switch path := req.URL.Path; {
case path == p.RobotsPath:
p.RobotsTxt(rw)
case path == p.PingPath:
case p.IsPingRequest(req):
p.PingPage(rw)
case p.IsWhitelistedRequest(req):
p.serveMux.ServeHTTP(rw, req)