-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
repository_legacy.go
474 lines (423 loc) · 17.2 KB
/
repository_legacy.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package db
import (
"strings"
"context"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
apiv1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/argoproj/argo-cd/v2/common"
appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/util/errors"
"github.com/argoproj/argo-cd/v2/util/git"
"github.com/argoproj/argo-cd/v2/util/settings"
)
var _ repositoryBackend = &legacyRepositoryBackend{}
// legacyRepositoryBackend is a repository backend strategy that maintains backward compatibility with previous versions.
// This can be removed in a future version, once the old "argocd-cm" storage for repositories is removed.
type legacyRepositoryBackend struct {
db *db
}
func (l *legacyRepositoryBackend) CreateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) {
// This strategy only kept to preserve backward compatibility, but is deprecated.
// Therefore no new repositories can be added with this backend.
panic("creating new repositories is not supported for the legacy repository backend")
}
func (l *legacyRepositoryBackend) GetRepository(ctx context.Context, repoURL string) (*appsv1.Repository, error) {
repository, err := l.tryGetRepository(repoURL)
if err != nil {
return nil, err
}
return repository, nil
}
func (l *legacyRepositoryBackend) ListRepositories(ctx context.Context, repoType *string) ([]*appsv1.Repository, error) {
inRepos, err := l.db.settingsMgr.GetRepositories()
if err != nil {
return nil, err
}
var repos []*appsv1.Repository
for _, inRepo := range inRepos {
if repoType == nil || *repoType == inRepo.Type {
r, err := l.tryGetRepository(inRepo.URL)
if err != nil {
if r != nil && errors.IsCredentialsConfigurationError(err) {
modifiedTime := metav1.Now()
r.ConnectionState = appsv1.ConnectionState{
Status: appsv1.ConnectionStatusFailed,
Message: "Configuration error - please check the server logs",
ModifiedAt: &modifiedTime,
}
log.Warnf("could not retrieve repo: %s", err.Error())
} else {
return nil, err
}
}
repos = append(repos, r)
}
}
return repos, nil
}
func (l *legacyRepositoryBackend) UpdateRepository(ctx context.Context, r *appsv1.Repository) (*appsv1.Repository, error) {
repos, err := l.db.settingsMgr.GetRepositories()
if err != nil {
return nil, err
}
index := l.getRepositoryIndex(repos, r.Repo)
if index < 0 {
return nil, status.Errorf(codes.NotFound, "repo '%s' not found", r.Repo)
}
repoInfo := repos[index]
err = l.updateRepositorySecrets(&repoInfo, r)
if err != nil {
return nil, err
}
// Update boolean settings
repoInfo.InsecureIgnoreHostKey = r.IsInsecure()
repoInfo.Insecure = r.IsInsecure()
repoInfo.EnableLFS = r.EnableLFS
repoInfo.Proxy = r.Proxy
repos[index] = repoInfo
err = l.db.settingsMgr.SaveRepositories(repos)
if err != nil {
return nil, err
}
return r, nil
}
func (l *legacyRepositoryBackend) DeleteRepository(ctx context.Context, repoURL string) error {
repos, err := l.db.settingsMgr.GetRepositories()
if err != nil {
return err
}
index := l.getRepositoryIndex(repos, repoURL)
if index < 0 {
return status.Errorf(codes.NotFound, "repo '%s' not found", repoURL)
}
err = l.updateRepositorySecrets(&repos[index], &appsv1.Repository{
SSHPrivateKey: "",
Password: "",
Username: "",
TLSClientCertData: "",
TLSClientCertKey: "",
GithubAppPrivateKey: "",
})
if err != nil {
return err
}
repos = append(repos[:index], repos[index+1:]...)
return l.db.settingsMgr.SaveRepositories(repos)
}
func (l *legacyRepositoryBackend) RepositoryExists(ctx context.Context, repoURL string) (bool, error) {
repos, err := l.db.settingsMgr.GetRepositories()
if err != nil {
return false, err
}
index := l.getRepositoryIndex(repos, repoURL)
return index >= 0, nil
}
func (l *legacyRepositoryBackend) CreateRepoCreds(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) {
// This strategy only kept to preserve backward compatibility, but is deprecated.
// Therefore no new repositories can be added with this backend.
panic("creating new repository credentials is not supported for the legacy repository backend")
}
func (l *legacyRepositoryBackend) GetRepoCreds(ctx context.Context, repoURL string) (*appsv1.RepoCreds, error) {
var credential *appsv1.RepoCreds
repoCredentials, err := l.db.settingsMgr.GetRepositoryCredentials()
if err != nil {
return nil, err
}
index := getRepositoryCredentialIndex(repoCredentials, repoURL)
if index >= 0 {
credential, err = l.credentialsToRepositoryCredentials(repoCredentials[index])
if err != nil {
return nil, err
}
}
return credential, err
}
func (l *legacyRepositoryBackend) ListRepoCreds(ctx context.Context) ([]string, error) {
repos, err := l.db.settingsMgr.GetRepositoryCredentials()
if err != nil {
return nil, err
}
urls := make([]string, len(repos))
for i := range repos {
urls[i] = repos[i].URL
}
return urls, nil
}
func (l *legacyRepositoryBackend) UpdateRepoCreds(ctx context.Context, r *appsv1.RepoCreds) (*appsv1.RepoCreds, error) {
repos, err := l.db.settingsMgr.GetRepositoryCredentials()
if err != nil {
return nil, err
}
index := getRepositoryCredentialIndex(repos, r.URL)
if index < 0 {
return nil, status.Errorf(codes.NotFound, "repository credentials '%s' not found", r.URL)
}
repoInfo := repos[index]
err = l.updateCredentialsSecret(&repoInfo, r)
if err != nil {
return nil, err
}
repos[index] = repoInfo
err = l.db.settingsMgr.SaveRepositoryCredentials(repos)
if err != nil {
return nil, err
}
return r, nil
}
func (l *legacyRepositoryBackend) DeleteRepoCreds(ctx context.Context, name string) error {
repos, err := l.db.settingsMgr.GetRepositoryCredentials()
if err != nil {
return err
}
index := getRepositoryCredentialIndex(repos, name)
if index < 0 {
return status.Errorf(codes.NotFound, "repository credentials '%s' not found", name)
}
err = l.updateCredentialsSecret(&repos[index], &appsv1.RepoCreds{
SSHPrivateKey: "",
Password: "",
Username: "",
TLSClientCertData: "",
TLSClientCertKey: "",
GithubAppPrivateKey: "",
})
if err != nil {
return err
}
repos = append(repos[:index], repos[index+1:]...)
return l.db.settingsMgr.SaveRepositoryCredentials(repos)
}
func (l *legacyRepositoryBackend) RepoCredsExists(ctx context.Context, repoURL string) (bool, error) {
creds, err := l.db.settingsMgr.GetRepositoryCredentials()
if err != nil {
return false, err
}
index := getRepositoryCredentialIndex(creds, repoURL)
return index >= 0, nil
}
func (l *legacyRepositoryBackend) GetAllHelmRepoCreds(ctx context.Context) ([]*appsv1.RepoCreds, error) {
var allCredentials []*appsv1.RepoCreds
repoCredentials, err := l.db.settingsMgr.GetRepositoryCredentials()
if err != nil {
return nil, err
}
for _, v := range repoCredentials {
if strings.EqualFold(v.Type, "helm") {
credential, err := l.credentialsToRepositoryCredentials(v)
if err != nil {
return nil, err
}
allCredentials = append(allCredentials, credential)
}
}
return allCredentials, err
}
func (l *legacyRepositoryBackend) updateRepositorySecrets(repoInfo *settings.Repository, r *appsv1.Repository) error {
secretsData := make(map[string]map[string][]byte)
repoInfo.UsernameSecret = l.setSecretData(repoSecretPrefix, r.Repo, secretsData, repoInfo.UsernameSecret, r.Username, username)
repoInfo.PasswordSecret = l.setSecretData(repoSecretPrefix, r.Repo, secretsData, repoInfo.PasswordSecret, r.Password, password)
repoInfo.SSHPrivateKeySecret = l.setSecretData(repoSecretPrefix, r.Repo, secretsData, repoInfo.SSHPrivateKeySecret, r.SSHPrivateKey, sshPrivateKey)
repoInfo.TLSClientCertDataSecret = l.setSecretData(repoSecretPrefix, r.Repo, secretsData, repoInfo.TLSClientCertDataSecret, r.TLSClientCertData, tlsClientCertData)
repoInfo.TLSClientCertKeySecret = l.setSecretData(repoSecretPrefix, r.Repo, secretsData, repoInfo.TLSClientCertKeySecret, r.TLSClientCertKey, tlsClientCertKey)
repoInfo.GithubAppPrivateKeySecret = l.setSecretData(repoSecretPrefix, r.Repo, secretsData, repoInfo.GithubAppPrivateKeySecret, r.GithubAppPrivateKey, githubAppPrivateKey)
repoInfo.GCPServiceAccountKey = l.setSecretData(repoSecretPrefix, r.Repo, secretsData, repoInfo.GCPServiceAccountKey, r.GCPServiceAccountKey, gcpServiceAccountKey)
for k, v := range secretsData {
err := l.upsertSecret(k, v)
if err != nil {
return err
}
}
return nil
}
func (l *legacyRepositoryBackend) updateCredentialsSecret(credsInfo *settings.RepositoryCredentials, c *appsv1.RepoCreds) error {
r := &appsv1.Repository{
Repo: c.URL,
Username: c.Username,
Password: c.Password,
SSHPrivateKey: c.SSHPrivateKey,
TLSClientCertData: c.TLSClientCertData,
TLSClientCertKey: c.TLSClientCertKey,
GithubAppPrivateKey: c.GithubAppPrivateKey,
GithubAppId: c.GithubAppId,
GithubAppInstallationId: c.GithubAppInstallationId,
GitHubAppEnterpriseBaseURL: c.GitHubAppEnterpriseBaseURL,
GCPServiceAccountKey: c.GCPServiceAccountKey,
}
secretsData := make(map[string]map[string][]byte)
credsInfo.UsernameSecret = l.setSecretData(credSecretPrefix, r.Repo, secretsData, credsInfo.UsernameSecret, r.Username, username)
credsInfo.PasswordSecret = l.setSecretData(credSecretPrefix, r.Repo, secretsData, credsInfo.PasswordSecret, r.Password, password)
credsInfo.SSHPrivateKeySecret = l.setSecretData(credSecretPrefix, r.Repo, secretsData, credsInfo.SSHPrivateKeySecret, r.SSHPrivateKey, sshPrivateKey)
credsInfo.TLSClientCertDataSecret = l.setSecretData(credSecretPrefix, r.Repo, secretsData, credsInfo.TLSClientCertDataSecret, r.TLSClientCertData, tlsClientCertData)
credsInfo.TLSClientCertKeySecret = l.setSecretData(credSecretPrefix, r.Repo, secretsData, credsInfo.TLSClientCertKeySecret, r.TLSClientCertKey, tlsClientCertKey)
credsInfo.GithubAppPrivateKeySecret = l.setSecretData(repoSecretPrefix, r.Repo, secretsData, credsInfo.GithubAppPrivateKeySecret, r.GithubAppPrivateKey, githubAppPrivateKey)
credsInfo.GCPServiceAccountKey = l.setSecretData(repoSecretPrefix, r.Repo, secretsData, credsInfo.GCPServiceAccountKey, r.GCPServiceAccountKey, gcpServiceAccountKey)
for k, v := range secretsData {
err := l.upsertSecret(k, v)
if err != nil {
return err
}
}
return nil
}
func (l *legacyRepositoryBackend) upsertSecret(name string, data map[string][]byte) error {
secret, err := l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Get(context.Background(), name, metav1.GetOptions{})
if err != nil {
if apierr.IsNotFound(err) {
if len(data) == 0 {
return nil
}
_, err = l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Create(context.Background(), &apiv1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Annotations: map[string]string{
common.AnnotationKeyManagedBy: common.AnnotationValueManagedByArgoCD,
},
},
Data: data,
}, metav1.CreateOptions{})
if err != nil {
return err
}
}
} else {
for _, key := range []string{username, password, sshPrivateKey, tlsClientCertData, tlsClientCertKey, githubAppPrivateKey} {
if secret.Data == nil {
secret.Data = make(map[string][]byte)
}
if val, ok := data[key]; ok && len(val) > 0 {
secret.Data[key] = val
} else {
delete(secret.Data, key)
}
}
if len(secret.Data) == 0 {
isManagedByArgo := secret.Annotations != nil && secret.Annotations[common.AnnotationKeyManagedBy] == common.AnnotationValueManagedByArgoCD
if isManagedByArgo {
return l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Delete(context.Background(), name, metav1.DeleteOptions{})
}
return nil
} else {
_, err = l.db.kubeclientset.CoreV1().Secrets(l.db.ns).Update(context.Background(), secret, metav1.UpdateOptions{})
if err != nil {
return err
}
}
}
return nil
}
// tryGetRepository returns a repository by URL.
// It provides the same functionality as GetRepository, with the additional behaviour of still returning a repository,
// even if an error occurred during the resolving of credentials for the repository. Otherwise this function behaves
// just as one would expect.
func (l *legacyRepositoryBackend) tryGetRepository(repoURL string) (*appsv1.Repository, error) {
repos, err := l.db.settingsMgr.GetRepositories()
if err != nil {
return nil, err
}
repo := &appsv1.Repository{Repo: repoURL}
index := l.getRepositoryIndex(repos, repoURL)
if index >= 0 {
repo, err = l.credentialsToRepository(repos[index])
if err != nil {
return repo, errors.NewCredentialsConfigurationError(err)
}
}
return repo, err
}
func (l *legacyRepositoryBackend) credentialsToRepository(repoInfo settings.Repository) (*appsv1.Repository, error) {
repo := &appsv1.Repository{
Repo: repoInfo.URL,
Type: repoInfo.Type,
Name: repoInfo.Name,
InsecureIgnoreHostKey: repoInfo.InsecureIgnoreHostKey,
Insecure: repoInfo.Insecure,
EnableLFS: repoInfo.EnableLFS,
EnableOCI: repoInfo.EnableOci,
GithubAppId: repoInfo.GithubAppId,
GithubAppInstallationId: repoInfo.GithubAppInstallationId,
GitHubAppEnterpriseBaseURL: repoInfo.GithubAppEnterpriseBaseURL,
Proxy: repoInfo.Proxy,
}
err := l.db.unmarshalFromSecretsStr(map[*SecretMaperValidation]*apiv1.SecretKeySelector{
&SecretMaperValidation{Dest: &repo.Username, Transform: StripCRLFCharacter}: repoInfo.UsernameSecret,
&SecretMaperValidation{Dest: &repo.Password, Transform: StripCRLFCharacter}: repoInfo.PasswordSecret,
&SecretMaperValidation{Dest: &repo.SSHPrivateKey, Transform: StripCRLFCharacter}: repoInfo.SSHPrivateKeySecret,
&SecretMaperValidation{Dest: &repo.TLSClientCertData, Transform: StripCRLFCharacter}: repoInfo.TLSClientCertDataSecret,
&SecretMaperValidation{Dest: &repo.TLSClientCertKey, Transform: StripCRLFCharacter}: repoInfo.TLSClientCertKeySecret,
&SecretMaperValidation{Dest: &repo.GithubAppPrivateKey, Transform: StripCRLFCharacter}: repoInfo.GithubAppPrivateKeySecret,
&SecretMaperValidation{Dest: &repo.GCPServiceAccountKey, Transform: StripCRLFCharacter}: repoInfo.GCPServiceAccountKey,
}, make(map[string]*apiv1.Secret))
return repo, err
}
func (l *legacyRepositoryBackend) credentialsToRepositoryCredentials(repoInfo settings.RepositoryCredentials) (*appsv1.RepoCreds, error) {
creds := &appsv1.RepoCreds{
URL: repoInfo.URL,
GithubAppId: repoInfo.GithubAppId,
GithubAppInstallationId: repoInfo.GithubAppInstallationId,
GitHubAppEnterpriseBaseURL: repoInfo.GithubAppEnterpriseBaseURL,
EnableOCI: repoInfo.EnableOCI,
}
err := l.db.unmarshalFromSecretsStr(map[*SecretMaperValidation]*apiv1.SecretKeySelector{
&SecretMaperValidation{Dest: &creds.Username}: repoInfo.UsernameSecret,
&SecretMaperValidation{Dest: &creds.Password}: repoInfo.PasswordSecret,
&SecretMaperValidation{Dest: &creds.SSHPrivateKey}: repoInfo.SSHPrivateKeySecret,
&SecretMaperValidation{Dest: &creds.TLSClientCertData}: repoInfo.TLSClientCertDataSecret,
&SecretMaperValidation{Dest: &creds.TLSClientCertKey}: repoInfo.TLSClientCertKeySecret,
&SecretMaperValidation{Dest: &creds.GithubAppPrivateKey}: repoInfo.GithubAppPrivateKeySecret,
&SecretMaperValidation{Dest: &creds.GCPServiceAccountKey}: repoInfo.GCPServiceAccountKey,
}, make(map[string]*apiv1.Secret))
return creds, err
}
// Set data to be stored in a given secret used for repository credentials and templates.
// The name of the secret is a combination of the prefix given, and a calculated value
// from the repository or template URL.
func (l *legacyRepositoryBackend) setSecretData(prefix string, url string, secretsData map[string]map[string][]byte, secretKey *apiv1.SecretKeySelector, value string, defaultKeyName string) *apiv1.SecretKeySelector {
if secretKey == nil && value != "" {
secretKey = &apiv1.SecretKeySelector{
LocalObjectReference: apiv1.LocalObjectReference{Name: RepoURLToSecretName(prefix, url)},
Key: defaultKeyName,
}
}
if secretKey != nil {
data, ok := secretsData[secretKey.Name]
if !ok {
data = map[string][]byte{}
}
if value != "" {
data[secretKey.Key] = []byte(value)
}
secretsData[secretKey.Name] = data
}
if value == "" {
secretKey = nil
}
return secretKey
}
func (l *legacyRepositoryBackend) getRepositoryIndex(repos []settings.Repository, repoURL string) int {
for i, repo := range repos {
if git.SameURL(repo.URL, repoURL) {
return i
}
}
return -1
}
// getRepositoryCredentialIndex returns the index of the best matching repository credential
// configuration, i.e. the one with the longest match
func getRepositoryCredentialIndex(repoCredentials []settings.RepositoryCredentials, repoURL string) int {
var max, idx int = 0, -1
repoURL = git.NormalizeGitURL(repoURL)
for i, cred := range repoCredentials {
credUrl := git.NormalizeGitURL(cred.URL)
if strings.HasPrefix(repoURL, credUrl) {
if len(credUrl) > max {
max = len(credUrl)
idx = i
}
}
}
return idx
}