...
1
16
17
18 package exec
19
20 import (
21 "errors"
22 "fmt"
23 "os"
24
25 "k8s.io/apimachinery/pkg/runtime"
26 "k8s.io/apimachinery/pkg/runtime/schema"
27 "k8s.io/apimachinery/pkg/runtime/serializer"
28 "k8s.io/client-go/pkg/apis/clientauthentication"
29 "k8s.io/client-go/pkg/apis/clientauthentication/install"
30 "k8s.io/client-go/rest"
31 )
32
33 const execInfoEnv = "KUBERNETES_EXEC_INFO"
34
35 var scheme = runtime.NewScheme()
36 var codecs = serializer.NewCodecFactory(scheme)
37
38 func init() {
39 install.Install(scheme)
40 }
41
42
43
44
45
46
47 func LoadExecCredentialFromEnv() (runtime.Object, *rest.Config, error) {
48 env := os.Getenv(execInfoEnv)
49 if env == "" {
50 return nil, nil, errors.New("KUBERNETES_EXEC_INFO env var is unset or empty")
51 }
52 return LoadExecCredential([]byte(env))
53 }
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69 func LoadExecCredential(data []byte) (runtime.Object, *rest.Config, error) {
70 obj, gvk, err := codecs.UniversalDeserializer().Decode(data, nil, nil)
71 if err != nil {
72 return nil, nil, fmt.Errorf("decode: %w", err)
73 }
74
75 expectedGK := schema.GroupKind{
76 Group: clientauthentication.SchemeGroupVersion.Group,
77 Kind: "ExecCredential",
78 }
79 if gvk.GroupKind() != expectedGK {
80 return nil, nil, fmt.Errorf(
81 "invalid group/kind: wanted %s, got %s",
82 expectedGK.String(),
83 gvk.GroupKind().String(),
84 )
85 }
86
87
88
89 var execCredential clientauthentication.ExecCredential
90 if err := scheme.Convert(obj, &execCredential, nil); err != nil {
91 return nil, nil, fmt.Errorf("cannot convert to ExecCredential: %w", err)
92 }
93
94 if execCredential.Spec.Cluster == nil {
95 return nil, nil, errors.New("ExecCredential does not contain cluster information")
96 }
97
98 restConfig, err := rest.ExecClusterToConfig(execCredential.Spec.Cluster)
99 if err != nil {
100 return nil, nil, fmt.Errorf("cannot create rest.Config: %w", err)
101 }
102
103 return obj, restConfig, nil
104 }
105
View as plain text