diff --git a/server/adapters/http.go b/server/adapters/http.go index 3fbf5fc6..2a45bbc3 100644 --- a/server/adapters/http.go +++ b/server/adapters/http.go @@ -14,6 +14,7 @@ import ( "fmt" "io" "net/http" + "path" "strconv" "strings" "time" @@ -76,10 +77,30 @@ func NewHttpAdapter( // ServeHTTP delegates to the internal mux which routes between // connection-status lookups and broker dispatch. +// +// A /broker/ path that is not clean (it has "//", "/./" or "/../") goes +// directly to dispatch. ServeMux answers such a path with a 301 to the +// cleaned path, and that Location is relative. The dispatcher cannot follow +// a relative redirect, so the call failed. snyk-broker forwards the path as +// it is, and the upstream decides what the path means. We do the same. func (h *HttpAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/broker/") && !isCleanPath(r.URL.Path) { + h.handleBrokerDispatch(w, r) + return + } h.mux.ServeHTTP(w, r) } +// isCleanPath reports whether ServeMux would route p without a redirect. It +// uses the same rule as ServeMux: path.Clean, with a trailing slash kept. +func isCleanPath(p string) bool { + cleaned := path.Clean(p) + if strings.HasSuffix(p, "/") && cleaned != "/" { + cleaned += "/" + } + return cleaned == p +} + // brokerOKFalse and brokerOKTrue are snyk-broker's response bodies, byte for // byte. Their exact bytes matter: the dispatcher identifies "this server does // not have that token" by comparing the body, so a reformat here (a space diff --git a/server/adapters/http_test.go b/server/adapters/http_test.go new file mode 100644 index 00000000..c227160a --- /dev/null +++ b/server/adapters/http_test.go @@ -0,0 +1,34 @@ +package adapters + +import ( + "context" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" +) + +// The agent must get the path as the caller sent it, as with snyk-broker. +// ServeMux cleans a path with "//", "/./" or "/../" and answers with a 301 +// to a relative Location, which the dispatcher cannot follow. +func TestBrokerDispatch_ForwardsPathAsSent(t *testing.T) { + for name, path := range map[string]string{ + "clean": "/repos/o/r/contents/Jenkinsfile", + "double slash": "/repos/o/r/contents//Jenkinsfile", + "dot": "/repos/o/r/contents/./Jenkinsfile", + "dot dot": "/repos/o/r/../r/contents/Jenkinsfile", + "query": "/repos/o/r/contents//Jenkinsfile?ref=main", + } { + t.Run(name, func(t *testing.T) { + fh := newFailureHarness(t, 0) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan *httptest.ResponseRecorder, 1) + go func() { done <- fh.serve(ctx, path) }() + + start := fh.next(t, isStart).GetStart() + require.Equal(t, path, start.GetPseudoHeaders()[":path"]) + cancel() + <-done + }) + } +}