Skip to content

Commit

Permalink
handle Entra auth for ASO API managed clusters
Browse files Browse the repository at this point in the history
  • Loading branch information
nojnhuh committed Nov 15, 2024
1 parent 9e02ebb commit dd9b8dc
Show file tree
Hide file tree
Showing 6 changed files with 1,100 additions and 8 deletions.
221 changes: 221 additions & 0 deletions controllers/aso_credential_cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
/*
Copyright 2024 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 controllers

import (
"context"
"os"
"strconv"

"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/azure-sdk-for-go/sdk/tracing/azotel"
asoannotations "github.com/Azure/azure-service-operator/v2/pkg/common/annotations"
"github.com/Azure/azure-service-operator/v2/pkg/common/config"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"

"sigs.k8s.io/cluster-api-provider-azure/azure"
"sigs.k8s.io/cluster-api-provider-azure/pkg/ot"
"sigs.k8s.io/cluster-api-provider-azure/util/tele"
)

const (
asoNamespaceSecretName = "aso-credential" //nolint:gosec // This is not a secret, only a reference to one.
asoGlobalSecretName = "aso-controller-settings"
asoNamespaceAnnotation = "serviceoperator.azure.com/operator-namespace"
)

// ASOCredentialCache caches credentials defined for ASO resources.
type ASOCredentialCache interface {
authTokenForASOResource(context.Context, client.Object) (azcore.TokenCredential, error)
}

type asoCredentialCache struct {
cache azure.CredentialCache
client client.Client
}

// NewASOCredentialCache creates a new ASOCredentialCache.
func NewASOCredentialCache(cache azure.CredentialCache, client client.Client) ASOCredentialCache {
return &asoCredentialCache{
cache: cache,
client: client,
}

Check warning on line 59 in controllers/aso_credential_cache.go

View check run for this annotation

Codecov / codecov/patch

controllers/aso_credential_cache.go#L55-L59

Added lines #L55 - L59 were not covered by tests
}

func (c *asoCredentialCache) authTokenForASOResource(ctx context.Context, obj client.Object) (azcore.TokenCredential, error) {
ctx, _, done := tele.StartSpanWithLogger(ctx, "controllers.asoCredentialCache.authTokenForASOResource")
defer done()

clientOpts, err := c.clientOptsForASOResource(ctx, obj)
if err != nil {
return nil, err
}

Check warning on line 69 in controllers/aso_credential_cache.go

View check run for this annotation

Codecov / codecov/patch

controllers/aso_credential_cache.go#L68-L69

Added lines #L68 - L69 were not covered by tests

secretName := asoNamespaceSecretName
if resourceSecretName := obj.GetAnnotations()[asoannotations.PerResourceSecret]; resourceSecretName != "" {
secretName = resourceSecretName
}
secret := &corev1.Secret{}
err = c.client.Get(ctx, client.ObjectKey{Namespace: obj.GetNamespace(), Name: secretName}, secret)
if client.IgnoreNotFound(err) != nil {
return nil, err
}

Check warning on line 79 in controllers/aso_credential_cache.go

View check run for this annotation

Codecov / codecov/patch

controllers/aso_credential_cache.go#L78-L79

Added lines #L78 - L79 were not covered by tests
if err == nil {
return c.authTokenForScopedASOSecret(secret, clientOpts)
}

secretNamespace := obj.GetAnnotations()[asoNamespaceAnnotation]
err = c.client.Get(ctx, client.ObjectKey{Namespace: secretNamespace, Name: asoGlobalSecretName}, secret)
if err != nil {
return nil, err
}

return c.authTokenForGlobalASOSecret(secret, clientOpts)
}

func (c *asoCredentialCache) clientOptsForASOResource(ctx context.Context, obj client.Object) (azcore.ClientOptions, error) {
secretNamespace := obj.GetAnnotations()[asoNamespaceAnnotation]
secret := &corev1.Secret{}
err := c.client.Get(ctx, client.ObjectKey{Namespace: secretNamespace, Name: asoGlobalSecretName}, secret)
if client.IgnoreNotFound(err) != nil {
return azcore.ClientOptions{}, err
}

Check warning on line 99 in controllers/aso_credential_cache.go

View check run for this annotation

Codecov / codecov/patch

controllers/aso_credential_cache.go#L98-L99

Added lines #L98 - L99 were not covered by tests

otelTP, err := ot.OTLPTracerProvider(ctx)
if err != nil {
return azcore.ClientOptions{}, err
}

Check warning on line 104 in controllers/aso_credential_cache.go

View check run for this annotation

Codecov / codecov/patch

controllers/aso_credential_cache.go#L103-L104

Added lines #L103 - L104 were not covered by tests

opts := azcore.ClientOptions{
TracingProvider: azotel.NewTracingProvider(otelTP, nil),
Cloud: cloud.Configuration{
ActiveDirectoryAuthorityHost: string(secret.Data[config.AzureAuthorityHost]),
},
}

if len(secret.Data[config.ResourceManagerAudience]) > 0 ||
len(secret.Data[config.ResourceManagerEndpoint]) > 0 {
opts.Cloud.Services = map[cloud.ServiceName]cloud.ServiceConfiguration{
cloud.ResourceManager: {
Audience: string(secret.Data[config.ResourceManagerAudience]),
Endpoint: string(secret.Data[config.ResourceManagerEndpoint]),
},
}
}

return opts, nil
}

func (c *asoCredentialCache) authTokenForScopedASOSecret(secret *corev1.Secret, clientOpts azcore.ClientOptions) (azcore.TokenCredential, error) {
d := secret.Data

if _, hasSecret := d[config.AzureClientSecret]; hasSecret {
return c.cache.GetOrStoreClientSecret(
string(d[config.AzureTenantID]),
string(d[config.AzureClientID]),
string(d[config.AzureClientSecret]),
&azidentity.ClientSecretCredentialOptions{
ClientOptions: clientOpts,
},
)
}

if _, hasCert := d[config.AzureClientCertificate]; hasCert {
return c.cache.GetOrStoreClientCert(
string(d[config.AzureTenantID]),
string(d[config.AzureClientID]),
d[config.AzureClientCertificate],
d[config.AzureClientCertificatePassword],
&azidentity.ClientCertificateCredentialOptions{
ClientOptions: clientOpts,
},
)
}

if authMode := d[config.AuthMode]; config.AuthModeOption(authMode) == config.PodIdentityAuthMode {
return c.cache.GetOrStoreManagedIdentity(
&azidentity.ManagedIdentityCredentialOptions{
ClientOptions: clientOpts,
ID: azidentity.ClientID(d[config.AzureClientID]),
},
)
}

return c.cache.GetOrStoreWorkloadIdentity(
&azidentity.WorkloadIdentityCredentialOptions{
ClientOptions: clientOpts,
TenantID: string(d[config.AzureTenantID]),
ClientID: string(d[config.AzureClientID]),
TokenFilePath: federatedTokenFilePath(),
},
)
}

func (c *asoCredentialCache) authTokenForGlobalASOSecret(secret *corev1.Secret, clientOpts azcore.ClientOptions) (azcore.TokenCredential, error) {
d := secret.Data

if workloadID, _ := strconv.ParseBool(string(d[config.UseWorkloadIdentityAuth])); workloadID {
return c.cache.GetOrStoreWorkloadIdentity(
&azidentity.WorkloadIdentityCredentialOptions{
ClientOptions: clientOpts,
TenantID: string(d[config.AzureTenantID]),
ClientID: string(d[config.AzureClientID]),
TokenFilePath: federatedTokenFilePath(),
},
)
}

if _, hasSecret := d[config.AzureClientSecret]; hasSecret {
return c.cache.GetOrStoreClientSecret(
string(d[config.AzureTenantID]),
string(d[config.AzureClientID]),
string(d[config.AzureClientSecret]),
&azidentity.ClientSecretCredentialOptions{
ClientOptions: clientOpts,
},
)
}

if _, hasCert := d[config.AzureClientCertificate]; hasCert {
return c.cache.GetOrStoreClientCert(
string(d[config.AzureTenantID]),
string(d[config.AzureClientID]),
d[config.AzureClientCertificate],
d[config.AzureClientCertificatePassword],
&azidentity.ClientCertificateCredentialOptions{
ClientOptions: clientOpts,
},
)
}

return c.cache.GetOrStoreManagedIdentity(
&azidentity.ManagedIdentityCredentialOptions{
ClientOptions: clientOpts,
ID: azidentity.ClientID(d[config.AzureClientID]),
},
)
}

func federatedTokenFilePath() string {
if env, ok := os.LookupEnv("AZURE_FEDERATED_TOKEN_FILE"); ok {
return env
}

Check warning on line 219 in controllers/aso_credential_cache.go

View check run for this annotation

Codecov / codecov/patch

controllers/aso_credential_cache.go#L218-L219

Added lines #L218 - L219 were not covered by tests
return "/var/run/secrets/azure/tokens/azure-identity-token"
}
Loading

0 comments on commit dd9b8dc

Please sign in to comment.