From 1a7fc0892dac8a6cae70de57a64da4129e61331b Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Tue, 16 Jan 2018 20:49:45 -0800 Subject: [PATCH] cmd/routed: use HTTP-01 challenges --- cmd/routed/main.go | 18 ++---------------- cmd/routed/server.go | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/cmd/routed/main.go b/cmd/routed/main.go index 323c561..d982015 100644 --- a/cmd/routed/main.go +++ b/cmd/routed/main.go @@ -55,22 +55,8 @@ func main() { defer l.Close() hs := &http.Server{ - Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case http.MethodPatch, http.MethodPut, http.MethodPost: - http.Error(w, "use https", http.StatusNotAcceptable) - ln.Log(r.Context(), ln.Action("cannot redirect (wrong method)"), ln.F{"remote": r.RemoteAddr, "host": r.Host, "path": r.URL.Path}) - return - } - - r.URL.Host = r.Host - r.URL.Scheme = "https" - - ln.Log(r.Context(), ln.Action("redirecting insecure HTTP to HTTPS"), ln.F{"remote": r.RemoteAddr, "host": r.Host, "path": r.URL.Path}) - - http.Redirect(w, r, r.URL.String(), http.StatusPermanentRedirect) - }), - Addr: scfg.WebAddr, + Handler: s.Manager.HTTPHandler(http.HandlerFunc(insecureRedirect)), + Addr: scfg.WebAddr, } hs.Serve(l) diff --git a/cmd/routed/server.go b/cmd/routed/server.go index 932b710..ef46c87 100644 --- a/cmd/routed/server.go +++ b/cmd/routed/server.go @@ -200,3 +200,20 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { rp.ServeHTTP(w, r) } + +// insecureRedirect redirects a client to https if they connect over plain HTTP. +func insecureRedirect(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodPatch, http.MethodPut, http.MethodPost: + http.Error(w, "use https", http.StatusNotAcceptable) + ln.Log(r.Context(), ln.Action("cannot redirect (wrong method)"), ln.F{"remote": r.RemoteAddr, "host": r.Host, "path": r.URL.Path}) + return + } + + r.URL.Host = r.Host + r.URL.Scheme = "https" + + ln.Log(r.Context(), ln.Action("redirecting insecure HTTP to HTTPS"), ln.F{"remote": r.RemoteAddr, "host": r.Host, "path": r.URL.Path}) + + http.Redirect(w, r, r.URL.String(), http.StatusPermanentRedirect) +}