forked from russellsimpkins/consul-acl-mgr
/
consul-acl-mgr.go
372 lines (315 loc) · 9.43 KB
/
consul-acl-mgr.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
log "github.com/russellsimpkins/consul-acl-mgr/Godeps/_workspace/src/github.com/Sirupsen/logrus"
yaml "github.com/russellsimpkins/consul-acl-mgr/Godeps/_workspace/src/gopkg.in/yaml.v2"
)
// I need something that can read in YAML files and generate my Consul ACLs with known UUIDs
// so that I can hand out the UUIDs to my internal clients and have tight control over the ACLs
// to support revoking ACLs, updating ACLs and changing the ACL token at given intervals.
// The code here will read one or more YAML files and update the consul using the HTTP API.
// Then I can store the ACL file using git-crypt.
// for name value pairs we use in the keys and services for ACLs
type Pair struct {
Name string `yaml:"name"`
Value string `yaml:"value"`
}
// an ACL entry in our yaml file
type ACL struct {
Department string
Team string
Token string
Name string
Type string
Remove bool
Keys []Pair
Services []Pair
}
// Consul's ACLs are a little odd, in that the rules are string encoded json
type ConsulACL struct {
ID string
Name string
Type string
Rules string
}
// Consul service definition
type ConsulService struct {
Id string
Service string
Address string
Port uint64
Tags []string
}
// Consul Node definition
type ConsulNode struct {
Node string
Address string
Datacenter string
Service ConsulService
}
// the base configurion in our YAML file
type Config struct {
Consul string `yaml:"consul_cluster"` // which IP/DNS address should we be talking to
Token string `yaml:"token"` // we need the master token to keep things up to date
UpdateAcl bool `yaml:"update_acl"`
AddNodes bool `yaml:"add_nodes"`
AddKeys bool `yaml:"add_keys"`
Datacenter string
Nodes []ConsulNode
Tokens []ACL
KeyValues []Pair `yaml:"keys"`
}
// struct to output Consul ACL Rules as JSON
// e.g. {"key":{ "some/key": {"policy": "write}}}
type ACLRule struct {
Key map[string]map[string]string `json:"key"`
Service map[string]map[string]string `json:"service"`
}
// the functions we need to update consul
type ACLParser interface {
ParseYaml(yamlFile string) (err error) // parse the yaml file in the directory to read in all ACL information
SetConsulACL() (err error) // update consul via the API - should we remove all ACLs, default is false
RulesString(token ACL) (json string, err error)
AddConsulNodes() (err error)
AddConsulKvPairs() (err error)
}
// this function reads a yaml file to populate our Config struct
func (csl *Config) ParseYaml(yamlFile string) (err error) {
file, err := os.Open(yamlFile)
if err != nil {
return err
}
_ = file.Close()
data, err := ioutil.ReadFile(yamlFile)
if nil != err {
panic(err)
}
err = yaml.Unmarshal(data, csl)
if err != nil {
panic(err)
}
return
}
// Output consul ACL rules string
func (c *Config) RulesString(token ACL) (result string, err error) {
data := ACLRule{}
var body []byte
data.Key = make(map[string]map[string]string)
data.Service = make(map[string]map[string]string)
for _, pair := range token.Keys {
item := make(map[string]string)
item["policy"] = pair.Value
data.Key[pair.Name] = item
}
for _, pair := range token.Services {
item := make(map[string]string)
item["policy"] = pair.Value
data.Service[pair.Name] = item
}
body, err = json.MarshalIndent(data, "", " ")
if err != nil {
return
}
result = string(body)
return
}
// call this fuction to add nodes
func (c *Config) AddConsulNodes() (err error) {
// iterate over all nodes and take appropriate action
for _, node := range c.Nodes {
var (
request *http.Request
client *http.Client
resp *http.Response
url string
putdata []byte
)
client = &http.Client{
CheckRedirect: nil,
}
url = fmt.Sprintf("http://%s/v1/catalog/register?token=%s", c.Consul, c.Token)
log.Debugf("Attempting to register the service using URL: %s", url)
node.Datacenter = c.Datacenter
//putdata, err := json.MarshalIndent(node, "", " ")
putdata, err := json.Marshal(node)
if err != nil {
log.Fatalf("Unable to create JSON from our structure. This could only be caused by a bug in your yaml: %s", err)
return err
}
log.Debugf("The token data to PUT: %s", string(putdata))
request, err = http.NewRequest("PUT", url, nil)
if err != nil {
log.Warnf("Unable to register the node. Err: %s", err)
return err
}
reqdata := strings.NewReader(string(putdata))
request, err = http.NewRequest("PUT", url, reqdata)
resp, err = client.Do(request)
if err != nil {
log.Fatalf("There was a problem calling the Consul server: %s", err)
return err
}
if resp.StatusCode != 200 {
log.Fatalf("There was a problem calling the Consul server. Response Code %i", resp.StatusCode)
return err
}
}
return err
}
// call this fuction to add nodes
func (c *Config) AddConsulKvPairs() (err error) {
// iterate over all nodes and take appropriate action
for _, pair := range c.KeyValues {
var (
request *http.Request
client *http.Client
resp *http.Response
url string
)
client = &http.Client{
CheckRedirect: nil,
}
url = fmt.Sprintf("http://%s/v1/kv/%s?token=%s", c.Consul, pair.Name, c.Token)
log.Debugf("Attempting to register the service using URL: %s", url)
log.Debugf("The token data to PUT: %s", pair.Value)
request, err = http.NewRequest("PUT", url, nil)
if err != nil {
log.Warnf("Unable to register the node. Err: %s", err)
return err
}
reqdata := strings.NewReader(pair.Value)
request, err = http.NewRequest("PUT", url, reqdata)
resp, err = client.Do(request)
if err != nil {
log.Fatalf("There was a problem calling the Consul server: %s", err)
return err
}
if resp.StatusCode != 200 {
log.Fatalf("There was a problem calling the Consul server. Response Code %i", resp.StatusCode)
return err
}
}
return err
}
// does the logic to set the tokens on the Consul cluster
// if a token is set to be removed, it does the logic to delete
// the token.
func (c *Config) SetConsulACL() (err error) {
// iterate over all tokens and take appropriate action
for _, token := range c.Tokens {
var (
request *http.Request
client *http.Client
resp *http.Response
url string
tok ConsulACL
)
tok = ConsulACL{}
client = &http.Client{
CheckRedirect: nil,
}
tok.ID = token.Token
if token.Remove {
url = fmt.Sprintf("http://%s/v1/acl/destroy/%s?token=%s", c.Consul, tok.ID, c.Token)
log.Debugf("Attempting to destroy an ACL. Using URL: %s", url)
request, err = http.NewRequest("PUT", url, nil)
if err != nil {
log.Warnf("Unable to destroy the ACL, it's possible it was already deleted. %s", err)
}
} else {
url = fmt.Sprintf("http://%s/v1/acl/destroy/%s?token=%s", c.Consul, tok.ID, c.Token)
log.Debugf("Cancel URL: %s", url)
request, err = http.NewRequest("PUT", url, nil)
if err != nil {
log.Fatalf("Unable to issue PUT request to desroy an existing token: %s", url)
return err
}
url = fmt.Sprintf("http://%s/v1/acl/create?token=%s", c.Consul, c.Token)
log.Debugf("Create URL: %s", url)
tok.Name = token.Name
tok.Type = token.Type
tok.Rules, err = c.RulesString(token)
if err != nil {
log.Fatalf("Unable to create JSON string of the rules: %s", err)
return err
}
tokdata, err := json.MarshalIndent(tok, "", " ")
if err != nil {
log.Fatalf("Unable to create JSON from our structure. This could only be caused by a bug in your code: %s", err)
return err
}
log.Debugf("The token data to PUT: %s", string(tokdata))
reqdata := strings.NewReader(string(tokdata))
request, err = http.NewRequest("PUT", url, reqdata)
}
resp, err = client.Do(request)
if err != nil {
log.Fatalf("There was a problem calling the Consul server: %s", err)
return err
}
if resp.StatusCode != 200 {
log.Fatalf("There was a problem calling the Consul server. Response Code %i", resp.StatusCode)
return
}
}
log.Info("Ran all updates against Consul at: ", c.Consul)
return
}
// Manage your Consul ACLs using a YAML file. There are 2 flags you
// can run with -f and -v. -f specify the YAML file location and -v
// set's the log level
func main() {
yamlFile := flag.String("f", "", "/abs/path/to/yaml/file.yml that has your Consul ACL data.")
logLevel := flag.String("v", "", "set your log level, v: Warn vv: Info vvv: Debug")
flag.Parse()
switch *logLevel {
case "":
log.SetLevel(log.ErrorLevel)
case "v":
log.SetLevel(log.WarnLevel)
break
case "vv":
log.SetLevel(log.InfoLevel)
break
case "vvv":
log.SetLevel(log.DebugLevel)
}
if *yamlFile == "" {
log.Error("You need to specify a valid yaml file with the -f flag.\nconsul-acl -f /path/to/acl.yaml")
return
}
cparser := Config{}
err := cparser.ParseYaml(*yamlFile)
if err != nil {
log.Error(err)
return
}
if cparser.UpdateAcl {
log.Debug("Set Consul ACL")
err = cparser.SetConsulACL()
if err != nil {
log.Error("There were problems updating the consul server: ", err)
}
}
if cparser.AddNodes {
log.Debug("Add node(s) to Consul.")
err = cparser.AddConsulNodes()
if err != nil {
log.Error("There were problems adding nodes to consul")
}
}
if cparser.AddKeys {
log.Debug("Adding key value pair(s) to Consul.")
err = cparser.AddConsulKvPairs()
if err != nil {
log.Error("There were problems adding nodes to consul")
}
}
log.Debug("All done.")
}