1/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package api
18
19import (
20	"fmt"
21
22	"k8s.io/apimachinery/pkg/runtime"
23)
24
25// Where possible, json tags match the cli argument names.
26// Top level config objects and all values required for proper functioning are not "omitempty".  Any truly optional piece of config is allowed to be omitted.
27
28// Config holds the information needed to build connect to remote kubernetes clusters as a given user
29// IMPORTANT if you add fields to this struct, please update IsConfigEmpty()
30// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
31type Config struct {
32	// Legacy field from pkg/api/types.go TypeMeta.
33	// TODO(jlowdermilk): remove this after eliminating downstream dependencies.
34	// +k8s:conversion-gen=false
35	// +optional
36	Kind string `json:"kind,omitempty"`
37	// Legacy field from pkg/api/types.go TypeMeta.
38	// TODO(jlowdermilk): remove this after eliminating downstream dependencies.
39	// +k8s:conversion-gen=false
40	// +optional
41	APIVersion string `json:"apiVersion,omitempty"`
42	// Preferences holds general information to be use for cli interactions
43	Preferences Preferences `json:"preferences"`
44	// Clusters is a map of referencable names to cluster configs
45	Clusters map[string]*Cluster `json:"clusters"`
46	// AuthInfos is a map of referencable names to user configs
47	AuthInfos map[string]*AuthInfo `json:"users"`
48	// Contexts is a map of referencable names to context configs
49	Contexts map[string]*Context `json:"contexts"`
50	// CurrentContext is the name of the context that you would like to use by default
51	CurrentContext string `json:"current-context"`
52	// Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
53	// +optional
54	Extensions map[string]runtime.Object `json:"extensions,omitempty"`
55}
56
57// IMPORTANT if you add fields to this struct, please update IsConfigEmpty()
58type Preferences struct {
59	// +optional
60	Colors bool `json:"colors,omitempty"`
61	// Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
62	// +optional
63	Extensions map[string]runtime.Object `json:"extensions,omitempty"`
64}
65
66// Cluster contains information about how to communicate with a kubernetes cluster
67type Cluster struct {
68	// LocationOfOrigin indicates where this object came from.  It is used for round tripping config post-merge, but never serialized.
69	// +k8s:conversion-gen=false
70	LocationOfOrigin string
71	// Server is the address of the kubernetes cluster (https://hostname:port).
72	Server string `json:"server"`
73	// TLSServerName is used to check server certificate. If TLSServerName is empty, the hostname used to contact the server is used.
74	// +optional
75	TLSServerName string `json:"tls-server-name,omitempty"`
76	// InsecureSkipTLSVerify skips the validity check for the server's certificate. This will make your HTTPS connections insecure.
77	// +optional
78	InsecureSkipTLSVerify bool `json:"insecure-skip-tls-verify,omitempty"`
79	// CertificateAuthority is the path to a cert file for the certificate authority.
80	// +optional
81	CertificateAuthority string `json:"certificate-authority,omitempty"`
82	// CertificateAuthorityData contains PEM-encoded certificate authority certificates. Overrides CertificateAuthority
83	// +optional
84	CertificateAuthorityData []byte `json:"certificate-authority-data,omitempty"`
85	// ProxyURL is the URL to the proxy to be used for all requests made by this
86	// client. URLs with "http", "https", and "socks5" schemes are supported.  If
87	// this configuration is not provided or the empty string, the client
88	// attempts to construct a proxy configuration from http_proxy and
89	// https_proxy environment variables. If these environment variables are not
90	// set, the client does not attempt to proxy requests.
91	//
92	// socks5 proxying does not currently support spdy streaming endpoints (exec,
93	// attach, port forward).
94	// +optional
95	ProxyURL string `json:"proxy-url,omitempty"`
96	// Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
97	// +optional
98	Extensions map[string]runtime.Object `json:"extensions,omitempty"`
99}
100
101// AuthInfo contains information that describes identity information.  This is use to tell the kubernetes cluster who you are.
102type AuthInfo struct {
103	// LocationOfOrigin indicates where this object came from.  It is used for round tripping config post-merge, but never serialized.
104	// +k8s:conversion-gen=false
105	LocationOfOrigin string
106	// ClientCertificate is the path to a client cert file for TLS.
107	// +optional
108	ClientCertificate string `json:"client-certificate,omitempty"`
109	// ClientCertificateData contains PEM-encoded data from a client cert file for TLS. Overrides ClientCertificate
110	// +optional
111	ClientCertificateData []byte `json:"client-certificate-data,omitempty"`
112	// ClientKey is the path to a client key file for TLS.
113	// +optional
114	ClientKey string `json:"client-key,omitempty"`
115	// ClientKeyData contains PEM-encoded data from a client key file for TLS. Overrides ClientKey
116	// +optional
117	ClientKeyData []byte `json:"client-key-data,omitempty" datapolicy:"security-key"`
118	// Token is the bearer token for authentication to the kubernetes cluster.
119	// +optional
120	Token string `json:"token,omitempty" datapolicy:"token"`
121	// TokenFile is a pointer to a file that contains a bearer token (as described above).  If both Token and TokenFile are present, Token takes precedence.
122	// +optional
123	TokenFile string `json:"tokenFile,omitempty"`
124	// Impersonate is the username to act-as.
125	// +optional
126	Impersonate string `json:"act-as,omitempty"`
127	// ImpersonateGroups is the groups to imperonate.
128	// +optional
129	ImpersonateGroups []string `json:"act-as-groups,omitempty"`
130	// ImpersonateUserExtra contains additional information for impersonated user.
131	// +optional
132	ImpersonateUserExtra map[string][]string `json:"act-as-user-extra,omitempty"`
133	// Username is the username for basic authentication to the kubernetes cluster.
134	// +optional
135	Username string `json:"username,omitempty"`
136	// Password is the password for basic authentication to the kubernetes cluster.
137	// +optional
138	Password string `json:"password,omitempty" datapolicy:"password"`
139	// AuthProvider specifies a custom authentication plugin for the kubernetes cluster.
140	// +optional
141	AuthProvider *AuthProviderConfig `json:"auth-provider,omitempty"`
142	// Exec specifies a custom exec-based authentication plugin for the kubernetes cluster.
143	// +optional
144	Exec *ExecConfig `json:"exec,omitempty"`
145	// Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
146	// +optional
147	Extensions map[string]runtime.Object `json:"extensions,omitempty"`
148}
149
150// Context is a tuple of references to a cluster (how do I communicate with a kubernetes cluster), a user (how do I identify myself), and a namespace (what subset of resources do I want to work with)
151type Context struct {
152	// LocationOfOrigin indicates where this object came from.  It is used for round tripping config post-merge, but never serialized.
153	// +k8s:conversion-gen=false
154	LocationOfOrigin string
155	// Cluster is the name of the cluster for this context
156	Cluster string `json:"cluster"`
157	// AuthInfo is the name of the authInfo for this context
158	AuthInfo string `json:"user"`
159	// Namespace is the default namespace to use on unspecified requests
160	// +optional
161	Namespace string `json:"namespace,omitempty"`
162	// Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields
163	// +optional
164	Extensions map[string]runtime.Object `json:"extensions,omitempty"`
165}
166
167// AuthProviderConfig holds the configuration for a specified auth provider.
168type AuthProviderConfig struct {
169	Name string `json:"name"`
170	// +optional
171	Config map[string]string `json:"config,omitempty"`
172}
173
174var _ fmt.Stringer = new(AuthProviderConfig)
175var _ fmt.GoStringer = new(AuthProviderConfig)
176
177// GoString implements fmt.GoStringer and sanitizes sensitive fields of
178// AuthProviderConfig to prevent accidental leaking via logs.
179func (c AuthProviderConfig) GoString() string {
180	return c.String()
181}
182
183// String implements fmt.Stringer and sanitizes sensitive fields of
184// AuthProviderConfig to prevent accidental leaking via logs.
185func (c AuthProviderConfig) String() string {
186	cfg := "<nil>"
187	if c.Config != nil {
188		cfg = "--- REDACTED ---"
189	}
190	return fmt.Sprintf("api.AuthProviderConfig{Name: %q, Config: map[string]string{%s}}", c.Name, cfg)
191}
192
193// ExecConfig specifies a command to provide client credentials. The command is exec'd
194// and outputs structured stdout holding credentials.
195//
196// See the client.authentication.k8s.io API group for specifications of the exact input
197// and output format
198type ExecConfig struct {
199	// Command to execute.
200	Command string `json:"command"`
201	// Arguments to pass to the command when executing it.
202	// +optional
203	Args []string `json:"args"`
204	// Env defines additional environment variables to expose to the process. These
205	// are unioned with the host's environment, as well as variables client-go uses
206	// to pass argument to the plugin.
207	// +optional
208	Env []ExecEnvVar `json:"env"`
209
210	// Preferred input version of the ExecInfo. The returned ExecCredentials MUST use
211	// the same encoding version as the input.
212	APIVersion string `json:"apiVersion,omitempty"`
213
214	// This text is shown to the user when the executable doesn't seem to be
215	// present. For example, `brew install foo-cli` might be a good InstallHint for
216	// foo-cli on Mac OS systems.
217	InstallHint string `json:"installHint,omitempty"`
218
219	// ProvideClusterInfo determines whether or not to provide cluster information,
220	// which could potentially contain very large CA data, to this exec plugin as a
221	// part of the KUBERNETES_EXEC_INFO environment variable. By default, it is set
222	// to false. Package k8s.io/client-go/tools/auth/exec provides helper methods for
223	// reading this environment variable.
224	ProvideClusterInfo bool `json:"provideClusterInfo"`
225
226	// Config holds additional config data that is specific to the exec
227	// plugin with regards to the cluster being authenticated to.
228	//
229	// This data is sourced from the clientcmd Cluster object's extensions[exec] field:
230	//
231	// clusters:
232	// - name: my-cluster
233	//   cluster:
234	//     ...
235	//     extensions:
236	//     - name: client.authentication.k8s.io/exec  # reserved extension name for per cluster exec config
237	//       extension:
238	//         audience: 06e3fbd18de8  # arbitrary config
239	//
240	// In some environments, the user config may be exactly the same across many clusters
241	// (i.e. call this exec plugin) minus some details that are specific to each cluster
242	// such as the audience.  This field allows the per cluster config to be directly
243	// specified with the cluster info.  Using this field to store secret data is not
244	// recommended as one of the prime benefits of exec plugins is that no secrets need
245	// to be stored directly in the kubeconfig.
246	// +k8s:conversion-gen=false
247	Config runtime.Object
248}
249
250var _ fmt.Stringer = new(ExecConfig)
251var _ fmt.GoStringer = new(ExecConfig)
252
253// GoString implements fmt.GoStringer and sanitizes sensitive fields of
254// ExecConfig to prevent accidental leaking via logs.
255func (c ExecConfig) GoString() string {
256	return c.String()
257}
258
259// String implements fmt.Stringer and sanitizes sensitive fields of ExecConfig
260// to prevent accidental leaking via logs.
261func (c ExecConfig) String() string {
262	var args []string
263	if len(c.Args) > 0 {
264		args = []string{"--- REDACTED ---"}
265	}
266	env := "[]ExecEnvVar(nil)"
267	if len(c.Env) > 0 {
268		env = "[]ExecEnvVar{--- REDACTED ---}"
269	}
270	config := "runtime.Object(nil)"
271	if c.Config != nil {
272		config = "runtime.Object(--- REDACTED ---)"
273	}
274	return fmt.Sprintf("api.ExecConfig{Command: %q, Args: %#v, Env: %s, APIVersion: %q, ProvideClusterInfo: %t, Config: %s}", c.Command, args, env, c.APIVersion, c.ProvideClusterInfo, config)
275}
276
277// ExecEnvVar is used for setting environment variables when executing an exec-based
278// credential plugin.
279type ExecEnvVar struct {
280	Name  string `json:"name"`
281	Value string `json:"value"`
282}
283
284// NewConfig is a convenience function that returns a new Config object with non-nil maps
285func NewConfig() *Config {
286	return &Config{
287		Preferences: *NewPreferences(),
288		Clusters:    make(map[string]*Cluster),
289		AuthInfos:   make(map[string]*AuthInfo),
290		Contexts:    make(map[string]*Context),
291		Extensions:  make(map[string]runtime.Object),
292	}
293}
294
295// NewContext is a convenience function that returns a new Context
296// object with non-nil maps
297func NewContext() *Context {
298	return &Context{Extensions: make(map[string]runtime.Object)}
299}
300
301// NewCluster is a convenience function that returns a new Cluster
302// object with non-nil maps
303func NewCluster() *Cluster {
304	return &Cluster{Extensions: make(map[string]runtime.Object)}
305}
306
307// NewAuthInfo is a convenience function that returns a new AuthInfo
308// object with non-nil maps
309func NewAuthInfo() *AuthInfo {
310	return &AuthInfo{
311		Extensions:           make(map[string]runtime.Object),
312		ImpersonateUserExtra: make(map[string][]string),
313	}
314}
315
316// NewPreferences is a convenience function that returns a new
317// Preferences object with non-nil maps
318func NewPreferences() *Preferences {
319	return &Preferences{Extensions: make(map[string]runtime.Object)}
320}
321