This repository has been archived by the owner on Dec 16, 2020. It is now read-only.
/
secrets.go
325 lines (263 loc) · 8.12 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
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
package handlers
import (
"context"
"encoding/json"
"fmt"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types/filters"
"io/ioutil"
"log"
"net/http"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"github.com/openfaas/faas/gateway/requests"
)
var (
ownerLabel = "com.openfaas.owner"
ownerLabelValue = "openfaas"
)
func MakeSecretsHandler(c *client.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
defer r.Body.Close()
}
body, readBodyErr := ioutil.ReadAll(r.Body)
if readBodyErr != nil {
log.Printf("couldn't read body of a request: %s", readBodyErr)
w.WriteHeader(http.StatusInternalServerError)
return
}
var (
responseStatus int
responseBody []byte
responseErr error
)
switch r.Method {
case http.MethodGet:
responseStatus, responseBody, responseErr = getSecrets(c, body)
break
case http.MethodPost:
responseStatus, responseBody, responseErr = createNewSecret(c, body)
break
case http.MethodPut:
responseStatus, responseBody, responseErr = updateSecret(c, body)
break
case http.MethodDelete:
responseStatus, responseBody, responseErr = deleteSecret(c, body)
break
}
if responseErr != nil {
log.Println(responseErr)
w.WriteHeader(responseStatus)
return
}
if responseBody != nil {
_, writeErr := w.Write(responseBody)
if writeErr != nil {
log.Println("cannot write body of a response")
w.WriteHeader(http.StatusInternalServerError)
return
}
}
w.WriteHeader(responseStatus)
}
}
func getSecretsWithLabel(c *client.Client, labelName string, labelValue string) ([]swarm.Secret, error) {
secrets, secretListErr := c.SecretList(context.Background(), types.SecretListOptions{})
if secretListErr != nil {
return nil, secretListErr
}
var filteredSecrets []swarm.Secret
for _, secret := range secrets {
if secret.Spec.Labels[labelName] == labelValue {
filteredSecrets = append(filteredSecrets, secret)
}
}
return filteredSecrets, nil
}
func getSecretWithName(c *client.Client, name string) (secret *swarm.Secret, err error, status int) {
secrets, secretListErr := c.SecretList(context.Background(), types.SecretListOptions{})
if secretListErr != nil {
return nil, secretListErr, http.StatusInternalServerError
}
for _, secret := range secrets {
if secret.Spec.Name == name {
if secret.Spec.Labels[ownerLabel] == ownerLabelValue {
return &secret, nil, http.StatusOK
}
return nil, fmt.Errorf(
"found secret with name: %s, but it doesn't have label: %s == %s",
name,
ownerLabel,
ownerLabelValue,
), http.StatusInternalServerError
}
}
return nil, fmt.Errorf("not found secret with name: %s", name), http.StatusNotFound
}
func getSecrets(c *client.Client, _ []byte) (responseStatus int, responseBody []byte, err error) {
secrets, err := getSecretsWithLabel(c, ownerLabel, ownerLabelValue)
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf(
"cannot get secrets with label: %s == %s in secretGetHandler: %s",
ownerLabel,
ownerLabelValue,
err,
)
}
results := []requests.Secret{}
for _, s := range secrets {
results = append(results, requests.Secret{Name: s.Spec.Name, Value: string(s.Spec.Data)})
}
resultsJson, marshalErr := json.Marshal(results)
if marshalErr != nil {
return http.StatusInternalServerError,
nil,
fmt.Errorf("error marshalling secrets to json: %s", marshalErr)
}
return http.StatusOK, resultsJson, nil
}
func createNewSecret(c *client.Client, body []byte) (responseStatus int, responseBody []byte, err error) {
var secret requests.Secret
unmarshalErr := json.Unmarshal(body, &secret)
if unmarshalErr != nil {
return http.StatusBadRequest, nil, fmt.Errorf(
"error unmarshalling body to json in secretPostHandler: %s",
unmarshalErr,
)
}
_, createSecretErr := c.SecretCreate(context.Background(), swarm.SecretSpec{
Annotations: swarm.Annotations{
Name: secret.Name,
Labels: map[string]string{
ownerLabel: ownerLabelValue,
},
},
Data: []byte(secret.Value),
})
if createSecretErr != nil {
return http.StatusInternalServerError, nil, fmt.Errorf(
"error creating secret in secretPostHandler: %s",
createSecretErr,
)
}
return http.StatusCreated, nil, nil
}
func updateSecret(c *client.Client, body []byte) (responseStatus int, responseBody []byte, err error) {
var secret requests.Secret
unmarshalErr := json.Unmarshal(body, &secret)
if unmarshalErr != nil {
return http.StatusBadRequest, nil, fmt.Errorf(
"error unmarshaling secret in secretPutHandler: %s",
unmarshalErr,
)
}
foundSecret, getSecretErr, status := getSecretWithName(c, secret.Name)
if getSecretErr != nil {
return status, nil, fmt.Errorf(
"cannot get secret with name: %s, which you want to remove. Error: %s",
secret.Name,
getSecretErr.Error(),
)
}
updateSecretErr := c.SecretUpdate(context.Background(), foundSecret.ID, foundSecret.Version, swarm.SecretSpec{
Annotations: swarm.Annotations{
Name: secret.Name,
Labels: map[string]string{
ownerLabel: ownerLabelValue,
},
},
Data: []byte(secret.Value),
})
if updateSecretErr != nil {
fmt.Println("updateSecretErr\n", updateSecretErr.Error())
return http.StatusInternalServerError, nil, fmt.Errorf(
"couldn't update secret (name: %s, ID: %s) because of error: %s",
secret.Name,
foundSecret.ID,
getSecretErr.Error(),
)
}
return http.StatusOK, nil,nil
}
func deleteSecret(c *client.Client, body []byte) (responseStatus int, responseBody []byte, err error) {
var secret requests.Secret
unmarshalErr := json.Unmarshal(body, &secret)
if unmarshalErr != nil {
return http.StatusBadRequest, nil, fmt.Errorf(
"error unmarshaling secret in secretDeleteHandler: %s",
unmarshalErr,
)
}
foundSecret, getSecretErr, status := getSecretWithName(c, secret.Name)
if getSecretErr != nil {
return status, nil, fmt.Errorf(
"cannot get secret with name: %s, which you want to remove. Error: %s",
secret.Name,
getSecretErr,
)
}
removeSecretErr := c.SecretRemove(context.Background(), foundSecret.ID)
if removeSecretErr != nil {
return http.StatusInternalServerError, nil, fmt.Errorf(
"error trying to remove secret (name: `%s`, ID: `%s`): %s",
secret.Name,
foundSecret.ID,
removeSecretErr,
)
}
return http.StatusOK, nil, nil
}
func makeSecretsArray(c *client.Client, secretNames []string) ([]*swarm.SecretReference, error) {
values := []*swarm.SecretReference{}
if len(secretNames) == 0 {
return values, nil
}
secretOpts := new(opts.SecretOpt)
for _, secret := range secretNames {
secretSpec := fmt.Sprintf("source=%s,target=/var/openfaas/secrets/%s", secret, secret)
if err := secretOpts.Set(secretSpec); err != nil {
return nil, err
}
}
requestedSecrets := make(map[string]bool)
ctx := context.Background()
// query the Swarm for the requested secret ids, these are required to complete
// the spec
args := filters.NewArgs()
for _, opt := range secretOpts.Value() {
args.Add("name", opt.SecretName)
}
secrets, err := c.SecretList(ctx, types.SecretListOptions{
Filters: args,
})
if err != nil {
return nil, err
}
// create map of matching secrets for easy lookup
foundSecrets := make(map[string]string)
foundSecretNames := []string{}
for _, secret := range secrets {
foundSecrets[secret.Spec.Annotations.Name] = secret.ID
foundSecretNames = append(foundSecretNames, secret.Spec.Annotations.Name)
}
// mimics the simple syntax for `docker service create --secret foo`
// and the code is based on the docker cli
for _, opts := range secretOpts.Value() {
secretName := opts.SecretName
if _, exists := requestedSecrets[secretName]; exists {
return nil, fmt.Errorf("duplicate secret target for %s not allowed", secretName)
}
id, ok := foundSecrets[secretName]
if !ok {
return nil, fmt.Errorf("secret not found: %s; possible choices:\n%v", secretName, foundSecretNames)
}
options := new(swarm.SecretReference)
*options = *opts
options.SecretID = id
requestedSecrets[secretName] = true
values = append(values, options)
}
return values, nil
}