-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmutate.go
216 lines (182 loc) · 6.34 KB
/
mutate.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
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"strings"
"k8s.io/api/admission/v1beta1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func cleanName(name string) string {
return strings.ReplaceAll(name, "_", "-")
}
func useExternalVault(pod *v1.Pod) (bool, string) {
if os.Getenv("VAULT_ADDR_HTTPS") == "" {
return false, ""
}
// if val, ok := pod.ObjectMeta.Labels["sidecar.istio.io/inject"]; ok && val == "false" {
if _, ok := pod.ObjectMeta.Labels["workflows.argoproj.io/workflow"]; ok {
log.Printf("Will use external Vault address for workflow %s", pod.Name)
return true, os.Getenv("VAULT_ADDR_HTTPS")
}
return false, ""
}
func shouldInject(pod *v1.Pod) bool {
// Inject Minio credentials into notebook pods (condition: has notebook-name label)
if _, ok := pod.ObjectMeta.Labels["notebook-name"]; ok {
log.Printf("Found notebook name for %s/%s; injecting", pod.Namespace, pod.Name)
return true
}
// Inject Minio credentials into argo workflow pods (condition: has workflows.argoproj.io/workflow label)
if _, ok := pod.ObjectMeta.Labels["workflows.argoproj.io/workflow"]; ok {
log.Printf("Found argo workflow name for %s/%s; injecting", pod.Namespace, pod.Name)
return true
}
// Inject Minio credentials into pod requesting credentials (condition: has add-default-minio-creds annotation)
if _, ok := pod.ObjectMeta.Annotations["data.statcan.gc.ca/inject-minio-creds"]; ok {
log.Printf("Found minio credential annotation on %s/%s; injecting", pod.Namespace, pod.Name)
return true
}
return false
}
func mutate(request v1beta1.AdmissionRequest, instances []Instance) (v1beta1.AdmissionResponse, error) {
response := v1beta1.AdmissionResponse{}
// Default response
response.Allowed = true
response.UID = request.UID
// Decode the pod object
var err error
pod := v1.Pod{}
if err := json.Unmarshal(request.Object.Raw, &pod); err != nil {
return response, fmt.Errorf("unable to decode Pod %w", err)
}
// Identify the data classification of the pod, defaulting to unclassified if unset
dataClassification := "unclassified"
if val, ok := pod.ObjectMeta.Labels["data.statcan.gc.ca/classification"]; ok {
dataClassification = val
}
if shouldInject(&pod) {
patch := v1beta1.PatchTypeJSONPatch
response.PatchType = &patch
response.AuditAnnotations = map[string]string{
"minio-admission-controller": "Added minio credentials",
}
// Handle https://github.com/StatCan/aaw-minio-credential-injector/issues/10
var roleName string
if pod.Namespace != "" {
roleName = cleanName("profile-" + pod.Namespace)
} else if request.Namespace != "" {
roleName = cleanName("profile-" + request.Namespace)
} else {
return response, fmt.Errorf("pod and request namespace were empty. Cannot determine the namespace.")
}
patches := []map[string]interface{}{
{
"op": "add",
"path": "/metadata/annotations/vault.hashicorp.com~1agent-inject",
"value": "true",
},
{
"op": "add",
"path": "/metadata/annotations/vault.hashicorp.com~1agent-pre-populate",
"value": "false",
},
{
"op": "add",
"path": "/metadata/annotations/vault.hashicorp.com~1role",
"value": roleName,
},
}
// Always explicitly choose the Vault address, internal or external
if useExternal, vaultAddr := useExternalVault(&pod); useExternal {
patches = append(patches, map[string]interface{}{
"op": "add",
"path": fmt.Sprintf("/metadata/annotations/vault.hashicorp.com~1service"),
"value": vaultAddr,
})
} else {
patches = append(patches, map[string]interface{}{
"op": "add",
"path": fmt.Sprintf("/metadata/annotations/vault.hashicorp.com~1service"),
"value": "http://vault.vault-system:8200",
})
}
useExternal, _ := useExternalVault(&pod)
if useExternal {
log.Printf("Pod %s/%s will use external urls", pod.Namespace, pod.Name)
} else {
log.Printf("Pod %s/%s will use internal urls", pod.Namespace, pod.Name)
}
for _, instance := range instances {
// Only apply to the relevant instances
if instance.Classification != dataClassification {
continue
} else if useExternal && instance.ExternalUrl == "" {
log.Printf("Not injecting the pod %s/%s with sensitive minio instance", pod.Namespace, pod.Name, instance.Name)
continue
}
var url string
if useExternal {
url = instance.ExternalUrl
} else {
url = instance.ServiceUrl
}
var instanceId string
if instance.Alias != "" {
instanceId = instance.Alias
} else {
instanceId = strings.ReplaceAll(instance.Name, "_", "-")
}
patches = append(patches, map[string]interface{}{
"op": "add",
"path": fmt.Sprintf("/metadata/annotations/vault.hashicorp.com~1agent-inject-secret-%s", instanceId),
"value": fmt.Sprintf("%s/keys/%s", instance.Name, roleName),
})
patches = append(patches, map[string]interface{}{
"op": "add",
"path": fmt.Sprintf("/metadata/annotations/vault.hashicorp.com~1agent-inject-template-%s", instanceId),
"value": fmt.Sprintf(`
{{- with secret "%s/keys/%s" }}
export MINIO_URL="%s"
export MINIO_ACCESS_KEY="{{ .Data.accessKeyId }}"
export MINIO_SECRET_KEY="{{ .Data.secretAccessKey }}"
export AWS_ACCESS_KEY_ID="{{ .Data.accessKeyId }}"
export AWS_SECRET_ACCESS_KEY="{{ .Data.secretAccessKey }}"
{{- end }}
`, instance.Name, roleName, url),
})
patches = append(patches, map[string]interface{}{
"op": "add",
"path": fmt.Sprintf("/metadata/annotations/vault.hashicorp.com~1agent-inject-secret-%s.json", instanceId),
"value": fmt.Sprintf("%s/keys/%s", instance.Name, roleName),
})
patches = append(patches, map[string]interface{}{
"op": "add",
"path": fmt.Sprintf("/metadata/annotations/vault.hashicorp.com~1agent-inject-template-%s.json", instanceId),
"value": fmt.Sprintf(`
{{- with secret "%s/keys/%s" }}
{
"MINIO_URL": "%s",
"MINIO_ACCESS_KEY": "{{ .Data.accessKeyId }}",
"MINIO_SECRET_KEY": "{{ .Data.secretAccessKey }}",
"AWS_ACCESS_KEY_ID": "{{ .Data.accessKeyId }}",
"AWS_SECRET_ACCESS_KEY": "{{ .Data.secretAccessKey }}"
}
{{- end }}
`, instance.Name, roleName, url),
})
}
response.Patch, err = json.Marshal(patches)
if err != nil {
return response, err
}
response.Result = &metav1.Status{
Status: metav1.StatusSuccess,
}
} else {
log.Printf("Not injecting the pod %s/%s", pod.Namespace, pod.Name)
}
return response, nil
}