package waf import ( "crypto/subtle" "io" "net/http" "strings" "github.com/go-chi/chi/v5" "sneak.berlin/go/smallwebwaf/internal/requestlog" "sneak.berlin/go/smallwebwaf/internal/wafprotocol" ) // routes returns the router of waf's own endpoints. A question never reaches // it, since ServeHTTP answers a question first. No check runs on a request // here: waf's address is on the private network, where the peers are rproxy // and the admin's tools, not visitors. func (h *handler) routes() http.Handler { r := chi.NewRouter() r.Use(matchDecodedPath) // The report writes no log line of its own: it finishes the line of the // request it reports. r.Post(wafprotocol.ReportPath, h.handleReport()) r.Group(func(r chi.Router) { r.Use(h.logOwnEndpoint) // The answer to a path with no endpoint, and to a method the path has // no endpoint for, is set in this group, so that it is logged too. r.NotFound(answerNotFound) r.MethodNotAllowed(answerNotFound) r.Get(wafprotocol.HealthPath, handleHealth()) r.Group(func(r chi.Router) { r.Use(requireToken(h.config.MetricsToken)) r.Get(MetricsPath, h.metrics.ServeHTTP) }) // The handlers under BansPath/ and ClientsPath read the address from // the path themselves, so that one that is not an address gets 400 // after the token check. r.Group(func(r chi.Router) { r.Use(requireToken(h.config.AdminToken)) r.Get(BansPath, h.handleListBans()) r.Post(BansPath, h.handleAddBan()) r.Delete(BansPath+"/*", h.handleLiftBans()) r.Get(ClientsPath+"*", h.handleShowClient()) }) }) return r } // matchDecodedPath has the router match the decoded path, which the handlers // read. chi matches the path as sent when it is encoded in an unusual way, // which would make /_sww/%68ealthz a path with no endpoint. func matchDecodedPath(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { chi.RouteContext(r.Context()).RoutePath = r.URL.Path next.ServeHTTP(w, r) }) } // logOwnEndpoint writes one log line for each request, with the action // own_endpoint. The line's request_bytes is how much of the body the handler // read. func (h *handler) logOwnEndpoint(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { peer := peerAddress(r) rq := h.startRequest(w, r, peer, peer, false) defer rq.finish() rq.line.Action = requestlog.ActionOwnEndpoint counted := r.Clone(r.Context()) counted.Body = &countedBody{ ReadCloser: r.Body, read: &rq.requestBytes, } next.ServeHTTP(rq.out, counted) }) } // countedBody is a request's body that adds the bytes read of it to read. type countedBody struct { io.ReadCloser read *int64 } // Read reads part of the body. func (b *countedBody) Read(p []byte) (int, error) { n, err := b.ReadCloser.Read(p) *b.read += int64(n) return n, err } // requireToken returns middleware that lets a request through only when it // carries token, as Authorization: Bearer . It answers 401 to a request // without it. While token is unset, it answers 404, as a path with no endpoint // does. func requireToken(token string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { switch { case token == "": answerNotFound(w, r) case !hasToken(r, token): w.Header().Set("WWW-Authenticate", "Bearer") http.Error( w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized, ) default: next.ServeHTTP(w, r) } }, ) } } // hasToken reports whether r carries token, as Authorization: Bearer // . func hasToken(r *http.Request, token string) bool { scheme, sent, _ := strings.Cut(r.Header.Get("Authorization"), " ") return strings.EqualFold(scheme, "Bearer") && subtle.ConstantTimeCompare([]byte(sent), []byte(token)) == 1 } // answerNotFound answers 404, for a path with no endpoint, and for a method // the path has no endpoint for. func answerNotFound(w http.ResponseWriter, _ *http.Request) { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) }