-
Notifications
You must be signed in to change notification settings - Fork 458
/
admin_kubeconfig.go
191 lines (155 loc) · 6.33 KB
/
admin_kubeconfig.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/*
Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
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 storage
import (
"context"
"encoding/json"
"fmt"
"net/url"
"time"
authenticationapi "github.com/gardener/gardener/pkg/apis/authentication"
authenticationapiv1alpha1 "github.com/gardener/gardener/pkg/apis/authentication/v1alpha1"
authenticationvalidation "github.com/gardener/gardener/pkg/apis/authentication/validation"
"github.com/gardener/gardener/pkg/apis/core"
gardencorev1alpha1 "github.com/gardener/gardener/pkg/apis/core/v1alpha1"
gardencorev1alpha1helper "github.com/gardener/gardener/pkg/apis/core/v1alpha1/helper"
v1beta1constants "github.com/gardener/gardener/pkg/apis/core/v1beta1/constants"
"github.com/gardener/gardener/pkg/client/kubernetes"
"github.com/gardener/gardener/pkg/utils/secrets"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/clock"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/apiserver/pkg/authentication/user"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
)
// AdminKubeconfigREST implements a RESTStorage for shoots/adminkubeconfig.
type AdminKubeconfigREST struct {
shootStateStorage getter
shootStorage getter
clock clock.Clock
maxExpirationSeconds int64
}
var (
_ = rest.NamedCreater(&AdminKubeconfigREST{})
_ = rest.GroupVersionKindProvider(&AdminKubeconfigREST{})
gvk = schema.GroupVersionKind{
Group: authenticationapiv1alpha1.SchemeGroupVersion.Group,
Version: authenticationapiv1alpha1.SchemeGroupVersion.Version,
Kind: "AdminKubeconfigRequest",
}
)
// New returns and instance of AdminKubeconfigRequest
func (r *AdminKubeconfigREST) New() runtime.Object {
return &authenticationapi.AdminKubeconfigRequest{}
}
// Create returns a AdminKubeconfigRequest with kubeconfig based on
// - shoot's advertised addresses
// - shoot's certificate authority
// - user making the request
func (r *AdminKubeconfigREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, _ *metav1.CreateOptions) (runtime.Object, error) {
if createValidation != nil {
if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err
}
}
out := obj.(*authenticationapi.AdminKubeconfigRequest)
if errs := authenticationvalidation.ValidateAdminKubeconfigRequest(out); len(errs) != 0 {
return nil, errors.NewInvalid(gvk.GroupKind(), "", errs)
}
userInfo, ok := genericapirequest.UserFrom(ctx)
if !ok {
return nil, errors.NewBadRequest("no user in context")
}
shootStateObj, err := r.shootStateStorage.Get(ctx, name, &metav1.GetOptions{})
if err != nil {
return nil, err
}
shootState := &gardencorev1alpha1.ShootState{}
err = kubernetes.GardenScheme.Convert(shootStateObj, shootState, nil)
if err != nil {
return nil, err
}
shootObj, err := r.shootStorage.Get(ctx, name, &metav1.GetOptions{})
if err != nil {
return nil, err
}
shoot, ok := shootObj.(*core.Shoot)
if !ok {
return nil, errors.NewInternalError(fmt.Errorf("cannot convert to *core.Shoot object - got type %T", shootObj))
}
if len(shoot.Status.AdvertisedAddresses) == 0 {
fieldErr := field.Invalid(field.NewPath("status", "status"), shoot.Status.AdvertisedAddresses, "no kube-apiserver advertised addresses in Shoot .status.advertisedAddresses")
return nil, errors.NewInvalid(gvk.GroupKind(), shoot.Name, field.ErrorList{fieldErr})
}
resourceDataList := gardencorev1alpha1helper.GardenerResourceDataList(shootState.Spec.Gardener)
ca := resourceDataList.Get(v1beta1constants.SecretNameCACluster)
if ca == nil {
return nil, errors.NewInternalError(fmt.Errorf("certificate authority not yet provisioned"))
}
data := make(map[string][]byte)
if err := json.Unmarshal(ca.Data.Raw, &data); err != nil {
return nil, errors.NewInternalError(err)
}
keyPrivateKey, keyCertificate := secrets.DataKeyPrivateKeyCA, secrets.DataKeyCertificateCA
if ca.Type == "certificate" {
keyPrivateKey, keyCertificate = "privateKey", "certificate"
}
caCert, err := secrets.LoadCertificate("", data[keyPrivateKey], data[keyCertificate])
if err != nil {
return nil, errors.NewInternalError(err)
}
if r.maxExpirationSeconds > 0 && out.Spec.ExpirationSeconds > r.maxExpirationSeconds {
out.Spec.ExpirationSeconds = r.maxExpirationSeconds
}
validity := time.Duration(out.Spec.ExpirationSeconds) * time.Second
authName := fmt.Sprintf("%s--%s", shoot.Namespace, shoot.Name)
cpsc := secrets.ControlPlaneSecretConfig{
Name: authName,
CertificateSecretConfig: &secrets.CertificateSecretConfig{
CommonName: userInfo.GetName(),
Organization: []string{user.SystemPrivilegedGroup},
CertType: secrets.ClientCert,
Validity: &validity,
SigningCA: caCert,
Clock: r.clock,
},
}
for _, address := range shoot.Status.AdvertisedAddresses {
u, err := url.Parse(address.URL)
if err != nil {
return nil, err
}
cpsc.KubeConfigRequests = append(cpsc.KubeConfigRequests, secrets.KubeConfigRequest{
ClusterName: fmt.Sprintf("%s-%s", authName, address.Name),
APIServerHost: u.Host,
})
}
cp, err := cpsc.GenerateControlPlane()
if err != nil {
return nil, err
}
out.Status.Kubeconfig = cp.Kubeconfig
out.Status.ExpirationTimestamp = metav1.Time{Time: cp.Certificate.Certificate.NotAfter}
return out, nil
}
// GroupVersionKind returns authentication.gardener.cloud/v1alpha1 for AdminKubeconfigRequest.
func (r *AdminKubeconfigREST) GroupVersionKind(schema.GroupVersion) schema.GroupVersionKind {
return gvk
}
type getter interface {
Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)
}