diff --git a/allow_on_405_answer_889_test.go b/allow_on_405_answer_889_test.go new file mode 100644 index 00000000..964b08a2 --- /dev/null +++ b/allow_on_405_answer_889_test.go @@ -0,0 +1,109 @@ +package celeris + +import ( + "strings" + "testing" +) + +// celeris#889 (from #852's round-2 review): the 405's Allow header is set by +// the end of the 405 chain, not before the global middleware, so a +// middleware's own answer to a request whose method no route takes (an auth +// 401) does not tell an unauthenticated client which methods the path takes. + +func TestAllowOnlyOnThe405Answer889(t *testing.T) { + auth := func(c *Context) error { + if c.Header("authorization") == "" { + return c.Blob(401, "text/plain", []byte("unauthorized")) + } + return c.Next() + } + for _, custom := range []bool{false, true} { + name := "builtin" + if custom { + name = "custom-handler" + } + t.Run(name, func(t *testing.T) { + s := New(Config{}) + s.Use(auth) + s.GET("/admin/users", func(c *Context) error { return c.String(200, "ok") }) + s.POST("/admin/users", func(c *Context) error { return c.String(201, "ok") }) + if custom { + s.MethodNotAllowed(func(c *Context) error { return c.String(405, "custom 405") }) + } + + // Unauthenticated: the middleware answers, with no Allow, on a + // path with routes and on one without. + for _, rq := range [][2]string{{"DELETE", "/admin/users"}, {"GET", "/nope"}} { + for arm, rw := range serve852(t, s, rq[0], rq[1]) { + desc := arm + " " + rq[0] + " " + rq[1] + r := one852(t, desc, rw) + if r.status != 401 { + t.Errorf("%s: status %d, want 401", desc, r.status) + } + if a := r.header("allow"); len(a) != 0 { + t.Errorf("%s: Allow %v on the middleware's own 401: it names the methods the path takes to an unauthenticated client", desc, a) + } + } + } + + // Admitted: the 405 itself carries the one Allow header listing + // the methods the path takes, builtin or custom handler alike. + s2 := New(Config{}) + s2.Use(func(c *Context) error { return c.Next() }) + s2.GET("/admin/users", func(c *Context) error { return c.String(200, "ok") }) + s2.POST("/admin/users", func(c *Context) error { return c.String(201, "ok") }) + if custom { + s2.MethodNotAllowed(func(c *Context) error { return c.String(405, "custom 405") }) + } + for arm, rw := range serve852(t, s2, "DELETE", "/admin/users") { + r := one852(t, arm, rw) + if r.status != 405 { + t.Fatalf("%s: status %d, want 405", arm, r.status) + } + a := r.header("allow") + if len(a) != 1 || !strings.Contains(a[0], "GET") || !strings.Contains(a[0], "POST") || strings.Contains(a[0], "DELETE") { + t.Errorf("%s: Allow %v on the 405, want one header listing GET and POST and not DELETE", arm, a) + } + } + }) + } +} + +// TestAllowOnA405WithTheChainStartedByStart889: the chains Start builds +// (buildUnmatchedChains) end in the same Allow-setting step, and the context's +// per-request value does not leak into the next request that reuses it. +func TestAllowOnA405WithTheChainStartedByStart889(t *testing.T) { + s := New(Config{}) + s.Use(func(c *Context) error { + if c.Method() == "DELETE" && c.Header("authorization") == "" { + return c.Blob(401, "text/plain", []byte("unauthorized")) + } + return c.Next() + }) + s.GET("/x", func(c *Context) error { return c.String(200, "ok") }) + ra := &routerAdapter{server: s} + ra.buildUnmatchedChains() + run := func(method, path string, hdr ...string) recordedResponse852 { + t.Helper() + st, _ := newTestStream(method, path) + for i := 0; i+1 < len(hdr); i += 2 { + st.Headers = append(st.Headers, [2]string{hdr[i], hdr[i+1]}) + } + rw := &recordingRW852{} + st.ResponseWriter = rw + if err := ra.HandleStream(t.Context(), st); err != nil { + t.Fatal(err) + } + st.Release() + return one852(t, method+" "+path, rw) + } + if r := run("DELETE", "/x"); r.status != 401 || len(r.header("allow")) != 0 { + t.Errorf("unauthenticated DELETE /x: %d allow=%v, want 401 and no Allow", r.status, r.header("allow")) + } + if r := run("POST", "/x"); r.status != 405 || len(r.header("allow")) != 1 { + t.Errorf("POST /x: %d allow=%v, want 405 with one Allow", r.status, r.header("allow")) + } + if r := run("GET", "/nope"); r.status != 404 || len(r.header("allow")) != 0 { + t.Errorf("GET /nope: %d allow=%v, want 404 and no Allow", r.status, r.header("allow")) + } +} diff --git a/context.go b/context.go index ee8007fb..01643ae8 100644 --- a/context.go +++ b/context.go @@ -117,6 +117,9 @@ type Context struct { path string rawQuery string fullPath string + // unmatchedAllow is the Allow value of a 405 under way (celeris#889), + // written by the end of the 405 chain, not before the middleware. + unmatchedAllow string statusCode int respHeaders [][2]string @@ -667,6 +670,7 @@ func (c *Context) reset() { c.path = "" c.rawQuery = "" c.fullPath = "" + c.unmatchedAllow = "" c.statusCode = 200 if n := len(c.respHeaders); n > 0 { // When a middleware stack emits more response headers than respHdrBuf diff --git a/handler.go b/handler.go index e9549f92..597d9b67 100644 --- a/handler.go +++ b/handler.go @@ -66,7 +66,7 @@ func newOptionsChain(middleware []HandlerFunc) []HandlerFunc { func (a *routerAdapter) buildUnmatchedChains() { s := a.server a.notFoundChain = newUnmatchedChain(s.middleware, s.notFoundHandler, builtinNotFound) - a.methodNotAllowedChain = newUnmatchedChain(s.middleware, s.methodNotAllowedHandler, builtinMethodNotAllowed) + a.methodNotAllowedChain = newMethodNotAllowedChain(s.middleware, s.methodNotAllowedHandler) // Written only when true: Server.AsyncHandlers, which a driver opened // WithEngine may call while Start runs, reads the flag only when the // default is sync, and then nothing writes it. @@ -93,6 +93,29 @@ func newUnmatchedChain(middleware []HandlerFunc, custom, builtin HandlerFunc) [] return append(chain, answerUnlessAnswered(end)) } +// newMethodNotAllowedChain is newUnmatchedChain for a 405, whose end sets the +// Allow header before the NotFound-like handler runs (withAllow). +func newMethodNotAllowedChain(middleware []HandlerFunc, custom HandlerFunc) []HandlerFunc { + end := builtinMethodNotAllowed + if custom != nil { + end = custom + } + return newUnmatchedChain(middleware, withAllow(end), nil) +} + +// withAllow sets the Allow header of the 405 under way (handleUnmatched +// stored it in c.unmatchedAllow) and runs h, so only a 405 answered by h +// carries it. A middleware that answers first (an auth 401, a rate limit's +// 429) sends none: celeris#889. +func withAllow(h HandlerFunc) HandlerFunc { + return func(c *Context) error { + if c.unmatchedAllow != "" { + c.SetHeader("allow", c.unmatchedAllow) + } + return h(c) + } +} + // answerUnlessAnswered runs h only if no handler before it in the chain has // answered the request: written the response, had it captured by a buffering // middleware (compress, etag, cache, ...) or taken the connection over. @@ -114,7 +137,7 @@ func answerUnlessAnswered(h HandlerFunc) HandlerFunc { // builtinNotFound and builtinMethodNotAllowed are the answers to an unmatched // request when no NotFound / MethodNotAllowed handler is set. They write // through the Context, as a route handler does, so buffering middleware sees -// the response; handleUnmatched has set the Allow header of a 405. +// the response; the end of a 405 chain sets its Allow header (withAllow). func builtinNotFound(c *Context) error { return c.Blob(404, "text/plain", []byte("404 Not Found")) } @@ -554,11 +577,12 @@ func (a *routerAdapter) handleUnmatched(c *Context, s *stream.Stream) { allowVal := strings.Join(allowed, ", ") chain := a.methodNotAllowedChain if chain == nil { - chain = newUnmatchedChain(a.server.middleware, a.server.methodNotAllowedHandler, builtinMethodNotAllowed) + chain = newMethodNotAllowedChain(a.server.middleware, a.server.methodNotAllowedHandler) } - // Set before the chain, so the Allow header is on the response - // whichever handler writes it. - c.SetHeader("allow", allowVal) + // The end of the chain sets Allow (withAllow), not this function + // before the middleware: a middleware's own answer (an auth 401) + // must not tell the client which methods a path takes (celeris#889). + c.unmatchedAllow = allowVal a.runUnmatched(c, s, chain) if !c.written && !c.detached && s.ResponseWriter != nil { // Nothing answered: a middleware aborted without writing, or