Skip to content

Commit

Permalink
Fix slice bounds out of range error on remove host entries
Browse files Browse the repository at this point in the history
  • Loading branch information
evidolob authored and praveenkumar committed Dec 14, 2023
1 parent 4d436cd commit e336a9e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
21 changes: 6 additions & 15 deletions pkg/hosts/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,17 +173,6 @@ func (h *Hosts) Remove(hosts []string) error {
return err
}

uniqueHosts := map[string]bool{}
for i := 0; i < len(hosts); i++ {
uniqueHosts[hosts[i]] = true
}

var hostEntries = make(map[string]struct{}, len(uniqueHosts))

for key := range uniqueHosts {
hostEntries[key] = struct{}{}
}

start, end := h.findCrcSection()

h.Lock()
Expand All @@ -196,11 +185,13 @@ func (h *Hosts) Remove(hosts []string) error {
continue
}

for hostIdx, hostname := range line.Hostnames {
if _, ok := hostEntries[hostname]; ok {
h.removeHostFromLine(line, hostIdx, i)
for _, hostToRemove := range hosts {
for hostIdx, hostname := range line.Hostnames {
if hostname == hostToRemove {
h.removeHostFromLine(line, hostIdx, i)
break
}
}

}
}
} else {
Expand Down
12 changes: 12 additions & 0 deletions pkg/hosts/hosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,18 @@ func TestRemoveOnOldHostFile(t *testing.T) {
assert.Equal(t, hostsTemplate, string(content))
}

func TestDeleteSliceBoundErrorOnRemove(t *testing.T) {
dir, err := os.MkdirTemp("", "hosts")
assert.NoError(t, err)
defer os.RemoveAll(dir)

hostsFile := filepath.Join(dir, "hosts")
assert.NoError(t, os.WriteFile(hostsFile, []byte(hostsTemplate+eol()+crcSection("192.168.130.11 api.crc.testing canary-openshift-ingress-canary.apps-crc.testing console-openshift-console.apps-crc.testing default-route-openshift-image-registry.apps-crc.testing downloads-openshift-console.apps-crc.testing oauth-openshift.apps-crc.testing")), 0600))
host := hosts(t, hostsFile)

assert.NoError(t, host.Remove([]string{"api.crc.testing", "oauth-openshift.apps-crc.testing", "console-openshift-console.apps-crc.testing", "downloads-openshift-console.apps-crc.testing", "canary-openshift-ingress-canary.apps-crc.testing", "default-route-openshift-image-registry.apps-crc.testing"}))
}

func hosts(t *testing.T, hostsFile string) Hosts {
config, _ := libhosty.NewHostsFileConfig(hostsFile)
file, err := libhosty.InitWithConfig(config)
Expand Down

0 comments on commit e336a9e

Please sign in to comment.