pkg/utils: use name+id for hash and extend tests
This commit is contained in:
@ -5,16 +5,15 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// 29 - len('CNI') - 2*len('-')
|
||||
const maxNameLen = 16
|
||||
const MaxChainLength = 29 - len("CNI-")
|
||||
|
||||
// Generates a chain name to be used with iptables.
|
||||
// Ensures that the generated name is less than
|
||||
// 29 chars in length
|
||||
func FormatChainName(name string, id string) string {
|
||||
h := sha512.Sum512([]byte(id))
|
||||
if len(name) > maxNameLen {
|
||||
return fmt.Sprintf("CNI-%s-%x", name[:len(name)-maxNameLen], h[:8])
|
||||
chain := fmt.Sprintf("%x", sha512.Sum512([]byte(name+id)))
|
||||
if len(chain) > MaxChainLength {
|
||||
chain = chain[:MaxChainLength]
|
||||
}
|
||||
return fmt.Sprintf("CNI-%s-%x", name, h[:8])
|
||||
return fmt.Sprintf("CNI-%s", chain)
|
||||
}
|
||||
|
@ -6,13 +6,34 @@ import (
|
||||
)
|
||||
|
||||
var _ = Describe("Utils", func() {
|
||||
It("should format a short name", func() {
|
||||
It("must format a short name", func() {
|
||||
chain := FormatChainName("test", "1234")
|
||||
Expect(chain).To(Equal("CNI-test-d404559f602eab6f"))
|
||||
Expect(len(chain) == 29).To(Equal(true))
|
||||
Expect(chain).To(Equal("CNI-2bbe0c48b91a7d1b8a6753a8b"))
|
||||
})
|
||||
|
||||
It("should truncate a long name", func() {
|
||||
It("must truncate a long name", func() {
|
||||
chain := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
|
||||
Expect(chain).To(Equal("CNI-testalongnamethat-d404559f602eab6f"))
|
||||
Expect(len(chain) == 29).To(Equal(true))
|
||||
Expect(chain).To(Equal("CNI-374f33fe84ab0ed84dcdebe38"))
|
||||
})
|
||||
|
||||
It("must be predictable", func() {
|
||||
chain1 := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
|
||||
chain2 := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
|
||||
Expect(len(chain1) == 29).To(Equal(true))
|
||||
Expect(len(chain2) == 29).To(Equal(true))
|
||||
Expect(chain1).To(Equal(chain2))
|
||||
})
|
||||
|
||||
It("must change when a character changes", func() {
|
||||
chain1 := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
|
||||
chain2 := FormatChainName("testalongnamethatdoesnotmakesense", "1235")
|
||||
Expect(len(chain1) == 29).To(Equal(true))
|
||||
Expect(len(chain2) == 29).To(Equal(true))
|
||||
Expect(chain1).To(Equal("CNI-374f33fe84ab0ed84dcdebe38"))
|
||||
Expect(chain2).NotTo(Equal("CNI-374f33fe84ab0ed84dcdebe38"))
|
||||
Expect(chain1).NotTo(Equal(chain2))
|
||||
})
|
||||
|
||||
})
|
||||
|
Reference in New Issue
Block a user