1/*
2Copyright 2020 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 rest
18
19import (
20	"fmt"
21	"net/http"
22	"net/url"
23
24	"k8s.io/client-go/pkg/apis/clientauthentication"
25	clientauthenticationapi "k8s.io/client-go/pkg/apis/clientauthentication"
26)
27
28// This file contains Config logic related to exec credential plugins.
29
30// ConfigToExecCluster creates a clientauthenticationapi.Cluster with the corresponding fields from
31// the provided Config.
32func ConfigToExecCluster(config *Config) (*clientauthenticationapi.Cluster, error) {
33	caData, err := dataFromSliceOrFile(config.CAData, config.CAFile)
34	if err != nil {
35		return nil, fmt.Errorf("failed to load CA bundle for execProvider: %v", err)
36	}
37
38	var proxyURL string
39	if config.Proxy != nil {
40		req, err := http.NewRequest("", config.Host, nil)
41		if err != nil {
42			return nil, fmt.Errorf("failed to create proxy URL request for execProvider: %w", err)
43		}
44		url, err := config.Proxy(req)
45		if err != nil {
46			return nil, fmt.Errorf("failed to get proxy URL for execProvider: %w", err)
47		}
48		if url != nil {
49			proxyURL = url.String()
50		}
51	}
52
53	return &clientauthentication.Cluster{
54		Server:                   config.Host,
55		TLSServerName:            config.ServerName,
56		InsecureSkipTLSVerify:    config.Insecure,
57		CertificateAuthorityData: caData,
58		ProxyURL:                 proxyURL,
59		Config:                   config.ExecProvider.Config,
60	}, nil
61}
62
63// ExecClusterToConfig creates a Config with the corresponding fields from the provided
64// clientauthenticationapi.Cluster. The returned Config will be anonymous (i.e., it will not have
65// any authentication-related fields set).
66func ExecClusterToConfig(cluster *clientauthentication.Cluster) (*Config, error) {
67	var proxy func(*http.Request) (*url.URL, error)
68	if cluster.ProxyURL != "" {
69		proxyURL, err := url.Parse(cluster.ProxyURL)
70		if err != nil {
71			return nil, fmt.Errorf("cannot parse proxy URL: %w", err)
72		}
73		proxy = http.ProxyURL(proxyURL)
74	}
75
76	return &Config{
77		Host: cluster.Server,
78		TLSClientConfig: TLSClientConfig{
79			Insecure:   cluster.InsecureSkipTLSVerify,
80			ServerName: cluster.TLSServerName,
81			CAData:     cluster.CertificateAuthorityData,
82		},
83		Proxy: proxy,
84	}, nil
85}
86