Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bugfix#2036 Websocket connections ignore userAgent setting #2151

Merged
merged 11 commits into from
Oct 12, 2021
5 changes: 2 additions & 3 deletions js/modules/k6/ws/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ func (*WS) Connect(ctx context.Context, url string, args ...goja.Value) (*WSHTTP
return nil, errors.New("last argument to ws.connect must be a function")
}

// Leave header to nil by default so we can pass it directly to the Dialer
var header http.Header
header := make(http.Header)
header.Set("User-Agent", state.Options.UserAgent.String)

tags := state.CloneTags()

Expand All @@ -119,7 +119,6 @@ func (*WS) Connect(ctx context.Context, url string, args ...goja.Value) (*WSHTTP
for _, k := range params.Keys() {
switch k {
case "headers":
header = http.Header{}
headersV := params.Get(k)
if goja.IsUndefined(headersV) || goja.IsNull(headersV) {
continue
Expand Down
73 changes: 73 additions & 0 deletions js/modules/k6/ws/ws_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
"github.com/gorilla/websocket"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/guregu/null.v3"

"go.k6.io/k6/js/common"
"go.k6.io/k6/lib"
Expand Down Expand Up @@ -729,3 +730,75 @@ func TestReadPump(t *testing.T) {
// Ensure all close code asserts passed
assert.Equal(t, numAsserts, len(closeCodes))
}

func TestUserAgent(t *testing.T) {
t.Parallel()
tb := httpmultibin.NewHTTPMultiBin(t)
sr := tb.Replacer.Replace

tb.Mux.HandleFunc("/ws-echo-useragent", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// Echo back User-Agent header if it exists
responseHeaders := w.Header().Clone()
if ua := req.Header.Get("User-Agent"); ua != "" {
responseHeaders.Add("Echo-User-Agent", req.Header.Get("User-Agent"))
}

conn, err := (&websocket.Upgrader{}).Upgrade(w, req, responseHeaders)
if err != nil {
t.Fatalf("/ws-echo-useragent cannot upgrade request: %v", err)
return
}

err = conn.Close()
cooliscool marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
t.Logf("error while closing connection in /ws-echo-useragent: %v", err)
return
}
}))

root, err := lib.NewGroup("", nil)
assert.NoError(t, err)

rt := goja.New()
rt.SetFieldNameMapper(common.FieldNameMapper{})
samples := make(chan stats.SampleContainer, 1000)
state := &lib.State{
Group: root,
Dialer: tb.Dialer,
Options: lib.Options{
SystemTags: stats.NewSystemTagSet(
stats.TagURL,
stats.TagProto,
stats.TagStatus,
stats.TagSubproto,
),
UserAgent: null.StringFrom("TestUserAgent"),
},
Samples: samples,
TLSConfig: tb.TLSClientConfig,
BuiltinMetrics: metrics.RegisterBuiltinMetrics(metrics.NewRegistry()),
}

ctx := lib.WithState(context.Background(), state)
ctx = common.WithRuntime(ctx, rt)

err = rt.Set("ws", common.Bind(rt, New(), &ctx))
assert.NoError(t, err)

// websocket handler should echo back User-Agent as Echo-User-Agent for this test to work
_, err = rt.RunString(sr(`
var res = ws.connect("WSBIN_URL/ws-echo-useragent", function(socket){
socket.close()
})
var userAgent = res.headers["Echo-User-Agent"];
if (userAgent == undefined) {
throw new Error("user agent is not echoed back by test server");
}
if (userAgent != "TestUserAgent") {
throw new Error("incorrect user agent: " + userAgent);
}
`))
assert.NoError(t, err)

assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo-useragent"), 101, "")
}