-
Notifications
You must be signed in to change notification settings - Fork 414
/
identity.go
353 lines (307 loc) · 13.9 KB
/
identity.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
Copyright 2020 The Kubernetes Authors.
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 scope
import (
"context"
"fmt"
"reflect"
"strings"
aadpodid "github.com/Azure/aad-pod-identity/pkg/apis/aadpodidentity"
aadpodv1 "github.com/Azure/aad-pod-identity/pkg/apis/aadpodidentity/v1"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/go-autorest/autorest"
"github.com/jongio/azidext/go/azidext"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
infrav1 "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1"
"sigs.k8s.io/cluster-api-provider-azure/util/identity"
"sigs.k8s.io/cluster-api-provider-azure/util/system"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
clusterctl "sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const azureSecretKey = "clientSecret"
// CredentialsProvider defines the behavior for azure identity based credential providers.
type CredentialsProvider interface {
GetAuthorizer(ctx context.Context, resourceManagerEndpoint, activeDirectoryEndpoint, tokenAudience string) (autorest.Authorizer, error)
GetClientID() string
GetClientSecret(ctx context.Context) (string, error)
GetTenantID() string
}
// AzureCredentialsProvider represents a credential provider with azure cluster identity.
type AzureCredentialsProvider struct {
Client client.Client
Identity *infrav1.AzureClusterIdentity
}
// AzureClusterCredentialsProvider wraps AzureCredentialsProvider with AzureCluster.
type AzureClusterCredentialsProvider struct {
AzureCredentialsProvider
AzureCluster *infrav1.AzureCluster
}
// ManagedControlPlaneCredentialsProvider wraps AzureCredentialsProvider with AzureManagedControlPlane.
type ManagedControlPlaneCredentialsProvider struct {
AzureCredentialsProvider
AzureManagedControlPlane *infrav1.AzureManagedControlPlane
}
var _ CredentialsProvider = (*AzureClusterCredentialsProvider)(nil)
var _ CredentialsProvider = (*ManagedControlPlaneCredentialsProvider)(nil)
// NewAzureClusterCredentialsProvider creates a new AzureClusterCredentialsProvider from the supplied inputs.
func NewAzureClusterCredentialsProvider(ctx context.Context, kubeClient client.Client, azureCluster *infrav1.AzureCluster) (*AzureClusterCredentialsProvider, error) {
if azureCluster.Spec.IdentityRef == nil {
return nil, errors.New("failed to generate new AzureClusterCredentialsProvider from empty identityName")
}
ref := azureCluster.Spec.IdentityRef
// if the namespace isn't specified then assume it's in the same namespace as the AzureCluster
namespace := ref.Namespace
if namespace == "" {
namespace = azureCluster.Namespace
}
identity := &infrav1.AzureClusterIdentity{}
key := client.ObjectKey{Name: ref.Name, Namespace: namespace}
if err := kubeClient.Get(ctx, key, identity); err != nil {
return nil, errors.Errorf("failed to retrieve AzureClusterIdentity external object %q/%q: %v", key.Namespace, key.Name, err)
}
return &AzureClusterCredentialsProvider{
AzureCredentialsProvider{
Client: kubeClient,
Identity: identity,
},
azureCluster,
}, nil
}
// GetAuthorizer returns an Azure authorizer based on the provided azure identity. It delegates to AzureCredentialsProvider with AzureCluster metadata.
func (p *AzureClusterCredentialsProvider) GetAuthorizer(ctx context.Context, resourceManagerEndpoint, activeDirectoryEndpoint, tokenAudience string) (autorest.Authorizer, error) {
return p.AzureCredentialsProvider.GetAuthorizer(ctx, resourceManagerEndpoint, activeDirectoryEndpoint, tokenAudience, p.AzureCluster.ObjectMeta)
}
// NewManagedControlPlaneCredentialsProvider creates a new ManagedControlPlaneCredentialsProvider from the supplied inputs.
func NewManagedControlPlaneCredentialsProvider(ctx context.Context, kubeClient client.Client, managedControlPlane *infrav1.AzureManagedControlPlane) (*ManagedControlPlaneCredentialsProvider, error) {
if managedControlPlane.Spec.IdentityRef == nil {
return nil, errors.New("failed to generate new ManagedControlPlaneCredentialsProvider from empty identityName")
}
ref := managedControlPlane.Spec.IdentityRef
// if the namespace isn't specified then assume it's in the same namespace as the AzureManagedControlPlane
namespace := ref.Namespace
if namespace == "" {
namespace = managedControlPlane.Namespace
}
identity := &infrav1.AzureClusterIdentity{}
key := client.ObjectKey{Name: ref.Name, Namespace: namespace}
if err := kubeClient.Get(ctx, key, identity); err != nil {
return nil, errors.Errorf("failed to retrieve AzureClusterIdentity external object %q/%q: %v", key.Namespace, key.Name, err)
}
return &ManagedControlPlaneCredentialsProvider{
AzureCredentialsProvider{
Client: kubeClient,
Identity: identity,
},
managedControlPlane,
}, nil
}
// GetAuthorizer returns an Azure authorizer based on the provided azure identity. It delegates to AzureCredentialsProvider with AzureManagedControlPlane metadata.
func (p *ManagedControlPlaneCredentialsProvider) GetAuthorizer(ctx context.Context, resourceManagerEndpoint, activeDirectoryEndpoint, tokenAudience string) (autorest.Authorizer, error) {
return p.AzureCredentialsProvider.GetAuthorizer(ctx, resourceManagerEndpoint, activeDirectoryEndpoint, tokenAudience, p.AzureManagedControlPlane.ObjectMeta)
}
// GetAuthorizer returns an Azure authorizer based on the provided azure identity and cluster metadata.
func (p *AzureCredentialsProvider) GetAuthorizer(ctx context.Context, resourceManagerEndpoint, activeDirectoryEndpoint, tokenAudience string, clusterMeta metav1.ObjectMeta) (autorest.Authorizer, error) {
var authErr error
var cred azcore.TokenCredential
switch p.Identity.Spec.Type {
case infrav1.ServicePrincipal, infrav1.ServicePrincipalCertificate, infrav1.UserAssignedMSI:
if err := createAzureIdentityWithBindings(ctx, p.Identity, resourceManagerEndpoint, activeDirectoryEndpoint, clusterMeta, p.Client); err != nil {
return nil, err
}
options := azidentity.ManagedIdentityCredentialOptions{
ID: azidentity.ClientID(p.Identity.Spec.ClientID),
}
cred, authErr = azidentity.NewManagedIdentityCredential(&options)
case infrav1.ManualServicePrincipal:
clientSecret, err := p.GetClientSecret(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to get client secret")
}
options := azidentity.ClientSecretCredentialOptions{
ClientOptions: azcore.ClientOptions{
Cloud: cloud.Configuration{
ActiveDirectoryAuthorityHost: activeDirectoryEndpoint,
Services: map[cloud.ServiceName]cloud.ServiceConfiguration{
cloud.ResourceManager: {
Audience: tokenAudience,
Endpoint: resourceManagerEndpoint,
},
},
},
},
}
cred, authErr = azidentity.NewClientSecretCredential(p.GetTenantID(), p.Identity.Spec.ClientID, clientSecret, &options)
default:
return nil, errors.Errorf("identity type %s not supported", p.Identity.Spec.Type)
}
if authErr != nil {
return nil, errors.Errorf("failed to get token from service principal identity: %v", authErr)
}
// We must use TokenAudience for StackCloud, otherwise we get an
// AADSTS500011 error from the API
scope := tokenAudience
if !strings.HasSuffix(scope, "/.default") {
scope += "/.default"
}
authorizer := azidext.NewTokenCredentialAdapter(cred, []string{scope})
return authorizer, nil
}
// GetClientID returns the Client ID associated with the AzureCredentialsProvider's Identity.
func (p *AzureCredentialsProvider) GetClientID() string {
return p.Identity.Spec.ClientID
}
// GetClientSecret returns the Client Secret associated with the AzureCredentialsProvider's Identity.
// NOTE: this only works if the Identity references a Service Principal Client Secret.
// If using another type of credentials, such a Certificate, we return an empty string.
func (p *AzureCredentialsProvider) GetClientSecret(ctx context.Context) (string, error) {
if p.hasClientSecret() {
secretRef := p.Identity.Spec.ClientSecret
key := types.NamespacedName{
Namespace: secretRef.Namespace,
Name: secretRef.Name,
}
secret := &corev1.Secret{}
if err := p.Client.Get(ctx, key, secret); err != nil {
return "", errors.Wrap(err, "Unable to fetch ClientSecret")
}
return string(secret.Data[azureSecretKey]), nil
}
return "", nil
}
// GetTenantID returns the Tenant ID associated with the AzureCredentialsProvider's Identity.
func (p *AzureCredentialsProvider) GetTenantID() string {
return p.Identity.Spec.TenantID
}
// hasClientSecret returns true if the identity has a Service Principal Client Secret.
// This does not include service principals with certificates or managed identities.
func (p *AzureCredentialsProvider) hasClientSecret() bool {
return p.Identity.Spec.Type == infrav1.ServicePrincipal || p.Identity.Spec.Type == infrav1.ManualServicePrincipal
}
func createAzureIdentityWithBindings(ctx context.Context, azureIdentity *infrav1.AzureClusterIdentity, resourceManagerEndpoint, activeDirectoryEndpoint string, clusterMeta metav1.ObjectMeta,
kubeClient client.Client) error {
azureIdentityType, err := getAzureIdentityType(azureIdentity)
if err != nil {
return err
}
// AzureIdentity and AzureIdentityBinding will no longer have an OwnerRef starting from capz release v0.5.0 because of the following:
// In Kubernetes v1.20+, if the garbage collector detects an invalid cross-namespace ownerReference, or a cluster-scoped dependent with
// an ownerReference referencing a namespaced kind, a warning Event with a reason of OwnerRefInvalidNamespace and an involvedObject
// of the invalid dependent is reported. You can check for that kind of Event by running kubectl get events -A --field-selector=reason=OwnerRefInvalidNamespace.
copiedIdentity := &aadpodv1.AzureIdentity{
TypeMeta: metav1.TypeMeta{
Kind: "AzureIdentity",
APIVersion: "aadpodidentity.k8s.io/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: identity.GetAzureIdentityName(clusterMeta.Name, clusterMeta.Namespace, azureIdentity.Name),
Namespace: system.GetManagerNamespace(),
Annotations: map[string]string{
aadpodv1.BehaviorKey: "namespaced",
},
Labels: map[string]string{
clusterv1.ClusterLabelName: clusterMeta.Name,
infrav1.ClusterLabelNamespace: clusterMeta.Namespace,
clusterctl.ClusterctlMoveHierarchyLabelName: "true",
},
},
Spec: aadpodv1.AzureIdentitySpec{
Type: azureIdentityType,
TenantID: azureIdentity.Spec.TenantID,
ClientID: azureIdentity.Spec.ClientID,
ClientPassword: azureIdentity.Spec.ClientSecret,
ResourceID: azureIdentity.Spec.ResourceID,
ADResourceID: resourceManagerEndpoint,
ADEndpoint: activeDirectoryEndpoint,
},
}
err = kubeClient.Create(ctx, copiedIdentity)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Errorf("failed to create copied AzureIdentity %s in %s: %v", copiedIdentity.Name, system.GetManagerNamespace(), err)
}
azureIdentityBinding := &aadpodv1.AzureIdentityBinding{
TypeMeta: metav1.TypeMeta{
Kind: "AzureIdentityBinding",
APIVersion: "aadpodidentity.k8s.io/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-binding", copiedIdentity.Name),
Namespace: copiedIdentity.Namespace,
Labels: map[string]string{
clusterv1.ClusterLabelName: clusterMeta.Name,
infrav1.ClusterLabelNamespace: clusterMeta.Namespace,
clusterctl.ClusterctlMoveHierarchyLabelName: "true",
},
},
Spec: aadpodv1.AzureIdentityBindingSpec{
AzureIdentity: copiedIdentity.Name,
Selector: infrav1.AzureIdentityBindingSelector, // should be same as selector added on controller
},
}
err = kubeClient.Create(ctx, azureIdentityBinding)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Errorf("failed to create AzureIdentityBinding %s in %s: %v", copiedIdentity.Name, system.GetManagerNamespace(), err)
}
return nil
}
func getAzureIdentityType(identity *infrav1.AzureClusterIdentity) (aadpodv1.IdentityType, error) {
switch identity.Spec.Type {
case infrav1.UserAssignedMSI:
return aadpodv1.UserAssignedMSI, nil
case infrav1.ServicePrincipal:
return aadpodv1.ServicePrincipal, nil
case infrav1.ServicePrincipalCertificate:
return aadpodv1.IdentityType(aadpodid.ServicePrincipalCertificate), nil
}
return -1, errors.New("AzureIdentity does not have a valid type")
}
// IsClusterNamespaceAllowed indicates if the cluster namespace is allowed.
func IsClusterNamespaceAllowed(ctx context.Context, k8sClient client.Client, allowedNamespaces *infrav1.AllowedNamespaces, namespace string) bool {
if allowedNamespaces == nil {
return false
}
// empty value matches with all namespaces
if reflect.DeepEqual(*allowedNamespaces, infrav1.AllowedNamespaces{}) {
return true
}
for _, v := range allowedNamespaces.NamespaceList {
if v == namespace {
return true
}
}
// Check if clusterNamespace is in the namespaces selected by the identity's allowedNamespaces selector.
namespaces := &corev1.NamespaceList{}
selector, err := metav1.LabelSelectorAsSelector(allowedNamespaces.Selector)
if err != nil {
return false
}
// If a Selector has a nil or empty selector, it should match nothing.
if selector.Empty() {
return false
}
if err := k8sClient.List(ctx, namespaces, client.MatchingLabelsSelector{Selector: selector}); err != nil {
return false
}
for _, n := range namespaces.Items {
if n.Name == namespace {
return true
}
}
return false
}