|
| 1 | +// Copyright The Conforma Contributors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | +// |
| 15 | +// SPDX-License-Identifier: Apache-2.0 |
| 16 | + |
| 17 | +package utils |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "strings" |
| 23 | + |
| 24 | + "github.com/spf13/afero" |
| 25 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 26 | + "k8s.io/client-go/kubernetes" |
| 27 | + "k8s.io/client-go/rest" |
| 28 | + "k8s.io/client-go/tools/clientcmd" |
| 29 | +) |
| 30 | + |
| 31 | +// contextKey is a custom type for context keys to avoid collisions |
| 32 | +type contextKey string |
| 33 | + |
| 34 | +const K8sClientKey contextKey = "k8s.client" |
| 35 | + |
| 36 | +// KeyFromKeyRef resolves a key from either a file path or a Kubernetes secret reference. |
| 37 | +// This provides a unified interface for both public and private key resolution. |
| 38 | +// Supported formats: |
| 39 | +// - File path: "/path/to/key.pem" |
| 40 | +// - Kubernetes secret: "k8s://namespace/secret-name/key-field" (explicit key field) |
| 41 | +// - Kubernetes secret: "k8s://namespace/secret-name" (auto-select if single key exists) |
| 42 | +func KeyFromKeyRef(ctx context.Context, keyRef string, fs afero.Fs) ([]byte, error) { |
| 43 | + if strings.HasPrefix(keyRef, "k8s://") { |
| 44 | + return keyFromKubernetesSecret(ctx, keyRef) |
| 45 | + } |
| 46 | + return keyFromFile(keyRef, fs) |
| 47 | +} |
| 48 | + |
| 49 | +// PublicKeyFromKeyRef resolves a public key from either a file path or a Kubernetes secret reference. |
| 50 | +// This provides a consistent interface with PrivateKeyFromKeyRef. |
| 51 | +// Supported formats: |
| 52 | +// - File path: "/path/to/public-key.pem" |
| 53 | +// - Kubernetes secret: "k8s://namespace/secret-name/key-field" (explicit key field) |
| 54 | +// - Kubernetes secret: "k8s://namespace/secret-name" (auto-select if single key exists) |
| 55 | +func PublicKeyFromKeyRef(ctx context.Context, keyRef string, fs afero.Fs) ([]byte, error) { |
| 56 | + return KeyFromKeyRef(ctx, keyRef, fs) |
| 57 | +} |
| 58 | + |
| 59 | +// keyFromFile reads a key from the filesystem |
| 60 | +func keyFromFile(keyPath string, fs afero.Fs) ([]byte, error) { |
| 61 | + keyBytes, err := afero.ReadFile(fs, keyPath) |
| 62 | + if err != nil { |
| 63 | + return nil, fmt.Errorf("read key from file %q: %w", keyPath, err) |
| 64 | + } |
| 65 | + return keyBytes, nil |
| 66 | +} |
| 67 | + |
| 68 | +// keyFromKubernetesSecret reads a key from a Kubernetes secret |
| 69 | +// Supported formats: |
| 70 | +// - k8s://namespace/secret-name/key-field (explicit key field) |
| 71 | +// - k8s://namespace/secret-name (auto-select if single key exists) |
| 72 | +func keyFromKubernetesSecret(ctx context.Context, keyRef string) ([]byte, error) { |
| 73 | + // Validate format first before attempting to create client |
| 74 | + parts := strings.Split(strings.TrimPrefix(keyRef, "k8s://"), "/") |
| 75 | + if len(parts) < 2 || len(parts) > 3 { |
| 76 | + return nil, fmt.Errorf("invalid k8s key reference format %q, expected k8s://namespace/secret-name or k8s://namespace/secret-name/key-field", keyRef) |
| 77 | + } |
| 78 | + |
| 79 | + namespace := parts[0] |
| 80 | + secretName := parts[1] |
| 81 | + var keyField string |
| 82 | + if len(parts) == 3 { |
| 83 | + keyField = parts[2] |
| 84 | + } |
| 85 | + |
| 86 | + if namespace == "" || secretName == "" { |
| 87 | + return nil, fmt.Errorf("invalid k8s key reference %q: namespace and secret name must be specified", keyRef) |
| 88 | + } |
| 89 | + |
| 90 | + k8sClient, err := getKubernetesClient(ctx) |
| 91 | + if err != nil { |
| 92 | + return nil, fmt.Errorf("get kubernetes client: %w", err) |
| 93 | + } |
| 94 | + |
| 95 | + secret, err := k8sClient.CoreV1().Secrets(namespace).Get(ctx, secretName, metav1.GetOptions{}) |
| 96 | + if err != nil { |
| 97 | + return nil, fmt.Errorf("fetch secret %s/%s: %w", namespace, secretName, err) |
| 98 | + } |
| 99 | + |
| 100 | + // If key field is specified, use it directly |
| 101 | + if keyField != "" { |
| 102 | + keyData, exists := secret.Data[keyField] |
| 103 | + if !exists { |
| 104 | + return nil, fmt.Errorf("key field %q not found in secret %s/%s", keyField, namespace, secretName) |
| 105 | + } |
| 106 | + return keyData, nil |
| 107 | + } |
| 108 | + |
| 109 | + // No key field specified - auto-select if single key exists |
| 110 | + keyCount := len(secret.Data) |
| 111 | + if keyCount == 0 { |
| 112 | + return nil, fmt.Errorf("secret %s/%s contains no keys", namespace, secretName) |
| 113 | + } |
| 114 | + if keyCount == 1 { |
| 115 | + // Get the single key |
| 116 | + for _, keyData := range secret.Data { |
| 117 | + return keyData, nil |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + // Multiple keys exist - return error without exposing key names |
| 122 | + return nil, fmt.Errorf("secret %s/%s contains multiple keys, please specify the key field: k8s://%s/%s/<key-field>", |
| 123 | + namespace, secretName, namespace, secretName) |
| 124 | +} |
| 125 | + |
| 126 | +// getKubernetesClient retrieves a Kubernetes client from the context or creates a new one |
| 127 | +func getKubernetesClient(ctx context.Context) (kubernetes.Interface, error) { |
| 128 | + // Try to get from context first (for testing) |
| 129 | + if client, ok := ctx.Value(K8sClientKey).(kubernetes.Interface); ok { |
| 130 | + return client, nil |
| 131 | + } |
| 132 | + |
| 133 | + // Create a new client using the same pattern as the existing kubernetes package |
| 134 | + // This follows the same pattern as used in the policy package |
| 135 | + config, err := getKubernetesConfig() |
| 136 | + if err != nil { |
| 137 | + return nil, fmt.Errorf("get kubernetes config: %w", err) |
| 138 | + } |
| 139 | + |
| 140 | + client, err := kubernetes.NewForConfig(config) |
| 141 | + if err != nil { |
| 142 | + return nil, fmt.Errorf("create kubernetes client: %w", err) |
| 143 | + } |
| 144 | + |
| 145 | + return client, nil |
| 146 | +} |
| 147 | + |
| 148 | +// getKubernetesConfig creates a Kubernetes config following the same pattern as the existing code |
| 149 | +func getKubernetesConfig() (*rest.Config, error) { |
| 150 | + rules := clientcmd.NewDefaultClientConfigLoadingRules() |
| 151 | + clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, nil) |
| 152 | + return clientConfig.ClientConfig() |
| 153 | +} |
0 commit comments