github.com/argoproj/argo-cd/v3@v3.2.1/applicationset/utils/kubernetes.go (about)

     1  package utils
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/argoproj/argo-cd/v3/common"
     8  
     9  	corev1 "k8s.io/api/core/v1"
    10  	"sigs.k8s.io/controller-runtime/pkg/client"
    11  
    12  	argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
    13  )
    14  
    15  var ErrDisallowedSecretAccess = fmt.Errorf("secret must have label %q=%q", common.LabelKeySecretType, common.LabelValueSecretTypeSCMCreds)
    16  
    17  // GetSecretRef gets the value of the key for the specified Secret resource.
    18  func GetSecretRef(ctx context.Context, k8sClient client.Client, ref *argoprojiov1alpha1.SecretRef, namespace string, tokenRefStrictMode bool) (string, error) {
    19  	if ref == nil {
    20  		return "", nil
    21  	}
    22  
    23  	secret := &corev1.Secret{}
    24  	err := k8sClient.Get(
    25  		ctx,
    26  		client.ObjectKey{
    27  			Name:      ref.SecretName,
    28  			Namespace: namespace,
    29  		},
    30  		secret)
    31  	if err != nil {
    32  		return "", fmt.Errorf("error fetching secret %s/%s: %w", namespace, ref.SecretName, err)
    33  	}
    34  
    35  	if tokenRefStrictMode && secret.GetLabels()[common.LabelKeySecretType] != common.LabelValueSecretTypeSCMCreds {
    36  		return "", fmt.Errorf("secret %s/%s is not a valid SCM creds secret: %w", namespace, ref.SecretName, ErrDisallowedSecretAccess)
    37  	}
    38  
    39  	tokenBytes, ok := secret.Data[ref.Key]
    40  	if !ok {
    41  		return "", fmt.Errorf("key %q in secret %s/%s not found", ref.Key, namespace, ref.SecretName)
    42  	}
    43  	return string(tokenBytes), nil
    44  }
    45  
    46  func GetConfigMapData(ctx context.Context, k8sClient client.Client, ref *argoprojiov1alpha1.ConfigMapKeyRef, namespace string) ([]byte, error) {
    47  	if ref == nil {
    48  		return nil, nil
    49  	}
    50  
    51  	configMap := &corev1.ConfigMap{}
    52  	err := k8sClient.Get(ctx, client.ObjectKey{Name: ref.ConfigMapName, Namespace: namespace}, configMap)
    53  	if err != nil {
    54  		return nil, err
    55  	}
    56  
    57  	data, ok := configMap.Data[ref.Key]
    58  	if !ok {
    59  		return nil, fmt.Errorf("key %s not found in ConfigMap %s", ref.Key, configMap.Name)
    60  	}
    61  
    62  	return []byte(data), nil
    63  }