Skip to content

Commit

Permalink
Prevent panic when slicing end is higher than nodes array size
Browse files Browse the repository at this point in the history
  • Loading branch information
asettouf authored and salem84 committed Feb 3, 2021
1 parent bec53d6 commit f1e77d1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
5 changes: 4 additions & 1 deletion js/modules/k6/html/html.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,10 @@ func (s Selection) Map(v goja.Value) []string {
}

func (s Selection) Slice(start int, def ...int) Selection {
if len(def) > 0 {
// We are forced to check that def[0] is inferior to the length of the array
// otherwise the s.sel.Slice panics. Besides returning the whole array when
// the end value for slicing is superior to the array length is standard in js.
if len(def) > 0 && def[0] < len(s.sel.Nodes) {
return Selection{s.rt, s.sel.Slice(start, def[0]), s.URL}
}

Expand Down
35 changes: 35 additions & 0 deletions js/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1647,6 +1647,41 @@ func TestStuffNotPanicking(t *testing.T) {
}
}

func TestPanicOnSimpleHTML(t *testing.T) {
tb := httpmultibin.NewHTTPMultiBin(t)
defer tb.Cleanup()

r, err := getSimpleRunner(t, "/script.js", tb.Replacer.Replace(`
var parseHTML = require("k6/html").parseHTML;
exports.options = { iterations: 1, vus: 1, vusMax: 1 };
exports.default = function() {
var doc = parseHTML("<html>");
var o = doc.find(".something").slice(0, 4).toArray()
};
`))
require.NoError(t, err)

ch := make(chan stats.SampleContainer, 1000)
initVU, err := r.NewVU(1, ch)
require.NoError(t, err)

ctx, cancel := context.WithCancel(context.Background())
vu := initVU.Activate(&lib.VUActivationParams{RunContext: ctx})
errC := make(chan error)
go func() { errC <- vu.RunOnce() }()

select {
case <-time.After(15 * time.Second):
cancel()
t.Fatal("Test timed out")
case err := <-errC:
cancel()
require.NoError(t, err)
}
}

func TestSystemTags(t *testing.T) {
t.Parallel()
tb := httpmultibin.NewHTTPMultiBin(t)
Expand Down

0 comments on commit f1e77d1

Please sign in to comment.