Skip to content

Commit

Permalink
Fix potential issue, slice bounds out of range error
Browse files Browse the repository at this point in the history
  • Loading branch information
s1061123 committed May 2, 2023
1 parent b05ff2d commit da704f8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
7 changes: 4 additions & 3 deletions pkg/netutils/netutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ func deleteDefaultGWCacheBytes(cacheFile []byte, ipv4, ipv6 bool) ([]byte, error
}

func deleteDefaultGWResultRoutes(routes []interface{}, dstGW string) ([]interface{}, error) {
var newRoutes []interface{}
for i, r := range routes {
route, ok := r.(map[string]interface{})
if !ok {
Expand All @@ -150,12 +151,12 @@ func deleteDefaultGWResultRoutes(routes []interface{}, dstGW string) ([]interfac
if !ok {
return nil, fmt.Errorf("wrong dst format: %v", route["dst"])
}
if dst == dstGW {
routes = append(routes[:i], routes[i+1:]...)
if dst != dstGW {
newRoutes = append(newRoutes, routes[i])
}
}
}
return routes, nil
return newRoutes, nil
}

func deleteDefaultGWResult(result map[string]interface{}, ipv4, ipv6 bool) (map[string]interface{}, error) {
Expand Down
20 changes: 20 additions & 0 deletions pkg/netutils/netutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1421,3 +1421,23 @@ var _ = Describe("netutil cnicache function testing", func() {

})
})

var _ = Describe("other function unit testing", func() {
It("deleteDefaultGWResultRoutes with invalid config", func() {
cniRouteConfig := []byte(`[
{ "dst": "0.0.0.0/0", "gw": "10.1.1.1" },
{ "dst": "10.1.1.0/24" },
{ "dst": "0.0.0.0/0", "gw": "10.1.1.1" }
]`)

var routes []interface{}
err := json.Unmarshal(cniRouteConfig, &routes)
Expect(err).NotTo(HaveOccurred())

newRoute, err := deleteDefaultGWResultRoutes(routes, "0.0.0.0/0")
Expect(err).NotTo(HaveOccurred())
routeJSON, err := json.Marshal(newRoute)
Expect(err).NotTo(HaveOccurred())
Expect(routeJSON).Should(MatchJSON(`[{"dst":"10.1.1.0/24"}]`))
})
})

0 comments on commit da704f8

Please sign in to comment.