-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
345 lines (318 loc) · 11 KB
/
main.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
package main
import (
// "context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strconv"
"text/template"
// "github.com/docker/docker/api/types"
// "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
// "github.com/docker/docker/pkg/stdcopy"
"github.com/docker/go-plugins-helpers/secrets"
vaultapi "github.com/hashicorp/vault/api"
"github.com/sirupsen/logrus"
)
const (
// Can be set to "vault_token" to return a vault token
typeLabel = "docker.plugin.secretprovider.vault.type"
vaultTokenType = "vault_token"
// Can be set to "true" to wrap the contents of the secret
wrapLabel = "docker.plugin.secretprovider.vault.wrap"
// Read secret from this path
pathLabel = "docker.plugin.secretprovider.vault.path"
// Read this field from the secret (defaults to "value")
fieldLabel = "docker.plugin.secretprovider.vault.field"
// If using v2 key/value backend, use this version of the secret
versionLabel = "docker.plugin.secretprovider.vault.version"
// Return JSON encoded map of secret if set to "true"
formatLabel = "docker.plugin.secretprovider.vault.format"
// socket address
socketAddress = "/run/docker/plugins/vault.sock"
)
var (
log = logrus.New()
policyTemplateExpression string
policyTemplate *template.Template
// secretZero string
)
type vaultSecretsDriver struct {
dockerClient *client.Client
vaultClient *vaultapi.Client
}
func (d vaultSecretsDriver) Get(req secrets.Request) secrets.Response {
errorResponse := func(s string, err error) secrets.Response {
log.Errorf("Error getting secret %q: %s: %v", req.SecretName, s, err)
return secrets.Response{
Value: []byte("-"),
Err: fmt.Sprintf("%s: %v", s, err),
}
}
valueResponse := func(s string) secrets.Response {
return secrets.Response{
Value: []byte(s),
DoNotReuse: true,
}
}
// First use secret zero client to create a service token
// var policies []string
// if policyTemplate == nil {
// policies = []string{req.ServiceName}
// } else {
// policiesBuffer := bytes.NewBuffer(nil)
// tmpl, err := policyTemplate.Clone()
// if err != nil {
// log.Fatalf("Error cloning template: %v", err)
// }
// if err := tmpl.Funcs(template.FuncMap{
// "ServiceLabel": func(name string) (string, error) {
// value, exists := req.ServiceLabels[name]
// if !exists {
// return "", fmt.Errorf("No such service label: %q", name)
// }
// return value, nil
// },
// }).Execute(policiesBuffer, req); err != nil {
// log.Fatalf("Error executing policy template: %v", err)
// }
// policies = strings.Split(policiesBuffer.String(), ",")
// if len(policies) == 0 {
// log.Fatalf("Empty policies list after executing template %q", policyTemplateExpression)
// }
// }
// serviceToken, err := d.vaultClient.Auth().Token().Create(&vaultapi.TokenCreateRequest{
// Policies: policies,
// })
// if err != nil {
// policiesString := strings.Join(policies, ",")
// return errorResponse(fmt.Sprintf("Error creating service token with policies like %q", policiesString), err)
// }
// Create a Vault client limited to the service token
// var serviceVaultClient *vaultapi.Client
// vaultConfig := vaultapi.DefaultConfig()
// if c, err := vaultapi.NewClient(vaultConfig); err != nil {
// log.Fatalf("Error creating Vault client: %v", err)
// } else {
// c.SetToken(serviceToken.Auth.ClientToken)
// serviceVaultClient = c
// defer serviceVaultClient.Auth().Token().RevokeSelf(serviceToken.Auth.ClientToken)
// }
// serviceVaultClient.SetToken(serviceToken.Auth.ClientToken)
// Tips: as we use global token, so no need to create policy and token for each services.
serviceVaultClient := d.vaultClient
// Inspect the secret to read its labels
var vaultWrapValue bool
if v, exists := req.SecretLabels[wrapLabel]; exists {
if v, err := strconv.ParseBool(v); err == nil {
vaultWrapValue = v
} else {
return errorResponse(fmt.Sprintf("Error parsing boolean value of label %q", wrapLabel), err)
}
}
format := "plain"
if value, exists := req.SecretLabels[formatLabel]; exists {
format = value
}
switch req.SecretLabels[typeLabel] {
case vaultTokenType:
// Create a token
// TODO: Set reasonable default values, and allow configuring them through secret labels
secret, err := serviceVaultClient.Auth().Token().Create(&vaultapi.TokenCreateRequest{
Lease: "1h",
// Policies: policies,
Metadata: map[string]string{
"created_by": os.Args[0],
// TODO: Add any other interesting metadata
},
})
if err != nil {
return errorResponse("Error creating token in Vault", err)
}
switch format {
case "meta+json":
resultBytes, err := json.Marshal(secret)
if err != nil {
return errorResponse("Error marshalling secret", err)
}
return valueResponse(string(resultBytes))
case "json":
resultBytes, err := json.Marshal(secret.Auth.ClientToken)
if err != nil {
return errorResponse("Error marshalling secret", err)
}
return valueResponse(string(resultBytes))
case "plain":
return valueResponse(secret.Auth.ClientToken)
default:
return errorResponse("Unexpected format", errors.New(format))
}
default:
var secret *vaultapi.Secret
// Read from KV secrets mount
field := ""
if fieldName, exists := req.SecretLabels[fieldLabel]; exists {
field = fieldName
}
path := fmt.Sprintf("secret/data/%s", req.SecretName)
if v, exists := req.SecretLabels[pathLabel]; exists {
path = v
}
params := make(url.Values)
if v, exists := req.SecretLabels[versionLabel]; exists {
params.Set("version", v)
}
secret, err := serviceVaultClient.Logical().ReadWithData(path, params)
if err != nil {
return errorResponse(fmt.Sprintf("Error getting kv secret from Vault at path %q", path), err)
}
if secret == nil || secret.Data == nil {
return errorResponse(fmt.Sprintf("Data is nil at path %q (secret: %#v)", path, secret), err)
}
data := secret.Data["data"]
if dataMap, ok := data.(map[string]interface{}); ok {
if !vaultWrapValue {
switch format {
case "json", "meta+json":
var resultBytes []byte
if format == "meta+json" {
resultBytes, err = json.Marshal(secret)
if err != nil {
return errorResponse("Error marshalling secret", err)
}
} else if len(field) == 0 {
resultBytes, err = json.Marshal(dataMap)
if err != nil {
return errorResponse("Error marshalling secret data map", err)
}
} else {
resultBytes, err = json.Marshal(dataMap[field])
if err != nil {
return errorResponse(fmt.Sprintf("Error marshalling secret data field %q", field), err)
}
}
return valueResponse(fmt.Sprintf("%v", string(resultBytes)))
case "plain":
if len(field) == 0 {
field = "value"
}
return valueResponse(fmt.Sprintf("%v", dataMap[field]))
default:
return errorResponse("Unexpected format", errors.New(format))
}
}
// Wrap data map
wrappedSecret, err := serviceVaultClient.Logical().Write("sys/wrapping/wrap", dataMap)
if err != nil {
return errorResponse("Error wrapping secret data", err)
}
return valueResponse(wrappedSecret.WrapInfo.Token)
}
return errorResponse("Invalid data map", err)
}
}
// Read "secret zero" from the file system of a helper service task container, then serve the plugin.
func main() {
// Create Docker client
var httpClient *http.Client
dockerAPIVersion := os.Getenv("DOCKER_API_VERSION")
cli, err := client.NewClient("unix:///var/run/docker.sock", dockerAPIVersion, httpClient, nil)
if err != nil {
log.Fatalf("Failed to create Docker client: %v", err)
}
// // Read plugin configuration from environment
// vaultHelperServiceName := os.Getenv("vault-token-service")
// secretZeroName := os.Getenv("vault-token-secret")
// // Inspect the helper service
// service, _, err := cli.ServiceInspectWithRaw(context.Background(), vaultHelperServiceName, types.ServiceInspectOptions{})
// if err != nil {
// log.Fatalf("Error inspecting helper service %q: %v", vaultHelperServiceName, err)
// }
// // Look up hostname to filter tasks
// hostname, err := os.Hostname()
// if err != nil {
// log.Fatalf("Error getting hostname: %v", err)
// }
// // Find a task on this node, as otherwise we will not be able to exec inside its container
// args := filters.NewArgs(filters.Arg("name", vaultHelperServiceName), filters.Arg("node", hostname))
// tasks, err := cli.TaskList(context.Background(), types.TaskListOptions{
// Filters: args,
// })
// if err != nil {
// log.Fatalf("Error listing tasks for service %q: %v", vaultHelperServiceName, err)
// }
// Look for a task from the helper service
// var secretZero string
// for _, task := range tasks {
// // avoid services with the name as a shared prefix but different ID
// if task.ServiceID != service.ID {
// continue
// }
// // Use a task that has a container
// containerStatus := task.Status.ContainerStatus
// if containerStatus != nil {
// // Create an exec to later read its output
// response, err := cli.ContainerExecCreate(context.Background(), containerStatus.ContainerID, types.ExecConfig{
// AttachStdout: true,
// Detach: false,
// Tty: false,
// Cmd: []string{"cat", fmt.Sprintf("/run/secrets/%s", secretZeroName)},
// })
// if err != nil {
// log.Fatalf("Error creating exec: %v", err)
// }
// // Start and attach to exec to read its output
// resp, err := cli.ContainerExecAttach(context.Background(), response.ID, types.ExecStartCheck{
// Detach: false,
// Tty: false,
// })
// if err != nil {
// log.Fatalf("Error attaching to exec: %v", err)
// }
// defer resp.Close()
// // Read the output into a buffer and convert to a string
// buf := new(bytes.Buffer)
// if _, err := stdcopy.StdCopy(buf, buf, resp.Reader); err != nil {
// if err != nil {
// log.Fatalf("Error reading secret zero: %v", err)
// }
// }
// secretZero = buf.String()
// break
// }
// }
// if len(secretZero) == 0 {
// log.Fatalf("Failed to read a Vault token from the helper service %q", vaultHelperServiceName)
// }
// Create a Vault client
vaultToken := os.Getenv("VAULT_TOKEN")
var vaultClient *vaultapi.Client
vaultConfig := vaultapi.DefaultConfig()
if c, err := vaultapi.NewClient(vaultConfig); err != nil {
log.Fatalf("Error creating Vault client: %v", err)
} else {
c.SetToken(vaultToken)
vaultClient = c
}
// Create the driver
d := vaultSecretsDriver{
dockerClient: cli,
vaultClient: vaultClient,
}
h := secrets.NewHandler(d)
// Parse policy template
// policyTemplateExpression = os.Getenv("policy-template")
// if len(policyTemplateExpression) > 0 {
// tmpl, err := template.New("policies").Parse(policyTemplateExpression)
// if err != nil {
// log.Fatalf("Error parsing policy template %q: %v", policyTemplateExpression, err)
// }
// policyTemplate = tmpl
// }
// Serve plugin
log.Infof("Listening on %s", socketAddress)
log.Error(h.ServeUnix(socketAddress, 0))
}