Skip to content

Commit

Permalink
proxy/actions/sumdb: copy Go behavior for pattern matching (#1388)
Browse files Browse the repository at this point in the history
  • Loading branch information
marwan-at-work authored Sep 20, 2019
1 parent 56a7e09 commit 68ba750
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
28 changes: 27 additions & 1 deletion cmd/proxy/actions/sumdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func noSumWrapper(h http.Handler, host string, patterns []string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/lookup/") {
for _, p := range patterns {
if isMatch, err := path.Match(p, r.URL.Path[len("/lookup/"):]); err == nil && isMatch {
if matchesPattern(p, r.URL.Path[len("/lookup/"):]) {
w.WriteHeader(http.StatusForbidden)
return
}
Expand All @@ -34,3 +34,29 @@ func noSumWrapper(h http.Handler, host string, patterns []string) http.Handler {
h.ServeHTTP(w, r)
})
}

// matchesPattern is adopted from
// https://github.com/golang/go/blob/a11644a26557ea436d456f005f39f4e01902bafe/src/cmd/go/internal/str/path.go#L58
// this function matches based on path prefixes and
// tries to keep the same behavior as GONOSUMDB and friends
func matchesPattern(pattern, target string) bool {
n := strings.Count(pattern, "/")
prefix := target
for i := 0; i < len(target); i++ {
if target[i] == '/' {
if n == 0 {
prefix = target[:i]
break
}
n--
}
}
if n > 0 {
return false
}
matched, _ := path.Match(pattern, prefix)
if matched {
return true
}
return false
}
24 changes: 24 additions & 0 deletions cmd/proxy/actions/sumdb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,30 @@ var noSumTestCases = []struct {
"github.com/private/repo@v0.0.1",
http.StatusForbidden,
},
{
"multi slash star",
[]string{"github.com/private/*"},
"github.com/private/repo/sub@v0.0.1",
http.StatusForbidden,
},
{
"multi star",
[]string{"github.com/*/*"},
"github.com/private/repo@v0.0.1",
http.StatusForbidden,
},
{
"multi star ok",
[]string{"github.com/private/*/*"},
"github.com/private/repo@v0.0.1",
http.StatusOK,
},
{
"multi star forbidden",
[]string{"github.com/private/*/*"},
"github.com/private/repo/sub@v0.0.1",
http.StatusForbidden,
},
{
"any version",
[]string{"github.com/private/repo*"},
Expand Down

0 comments on commit 68ba750

Please sign in to comment.