diff --git a/pkg/commands/helpers/kubectl_auth.go b/pkg/commands/helpers/kubectl_auth.go index bbadf2d2ce..f40f742348 100644 --- a/pkg/commands/helpers/kubectl_auth.go +++ b/pkg/commands/helpers/kubectl_auth.go @@ -24,6 +24,7 @@ import ( "encoding/json" "fmt" "io" + "math/big" "os" "os/user" "path/filepath" @@ -174,7 +175,11 @@ func cacheFilePath(kopsStateStore string, clusterName string) string { b.WriteString(clusterName) b.WriteByte(0) - hash := fmt.Sprintf("%x", sha256.New().Sum(b.Bytes())) + var i big.Int + hb := sha256.Sum224(b.Bytes()) + i.SetBytes(hb[:]) + hash := i.Text(62) + sanitizedName := strings.Map(func(r rune) rune { switch { case r >= 'a' && r <= 'z': @@ -187,6 +192,9 @@ func cacheFilePath(kopsStateStore string, clusterName string) string { return '_' } }, clusterName) + if len(sanitizedName) > 32 { + sanitizedName = sanitizedName[:32] + } return filepath.Join(homedir.HomeDir(), ".kube", "cache", "kops-authentication", sanitizedName+"_"+hash) } diff --git a/pkg/commands/helpers/kubectl_auth_test.go b/pkg/commands/helpers/kubectl_auth_test.go new file mode 100644 index 0000000000..34950d0e22 --- /dev/null +++ b/pkg/commands/helpers/kubectl_auth_test.go @@ -0,0 +1,44 @@ +/* +Copyright 2023 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package helpers + +import ( + "path" + "testing" +) + +func Test_cacheFilePath(t *testing.T) { + inputs := []struct { + kopsStateStore string + clusterName string + }{ + { + kopsStateStore: "s3://abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk", + clusterName: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcde." + + "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk." + + "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk." + + "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.com", + }, + } + + output1 := cacheFilePath(inputs[0].kopsStateStore, inputs[0].clusterName) + _, file := path.Split(output1) + + if len(file) > 71 { + t.Errorf("cacheFilePath() got %v, too long(%v)", output1, len(file)) + } +}