Repository navigation
Expand file tree
/
Copy pathsecrets.go
More file actions
272 lines (223 loc) · 8.25 KB
/
Copy pathsecrets.go
File metadata and controls
272 lines (223 loc) · 8.25 KB
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
/*
Copyright 2025 The Flux 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 secrets
import (
"crypto/tls"
"fmt"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
// KeyTLSCert is the standard key for TLS certificate data in secrets.
KeyTLSCert = corev1.TLSCertKey
// KeyTLSPrivateKey is the standard key for TLS private key data in secrets.
KeyTLSPrivateKey = corev1.TLSPrivateKeyKey
// KeyCACert is the standard key for CA certificate data in secrets.
KeyCACert = "ca.crt"
// LegacyKeyTLSCert is the legacy key for TLS certificate data in secrets.
LegacyKeyTLSCert = "certFile"
// LegacyKeyTLSPrivateKey is the legacy key for TLS private key data in secrets.
LegacyKeyTLSPrivateKey = "keyFile"
// LegacyKeyCACert is the legacy key for CA certificate data in secrets.
LegacyKeyCACert = "caFile"
// KeyUsername is the key for username data in basic auth secrets.
KeyUsername = "username"
// KeyPassword is the key for password data in basic auth secrets.
KeyPassword = "password"
// KeyAddress is the key for proxy address data in proxy secrets.
KeyAddress = "address"
// KeyBearerToken is the key for bearer token data in secrets.
KeyBearerToken = "bearerToken"
// KeyToken is the key for generic API token data in secrets.
KeyToken = "token"
// KeyGitHubAppID is the key for GitHub App ID data in secrets.
KeyGitHubAppID = "githubAppID"
// KeyGitHubAppClientID is the key for GitHub App client ID data in secrets.
KeyGitHubAppClientID = "githubAppClientID"
// KeyGitHubAppInstallationOwner is the key for GitHub App installation owner data in secrets.
KeyGitHubAppInstallationOwner = "githubAppInstallationOwner"
// KeyGitHubAppInstallationID is the key for GitHub App installation ID data in secrets.
KeyGitHubAppInstallationID = "githubAppInstallationID"
// KeyGitHubAppPrivateKey is the key for GitHub App private key data in secrets.
KeyGitHubAppPrivateKey = "githubAppPrivateKey"
// KeyGitHubAppBaseURL is the key for GitHub App base URL data in secrets.
KeyGitHubAppBaseURL = "githubAppBaseURL"
// KeySSHPrivateKey is the key for SSH private key data in secrets.
KeySSHPrivateKey = "identity"
// KeySSHPublicKey is the key for SSH public key data in secrets.
KeySSHPublicKey = "identity.pub"
// KeySSHKnownHosts is the key for SSH known hosts data in secrets.
KeySSHKnownHosts = "known_hosts"
// MaxProxyURLLength is the maximum allowed length for proxy URLs.
MaxProxyURLLength = 2048
)
// supportedProxySchemes defines the officially supported proxy URL schemes.
// See https://fluxcd.io/flux/installation/configuration/proxy-setting for more information.
var supportedProxySchemes = []string{"http", "https", "socks5"}
// AuthMethods holds all available authentication methods detected from a secret.
type AuthMethods struct {
Basic *BasicAuth
Bearer BearerAuth
Token TokenAuth
SSH *SSHAuth
GitHubAppData GitHubAppData
TLS *tls.Config
}
// HasBasicAuth returns true if basic authentication is available.
func (am *AuthMethods) HasBasicAuth() bool {
return am.Basic != nil
}
// HasBearerAuth returns true if bearer token authentication is available.
func (am *AuthMethods) HasBearerAuth() bool {
return am.Bearer != ""
}
// HasTokenAuth returns true if token authentication is available.
func (am *AuthMethods) HasTokenAuth() bool {
return am.Token != ""
}
// HasSSH returns true if SSH authentication is available.
func (am *AuthMethods) HasSSH() bool {
return am.SSH != nil
}
// HasGitHubAppData returns true if GitHub App authentication data is available.
func (am *AuthMethods) HasGitHubAppData() bool {
return len(am.GitHubAppData) > 0
}
// HasTLS returns true if TLS configuration is available.
func (am *AuthMethods) HasTLS() bool {
return am.TLS != nil
}
// AuthMethodsOption configures the behavior of AuthMethodsFromSecret.
type AuthMethodsOption func(*authMethodsConfig)
// authMethodsConfig holds configuration for AuthMethods extraction.
type authMethodsConfig struct {
tlsConfigOpts []TLSConfigOption
}
// tlsConfig holds TLS-specific configuration options.
type tlsConfig struct {
useSystemCertPool bool
}
// WithTLSSystemCertPool enables the use of system certificate pool in addition to user-provided CA certificates.
func WithTLSSystemCertPool() AuthMethodsOption {
return func(cfg *authMethodsConfig) {
cfg.tlsConfigOpts = append(cfg.tlsConfigOpts, WithSystemCertPool())
}
}
// tlsCertificateData holds TLS certificate, key, and optional CA data
type tlsCertificateData struct {
cert []byte
key []byte
caCert []byte
}
// newTLSCertificateData creates tlsCertificateData from a Kubernetes secret.
func newTLSCertificateData(secret *corev1.Secret, logger logr.Logger) (*tlsCertificateData, error) {
data := &tlsCertificateData{
cert: getSecretData(secret, KeyTLSCert, LegacyKeyTLSCert, logger),
key: getSecretData(secret, KeyTLSPrivateKey, LegacyKeyTLSPrivateKey, logger),
caCert: getSecretData(secret, KeyCACert, LegacyKeyCACert, logger),
}
if err := data.validate(); err != nil {
return nil, err
}
return data, nil
}
func (t *tlsCertificateData) validate() error {
hasCert := len(t.cert) > 0
hasKey := len(t.key) > 0
hasCA := len(t.caCert) > 0
if hasCert != hasKey {
if hasCert {
return &TLSValidationError{Type: ErrMissingPrivateKey}
}
return &TLSValidationError{Type: ErrMissingCertificate}
}
if !hasCert && !hasCA {
return &TLSValidationError{Type: ErrNoCertificatePairOrCA}
}
return nil
}
func (t *tlsCertificateData) hasCertPair() bool {
return len(t.cert) > 0 && len(t.key) > 0
}
func (t *tlsCertificateData) hasCA() bool {
return len(t.caCert) > 0
}
// validateCertificatePairIfPresent validates the certificate and key pair if both are present.
func (t *tlsCertificateData) validateCertificatePairIfPresent() error {
if t.hasCertPair() {
if _, err := tls.X509KeyPair(t.cert, t.key); err != nil {
return fmt.Errorf("invalid TLS certificate and key pair: %w", err)
}
}
return nil
}
// toSecret creates a Kubernetes secret from the certificate data.
func (t *tlsCertificateData) toSecret(name, namespace string) *corev1.Secret {
secretData := make(map[string]string)
var secretType corev1.SecretType
if t.hasCertPair() {
secretData[KeyTLSCert] = string(t.cert)
secretData[KeyTLSPrivateKey] = string(t.key)
secretType = corev1.SecretTypeTLS
} else {
secretType = corev1.SecretTypeOpaque
}
if t.hasCA() {
secretData[KeyCACert] = string(t.caCert)
}
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Type: secretType,
StringData: secretData,
}
secret.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret"))
return secret
}
// BasicAuth holds basic authentication credentials.
type BasicAuth struct {
Username string
Password string
}
// BearerAuth holds bearer token authentication credentials.
type BearerAuth string
// TokenAuth holds generic token authentication credentials.
type TokenAuth string
// GitHubAppData holds GitHub App authentication data as key-value pairs.
type GitHubAppData = map[string][]byte
// SSHAuth holds SSH authentication credentials.
type SSHAuth struct {
PrivateKey []byte
PublicKey []byte
KnownHosts string
Password string
}
// getSecretData retrieves data from secret with fallback support for legacy keys.
func getSecretData(secret *corev1.Secret, key, fallbackKey string, logger logr.Logger) []byte {
if data, exists := secret.Data[key]; exists {
return data
}
// Always support legacy fields for consistency across Flux APIs
if data, exists := secret.Data[fallbackKey]; exists {
logger.Error(nil, "using legacy key in secret data",
"secret", client.ObjectKeyFromObject(secret),
"key", fallbackKey,
"preferred", key)
return data
}
return nil
}