-
Notifications
You must be signed in to change notification settings - Fork 211
/
secrets.go
191 lines (166 loc) · 6.51 KB
/
secrets.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
package kube
import (
"context"
"fmt"
"strings"
"github.com/aquasecurity/trivy-operator/pkg/docker"
corev1 "k8s.io/api/core/v1"
k8sapierror "k8s.io/apimachinery/pkg/api/errors"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// MapContainerNamesToDockerAuths creates the mapping from a container name to the Docker authentication
// credentials for the specified kube.ContainerImages and image pull Secrets.
func MapContainerNamesToDockerAuths(images ContainerImages, secrets []corev1.Secret) (map[string]docker.Auth, error) {
auths, wildcardServers, err := MapDockerRegistryServersToAuths(secrets)
if err != nil {
return nil, err
}
mapping := make(map[string]docker.Auth)
for containerName, imageRef := range images {
server, err := docker.GetServerFromImageRef(imageRef)
if err != nil {
return nil, err
}
if auth, ok := auths[server]; ok {
mapping[containerName] = auth
}
if len(wildcardServers) > 0 {
if wildcardDomain := matchSubDomain(wildcardServers, server); len(wildcardDomain) > 0 {
if auth, ok := auths[wildcardDomain]; ok {
mapping[containerName] = auth
}
}
}
}
return mapping, nil
}
func matchSubDomain(wildcardServers []string, subDomain string) string {
for _, domain := range wildcardServers {
domainWithoutWildcard := strings.Replace(domain, "*", "", 1)
if strings.HasSuffix(subDomain, domainWithoutWildcard) {
return domain
}
}
return ""
}
// MapDockerRegistryServersToAuths creates the mapping from a Docker registry server
// to the Docker authentication credentials for the specified slice of image pull Secrets.
func MapDockerRegistryServersToAuths(imagePullSecrets []corev1.Secret) (map[string]docker.Auth, []string, error) {
auths := make(map[string]docker.Auth)
wildcardServers := make([]string, 0)
for _, secret := range imagePullSecrets {
// Skip a deprecated secret of type "kubernetes.io/dockercfg" which contains a dockercfg file
// that follows the same format rules as ~/.dockercfg
// See https://docs.docker.com/engine/deprecated/#support-for-legacy-dockercfg-configuration-files
if secret.Type != corev1.SecretTypeDockerConfigJson {
continue
}
data, hasRequiredData := secret.Data[corev1.DockerConfigJsonKey]
// Skip a secrets of type "kubernetes.io/dockerconfigjson" which does not contain
// the required ".dockerconfigjson" key.
if !hasRequiredData {
continue
}
dockerConfig := &docker.Config{}
err := dockerConfig.Read(data)
if err != nil {
return nil, nil, fmt.Errorf("reading %s field of %q secret: %w", corev1.DockerConfigJsonKey, secret.Namespace+"/"+secret.Name, err)
}
for authKey, auth := range dockerConfig.Auths {
server, err := docker.GetServerFromDockerAuthKey(authKey)
if err != nil {
return nil, nil, err
}
auths[server] = auth
if strings.HasPrefix(server, "*.") {
wildcardServers = append(wildcardServers, server)
}
}
}
return auths, wildcardServers, nil
}
func AggregateImagePullSecretsData(images ContainerImages, credentials map[string]docker.Auth) map[string][]byte {
secretData := make(map[string][]byte)
for containerName := range images {
if dockerAuth, ok := credentials[containerName]; ok {
secretData[fmt.Sprintf("%s.username", containerName)] = []byte(dockerAuth.Username)
secretData[fmt.Sprintf("%s.password", containerName)] = []byte(dockerAuth.Password)
}
}
return secretData
}
const (
serviceAccountDefault = "default"
)
// SecretsReader defines methods for reading Secrets.
type SecretsReader interface {
ListByLocalObjectReferences(ctx context.Context, refs []corev1.LocalObjectReference, ns string) ([]corev1.Secret, error)
ListImagePullSecretsByPodSpec(ctx context.Context, spec corev1.PodSpec, ns string) ([]corev1.Secret, error)
CredentialsByWorkload(ctx context.Context, workload client.Object) (map[string]docker.Auth, error)
}
// NewSecretsReader constructs a new SecretsReader which is using the client
// package provided by the controller-runtime libraries for interacting with
// the Kubernetes API server.
func NewSecretsReader(c client.Client) SecretsReader {
return &secretsReader{client: c}
}
//+kubebuilder:rbac:groups="",resources=secrets,verbs=get
//+kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get
type secretsReader struct {
client client.Client
}
func (r *secretsReader) ListByLocalObjectReferences(ctx context.Context, refs []corev1.LocalObjectReference, ns string) ([]corev1.Secret, error) {
secrets := make([]corev1.Secret, 0)
for _, secretRef := range refs {
var secret corev1.Secret
err := r.client.Get(ctx, client.ObjectKey{Name: secretRef.Name, Namespace: ns}, &secret)
if err != nil {
if k8sapierror.IsNotFound(err) {
continue
}
return nil, fmt.Errorf("getting secret by name: %s/%s: %w", ns, secretRef.Name, err)
}
secrets = append(secrets, secret)
}
return secrets, nil
}
func (r *secretsReader) getServiceAccountByPodSpec(ctx context.Context, spec corev1.PodSpec, ns string) (corev1.ServiceAccount, error) {
serviceAccountName := spec.ServiceAccountName
if serviceAccountName == "" {
serviceAccountName = serviceAccountDefault
}
sa := corev1.ServiceAccount{}
err := r.client.Get(ctx, client.ObjectKey{Name: serviceAccountName, Namespace: ns}, &sa)
if err != nil {
return sa, fmt.Errorf("getting service account by name: %s/%s: %w", ns, serviceAccountName, err)
}
return sa, nil
}
func (r *secretsReader) ListImagePullSecretsByPodSpec(ctx context.Context, spec corev1.PodSpec, ns string) ([]corev1.Secret, error) {
imagePullSecrets := spec.ImagePullSecrets
sa, err := r.getServiceAccountByPodSpec(ctx, spec, ns)
if err != nil && !k8sapierror.IsNotFound(err) {
return nil, err
}
imagePullSecrets = append(imagePullSecrets, sa.ImagePullSecrets...)
secrets, err := r.ListByLocalObjectReferences(ctx, imagePullSecrets, ns)
if err != nil {
return nil, err
}
// if image pull secret define in either service account or pod spec and no secrets found
if len(imagePullSecrets) > 0 && len(secrets) == 0 {
return nil, fmt.Errorf("failed to list secrets by imagePullSecrets ref %v and service account %s", spec.ImagePullSecrets, sa.Name)
}
return secrets, nil
}
func (r *secretsReader) CredentialsByWorkload(ctx context.Context, workload client.Object) (map[string]docker.Auth, error) {
spec, err := GetPodSpec(workload)
if err != nil {
return nil, fmt.Errorf("getting Pod template: %w", err)
}
imagePullSecrets, err := r.ListImagePullSecretsByPodSpec(ctx, spec, workload.GetNamespace())
if err != nil {
return nil, err
}
return MapContainerNamesToDockerAuths(GetContainerImagesFromPodSpec(spec), imagePullSecrets)
}