blob: 8d249cb54b4212803b8dfe7cfe6580ff73730b31 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2018 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 options
18
19import (
20 "crypto/tls"
21 "fmt"
22
23 "github.com/pborman/uuid"
24
25 "k8s.io/apiserver/pkg/server"
26 certutil "k8s.io/client-go/util/cert"
27)
28
29type SecureServingOptionsWithLoopback struct {
30 *SecureServingOptions
31}
32
33func WithLoopback(o *SecureServingOptions) *SecureServingOptionsWithLoopback {
34 return &SecureServingOptionsWithLoopback{o}
35}
36
37// ApplyTo fills up serving information in the server configuration.
38func (s *SecureServingOptionsWithLoopback) ApplyTo(c *server.Config) error {
39 if s == nil || s.SecureServingOptions == nil {
40 return nil
41 }
42
43 if err := s.SecureServingOptions.ApplyTo(&c.SecureServing); err != nil {
44 return err
45 }
46
47 if c.SecureServing == nil {
48 return nil
49 }
50
51 c.ReadWritePort = s.BindPort
52
53 // create self-signed cert+key with the fake server.LoopbackClientServerNameOverride and
54 // let the server return it when the loopback client connects.
55 certPem, keyPem, err := certutil.GenerateSelfSignedCertKey(server.LoopbackClientServerNameOverride, nil, nil)
56 if err != nil {
57 return fmt.Errorf("failed to generate self-signed certificate for loopback connection: %v", err)
58 }
59 tlsCert, err := tls.X509KeyPair(certPem, keyPem)
60 if err != nil {
61 return fmt.Errorf("failed to generate self-signed certificate for loopback connection: %v", err)
62 }
63
64 secureLoopbackClientConfig, err := c.SecureServing.NewLoopbackClientConfig(uuid.NewRandom().String(), certPem)
65 switch {
66 // if we failed and there's no fallback loopback client config, we need to fail
67 case err != nil && c.LoopbackClientConfig == nil:
68 return err
69
70 // if we failed, but we already have a fallback loopback client config (usually insecure), allow it
71 case err != nil && c.LoopbackClientConfig != nil:
72
73 default:
74 c.LoopbackClientConfig = secureLoopbackClientConfig
75 c.SecureServing.SNICerts[server.LoopbackClientServerNameOverride] = &tlsCert
76 }
77
78 return nil
79}