From e336a9e26cd76d2c49d23fe62ab958d86bf2a94d Mon Sep 17 00:00:00 2001 From: Yevhen Vydolob Date: Thu, 14 Dec 2023 10:39:46 +0200 Subject: [PATCH] Fix slice bounds out of range error on remove host entries --- pkg/hosts/hosts.go | 21 ++++++--------------- pkg/hosts/hosts_test.go | 12 ++++++++++++ 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/pkg/hosts/hosts.go b/pkg/hosts/hosts.go index e0af6331..1364572a 100644 --- a/pkg/hosts/hosts.go +++ b/pkg/hosts/hosts.go @@ -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() @@ -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 { diff --git a/pkg/hosts/hosts_test.go b/pkg/hosts/hosts_test.go index f079aa3d..34b7df0d 100644 --- a/pkg/hosts/hosts_test.go +++ b/pkg/hosts/hosts_test.go @@ -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)