Fix potential issue, slice bounds out of range error

This commit is contained in:
Tomofumi Hayashi
2023-05-03 03:19:24 +09:00
parent b05ff2db4e
commit da704f8f63
2 changed files with 24 additions and 3 deletions

View File

@@ -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 {
@@ -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) {

View File

@@ -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"}]`))
})
})