Skip to content

A regexp placeholder followed by a suffix matches a value containing / #1188

Description

@DRMacIver

When a literal suffix follows a regexp placeholder, the placeholder's value can span a slash: /re/{name:[^.]+}.json serves /re/a/b.json with name = "a/b", while the same regexp with nothing after it, and a plain {name}.json, both return 404 for a two-segment value:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/go-chi/chi/v5"
)

func main() {
	r := chi.NewRouter()
	echo := func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "name=%q", chi.URLParam(r, "name"))
	}
	r.Get("/re/{name:[^.]+}.json", echo)
	r.Get("/bare/{name:[^.]+}", echo)
	r.Get("/plain/{name}.json", echo)
	for _, p := range []string{"/re/a.json", "/re/a/b.json", "/bare/a/b", "/plain/a/b.json"} {
		rec := httptest.NewRecorder()
		r.ServeHTTP(rec, httptest.NewRequest("GET", p, nil))
		fmt.Printf("GET %-16s -> %d %s\n", p, rec.Code, strings.TrimSpace(rec.Body.String()))
	}
}

Output:

GET /re/a.json       -> 200 name="a"
GET /re/a/b.json     -> 200 name="a/b"
GET /bare/a/b        -> 404 404 page not found
GET /plain/a/b.json  -> 404 404 page not found

The "URL patterns" documentation in chi.go says of a regexp placeholder that / will never be matched. I expected GET /re/a/b.json to be a 404 like the other two, rather than a match with a slash inside the parameter value.

Tested on chi v5.3.2 and on current master (3d1777a).

BTW, this was found by an automated program that writes property-based tests for various open source projects using hegel (but it has been reviewed by hand before reporting). We've also potentially found (but not yet hand validated) 15 other bugs in chi. You can see the tests at https://github.com/hegeldev/hegel-zoo/tree/main/targets/go/chi. Let us know if you would like us to file the other bugs found and/or contribute the tests. NB the tests are currently LLM generated and probably not yet suitable for inclusion as is, but we're happy to help get them into a better state if you want them.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions