-
Notifications
You must be signed in to change notification settings - Fork 66
/
connection.go
73 lines (61 loc) · 2.38 KB
/
connection.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
package atlas
import (
"context"
"fmt"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
orgIDKey = "orgId"
publicAPIKey = "publicApiKey"
privateAPIKey = "privateApiKey"
)
// Connection encapsulates Atlas connectivity information that is necessary to perform API requests
type Connection struct {
OrgID string
PublicKey string
PrivateKey string
}
// ReadConnection reads Atlas API connection parameters from AtlasProject Secret or from the default Operator one if the
// former is not specified
func ReadConnection(log *zap.SugaredLogger, kubeClient client.Client, operatorAPISecret client.ObjectKey, projectOverrideSecretRef *client.ObjectKey) (Connection, error) {
if projectOverrideSecretRef != nil {
// TODO is it possible that part of connection (like orgID is still in the Operator level secret and needs to get merged?)
log.Infof("Reading Atlas API credentials from the AtlasProject Secret %s", projectOverrideSecretRef)
return readAtlasConnectionFromSecret(kubeClient, *projectOverrideSecretRef)
}
log.Debugf("AtlasProject connection Secret is not specified - using the Operator one: %v", operatorAPISecret)
return readAtlasConnectionFromSecret(kubeClient, operatorAPISecret)
}
func readAtlasConnectionFromSecret(kubeClient client.Client, secretRef client.ObjectKey) (Connection, error) {
secret := &corev1.Secret{}
if err := kubeClient.Get(context.Background(), secretRef, secret); err != nil {
return Connection{}, fmt.Errorf("can't read Atlas API credentials from the Secret %v: %w", secretRef, err)
}
secretData := make(map[string]string)
for k, v := range secret.Data {
secretData[k] = string(v)
}
if err := validateConnectionSecret(secretRef, secretData); err != nil {
return Connection{}, err
}
return Connection{
OrgID: secretData["orgId"],
PublicKey: secretData["publicApiKey"],
PrivateKey: secretData["privateApiKey"],
}, nil
}
func validateConnectionSecret(secretRef client.ObjectKey, secretData map[string]string) error {
var missingFields []string
requiredKeys := []string{orgIDKey, publicAPIKey, privateAPIKey}
for _, key := range requiredKeys {
if _, ok := secretData[key]; !ok {
missingFields = append(missingFields, key)
}
}
if len(missingFields) > 0 {
return fmt.Errorf("the following fields are missing in the Secret %v: %v", secretRef, missingFields)
}
return nil
}