/
policies.go
461 lines (391 loc) · 11.3 KB
/
policies.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package cmd
import (
"context"
"fmt"
"os"
"sort"
"strings"
"sync"
"text/tabwriter"
"github.com/juju/ansiterm"
"github.com/urfave/cli"
"github.com/manifoldco/torus-cli/api"
"github.com/manifoldco/torus-cli/config"
"github.com/manifoldco/torus-cli/envelope"
"github.com/manifoldco/torus-cli/errs"
"github.com/manifoldco/torus-cli/identity"
"github.com/manifoldco/torus-cli/prompts"
"github.com/manifoldco/torus-cli/ui"
"github.com/manifoldco/torus-cli/validate"
)
func init() {
policies := cli.Command{
Name: "policies",
Usage: "Manage which resources machines and users can access",
Category: "ACCESS CONTROL",
Subcommands: []cli.Command{
{
Name: "list",
Usage: "List all policies for an organization",
Flags: []cli.Flag{
orgFlag("The org to show policies for", false),
},
Action: chain(
ensureDaemon, ensureSession, loadDirPrefs, loadPrefDefaults,
checkRequiredFlags, listPoliciesCmd,
),
},
{
Name: "view",
Usage: "Display the contents of a policy",
ArgsUsage: "<policy>",
Flags: []cli.Flag{
orgFlag("The org the policy belongs to", false),
},
Action: chain(
ensureDaemon, ensureSession, loadDirPrefs, loadPrefDefaults,
checkRequiredFlags, viewPolicyCmd,
),
},
{
Name: "detach",
Usage: "Detach (but not delete) a policy from a team or machine role",
ArgsUsage: "<name> <team|machine-role>",
Flags: []cli.Flag{
orgFlag("The org the team and policy belong to", true),
},
Action: chain(
ensureDaemon, ensureSession, loadDirPrefs, loadPrefDefaults,
checkRequiredFlags, detachPolicyCmd,
),
},
{
Name: "attach",
Usage: "Attach a policy to a team or machine role",
ArgsUsage: "<name> <team|machine-role>",
Flags: []cli.Flag{
orgFlag("The org the team and policy belong to", true),
},
Action: chain(
ensureDaemon, ensureSession, loadDirPrefs, loadPrefDefaults,
checkRequiredFlags, attachPolicyCmd,
),
},
{
Name: "delete",
Usage: "Delete a policy from the organization",
ArgsUsage: "<name>",
Flags: []cli.Flag{
stdAutoAcceptFlag,
orgFlag("The org the policy belongs to", true),
},
Action: chain(
ensureDaemon, ensureSession, loadDirPrefs, loadPrefDefaults,
checkRequiredFlags, deletePolicyCmd,
),
},
},
}
Cmds = append(Cmds, policies)
}
const policyDetachFailed = "Could not detach policy."
const policyAttachFailed = "Could not attach policy."
const policyDeleteFailed = "Could not delete policy."
func attachPolicyCmd(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
args := ctx.Args()
if len(args) < 2 {
return errs.NewUsageExitError("Not enough arguments provided", ctx)
} else if len(args) > 2 {
return errs.NewUsageExitError("Too many arguments provided", ctx)
}
policyName := args[0]
teamName := args[1]
if err := validate.PolicyName(policyName); err != nil {
return errs.NewUsageExitError("Invalid policy name provided", ctx)
}
if err := validate.TeamName(teamName); err != nil {
return errs.NewUsageExitError("Invalid team name provided", ctx)
}
client := api.NewClient(cfg)
c := context.Background()
org, policy, team, err := getOrgPolicyAndTeam(c, client, ctx.String("org"), policyName, teamName)
if err != nil {
return err
}
err = client.Policies.Attach(c, org.ID, policy.ID, team.ID)
if err != nil {
return errs.NewErrorExitError(policyAttachFailed, err)
}
fmt.Printf("Policy %s has been attached to team %s!\n",
policy.Body.Policy.Name,
team.Body.Name,
)
return nil
}
func getOrgPolicyAndTeam(ctx context.Context, client *api.Client, orgName,
policyName, teamName string) (*envelope.Org, *envelope.Policy, *envelope.Team, error) {
org, err := client.Orgs.GetByName(ctx, orgName)
if err != nil {
return nil, nil, nil, errs.NewErrorExitError(policyDetachFailed, err)
}
if org == nil {
return nil, nil, nil, errs.NewExitError("Org not found")
}
var waitPolicy sync.WaitGroup
waitPolicy.Add(2)
var team *envelope.Team
var policy *envelope.Policy
var pErr, tErr error
go func() {
var policies []envelope.Policy
policies, pErr = client.Policies.List(ctx, org.ID, "")
for _, p := range policies {
if p.Body.Policy.Name == policyName {
policy = &p
break
}
}
waitPolicy.Done()
}()
go func() {
teams, tErr := client.Teams.GetByName(ctx, org.ID, teamName)
if len(teams) < 1 || tErr != nil {
waitPolicy.Done()
return
}
team = &teams[0]
waitPolicy.Done()
}()
waitPolicy.Wait()
if tErr != nil || pErr != nil {
return nil, nil, nil, errs.MultiError(
tErr,
pErr,
)
}
if team == nil {
return nil, nil, nil, errs.NewExitError("Team " + teamName + " not found.")
}
if policy == nil {
return nil, nil, nil, errs.NewExitError("Policy " + policyName + " not found.")
}
return org, policy, team, nil
}
func detachPolicyCmd(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
args := ctx.Args()
if len(args) < 2 {
return errs.NewUsageExitError("Too few arguments", ctx)
} else if len(args) > 2 {
return errs.NewUsageExitError("Too many arguments", ctx)
}
policyName := args[0]
teamName := args[1]
if err := validate.PolicyName(policyName); err != nil {
return errs.NewUsageExitError("Invalid policy name provided", ctx)
}
if err := validate.TeamName(teamName); err != nil {
return errs.NewUsageExitError("Invalid team name provided", ctx)
}
client := api.NewClient(cfg)
c := context.Background()
// Look up the target org
org, policy, team, err := getOrgPolicyAndTeam(c, client, ctx.String("org"), policyName, teamName)
if err != nil {
return err
}
attachments, err := client.Policies.AttachmentsList(c, org.ID, team.ID, policy.ID)
if err != nil {
return errs.NewErrorExitError(policyDetachFailed, err)
}
if len(attachments) < 1 {
return errs.NewExitError(policyName + " policy is not currently attached to " + teamName)
}
err = client.Policies.Detach(c, attachments[0].ID)
if err != nil {
if strings.Contains(err.Error(), "system team") {
return errs.NewExitError("Cannot delete system team attachment")
}
return errs.NewErrorExitError(policyDetachFailed, err)
}
fmt.Println("Policy " + policyName + " has been detached from team " + teamName)
return nil
}
const policyListFailed = "Could not list policies."
func deletePolicyCmd(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
client := api.NewClient(cfg)
c := context.Background()
args := ctx.Args()
if len(args) != 1 {
return errs.NewUsageExitError("A policy name must be provided", ctx)
}
policyName := args[0]
if err := validate.PolicyName(policyName); err != nil {
return errs.NewUsageExitError("Invalid policy name provided", ctx)
}
org, err := client.Orgs.GetByName(c, ctx.String("org"))
if err != nil {
return errs.NewErrorExitError(policyDeleteFailed, err)
}
if org == nil {
return errs.NewExitError("Org not found.")
}
policies, err := client.Policies.List(c, org.ID, policyName)
if err != nil {
return errs.NewErrorExitError(policyDeleteFailed, err)
}
if len(policies) == 0 {
return errs.NewExitError("Policy not found.")
}
policy := policies[0]
preamble := fmt.Sprintf("You are about to delete the %s policy and all "+
"of it's attachments. This cannot be undone.", policyName)
success, err := prompts.Confirm(nil, &preamble, true, true)
if err != nil {
return errs.NewErrorExitError("Failed to retrieve confirmation", err)
}
if !success {
return errs.ErrAbort
}
err = client.Policies.Delete(c, policy.ID)
if err != nil {
return errs.NewErrorExitError(policyDeleteFailed, err)
}
fmt.Printf("\nPolicy %s and all of it's attachments have been deleted.\n", policyName)
return nil
}
func listPoliciesCmd(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
client := api.NewClient(cfg)
c := context.Background()
org, _, _, err := selectOrg(c, client, ctx.String("org"), false)
if err != nil {
return err
}
var getAttachments, display sync.WaitGroup
getAttachments.Add(3)
display.Add(1)
var policies []envelope.Policy
var pErr error
go func() {
policies, pErr = client.Policies.List(c, org.ID, "")
getAttachments.Done()
}()
var attachments []envelope.PolicyAttachment
var aErr error
go func() {
attachments, aErr = client.Policies.AttachmentsList(c, org.ID, nil, nil)
getAttachments.Done()
}()
var teams []envelope.Team
var tErr error
go func() {
teams, tErr = client.Teams.GetByOrg(c, org.ID)
getAttachments.Done()
}()
if aErr != nil || pErr != nil || tErr != nil {
return errs.MultiError(
pErr,
aErr,
tErr,
errs.NewExitError(policyListFailed),
)
}
teamsByID := make(map[identity.ID]envelope.Team)
policiesByName := make(map[string]envelope.Policy)
attachedTeamsByPolicyID := make(map[identity.ID][]string)
var sortedNames []string
go func() {
getAttachments.Wait()
for _, t := range teams {
teamsByID[*t.ID] = t
}
for _, p := range policies {
policiesByName[p.Body.Policy.Name] = p
sortedNames = append(sortedNames, p.Body.Policy.Name)
}
sort.Strings(sortedNames)
for _, a := range attachments {
ID := *a.Body.PolicyID
attachedTeamsByPolicyID[ID] = append(attachedTeamsByPolicyID[ID], teamsByID[*a.Body.OwnerID].Body.Name)
}
display.Done()
}()
display.Wait()
fmt.Println("")
w := ansiterm.NewTabWriter(os.Stdout, 0, 0, 4, ' ', 0)
fmt.Fprintf(w, "%s\t%s\t%s\n", ui.BoldString("Policy Name"), ui.BoldString("Type"), ui.BoldString("Attached To"))
for _, name := range sortedNames {
teamNames := ""
policy := policiesByName[name]
policyID := *policy.ID
if len(attachedTeamsByPolicyID[policyID]) > 0 {
teamNames = strings.Join(attachedTeamsByPolicyID[policyID], ", ")
}
fmt.Fprintf(w, "%s\t%s\t%s\n", policy.Body.Policy.Name, policy.Body.PolicyType, teamNames)
}
w.Flush()
fmt.Println("")
return nil
}
func viewPolicyCmd(ctx *cli.Context) error {
args := ctx.Args()
if len(args) != 1 {
msg := "policy name is required."
if len(args) > 1 {
msg = "Too many arguments provided."
}
return errs.NewUsageExitError(msg, ctx)
}
policyName := args[0]
if err := validate.PolicyName(policyName); err != nil {
return errs.NewUsageExitError("Invalid policy name provided", ctx)
}
cfg, err := config.LoadConfig()
if err != nil {
return err
}
client := api.NewClient(cfg)
c := context.Background()
org, _, _, err := selectOrg(c, client, ctx.String("org"), false)
if err != nil {
return err
}
policies, err := client.Policies.List(c, org.ID, policyName)
if err != nil {
return errs.NewExitError("Unable to list policies.")
}
if len(policies) < 1 {
return errs.NewExitError("Policy '" + policyName + "' not found.")
}
policy := policies[0]
p := policy.Body.Policy
w := tabwriter.NewWriter(os.Stdout, 2, 0, 1, ' ', 0)
fmt.Fprintf(w, "%s\t%s\n", ui.BoldString("Name:"), p.Name)
fmt.Fprintf(w, "%s\t%s\n", ui.BoldString("Description:"), p.Description)
fmt.Fprintln(w, "")
w.Flush()
for _, stmt := range p.Statements {
rpath, err := displayResourcePath(stmt.Resource)
if err != nil {
return errs.NewErrorExitError("Could not parse resource path", err)
}
fmt.Fprintf(w, "%s\t%s\t%s\n", stmt.Effect.String(), stmt.Action.ShortString(), rpath)
}
w.Flush()
return nil
}