Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions server/adapters/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"fmt"
"io"
"net/http"
"path"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions server/adapters/http_test.go
Original file line number Diff line number Diff line change
@@ -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
})
}
}
Loading