/
list.go
292 lines (249 loc) · 7.48 KB
/
list.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
package cmd
import (
"context"
"fmt"
"os"
"strconv"
"sync"
"github.com/juju/ansiterm"
"github.com/urfave/cli"
"github.com/manifoldco/torus-cli/api"
"github.com/manifoldco/torus-cli/apitypes"
"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/pathexp"
"github.com/manifoldco/torus-cli/ui"
)
func init() {
list := cli.Command{
Name: "list",
ArgsUsage: "",
Usage: "List allows you to list and filter all the secrets that you can access inside a project.",
Category: "SECRETS",
Flags: []cli.Flag{
orgFlag("Use this organization.", false),
projectFlag("Use this project.", false),
envSliceFlag("Use this environment.", false),
serviceSliceFlag("Use this service.", "", false),
teamSliceFlag("Filter credentials against this team.", false),
cli.BoolFlag{
Name: "verbose, v",
Usage: "Display the full credential path of each secret.",
},
},
Action: chain(
ensureDaemon, ensureSession, loadDirPrefs, checkRequiredFlags, listCmd,
),
}
Cmds = append(Cmds, list)
}
type serviceCredentialMap map[string]credentialSet
type credentialTree map[string]serviceCredentialMap
func listCmd(ctx *cli.Context) error {
verbose := ctx.Bool("verbose")
args := ctx.Args()
cfg, err := config.LoadConfig()
if err != nil {
return err
}
client := api.NewClient(cfg)
c := context.Background()
tree := make(credentialTree)
org, _, _, err := selectOrg(c, client, ctx.String("org"), false)
if err != nil {
return err
}
project, _, _, err := selectProject(c, client, org, ctx.String("project"), false)
if err != nil {
return err
}
session, err := client.Session.Who(c)
if err != nil {
return err
}
ident := deriveIdentity(session)
// Retrieve environment flag values
// If no values were set, use a full glob
envFilters := ctx.StringSlice("environment")
if len(envFilters) == 0 {
envFilters = append(envFilters, "*")
}
// Retrieve service flag values
// If no values were set, use a full glob
serviceFilters := ctx.StringSlice("service")
if len(serviceFilters) == 0 {
serviceFilters = append(serviceFilters, "*")
}
// Retrieve team flag values
// If no values were set, use a full glob
teamFilter := ctx.StringSlice("team")
// Retrieve teams from team names
var teams []envelope.Team
var teamIDs []identity.ID
if len(teamFilter) != 0 {
// Retrieve all teams for the current org
orgTeams, err := client.Teams.GetByOrg(c, org.ID)
if err != nil {
return errs.NewErrorExitError("Failed to retrieve teams for org "+org.Body.Name+".", err)
}
if len(orgTeams) == 0 {
return errs.NewExitError("No teams for org " + org.Body.Name + ".")
}
teams, err = filterTeamsByNames(teamFilter, orgTeams)
if err != nil {
return err
}
for _, t := range teams {
teamIDs = append(teamIDs, *t.ID)
}
}
// The following two slices are placeholders necessary to
// build the PathExp later.
instanceFilters := []string{"*"}
idenityFilters := []string{"*"}
// Create a PathExp based on flags. This is the search space that
// will be used to retrieve credentials.
filterPathExp, err := pathexp.New(
org.Body.Name,
project.Body.Name,
envFilters,
serviceFilters,
instanceFilters,
idenityFilters)
if err != nil {
return errs.NewErrorExitError("Failed to create path for specified flags.", err)
}
// Retrieve envs, services and credentials in parallel
var getEnvsServicesCreds sync.WaitGroup
getEnvsServicesCreds.Add(3)
var environments []envelope.Environment
var services []envelope.Service
var credentials []apitypes.CredentialEnvelope
var eErr, sErr, cErr error
go func() {
// Get environments
environments, eErr = listEnvs(&c, client, org.ID, project.ID, teamIDs, nil)
getEnvsServicesCreds.Done()
}()
go func() {
// Get services
services, sErr = listServices(&c, client, org.ID, project.ID, teamIDs, nil)
getEnvsServicesCreds.Done()
}()
go func() {
// Get credentials
credentials, cErr = client.Credentials.Search(c, filterPathExp.String(), teamIDs, nil)
getEnvsServicesCreds.Done()
}()
getEnvsServicesCreds.Wait()
if cErr != nil {
return errs.NewErrorExitError("Could not retrieve credentials.", cErr)
}
if eErr != nil {
return errs.NewErrorExitError("Could not retrieve environments.", eErr)
}
if sErr != nil {
return errs.NewErrorExitError("Could not retrieve services.", sErr)
}
filteredEnvNames := []string{}
filteredServiceNames := []string{}
// Filter out the retrieved environments based on the
// search space provided in filterPathExp. If no flags
// were set, all environments will pass the following test.
for _, e := range environments {
if filterPathExp.Envs.Contains(e.Body.Name) {
filteredEnvNames = append(filteredEnvNames, e.Body.Name)
}
}
// Filter out the retrieved services based on the
// search space provided in filterPathExp. If no flags
// were set, all services will pass the following test.
for _, s := range services {
if filterPathExp.Services.Contains(s.Body.Name) {
filteredServiceNames = append(filteredServiceNames, s.Body.Name)
}
}
// Create credentialsTree for verbose mode
// In verbose mode, ALL paths are displayed,
// whether they contain credentials or not.
// This will be filled in the following section.
if verbose {
for _, eName := range filteredEnvNames {
tree[eName] = make(serviceCredentialMap)
for _, sName := range filteredServiceNames {
tree[eName][sName] = make(credentialSet)
}
}
}
// Check for each env and service in the filtered list, add
// any credentials along that path to that env/service branch
// of the credentialsTree
credCount := 0
for _, e := range filteredEnvNames {
for _, s := range filteredServiceNames {
builtPathExp, err := deriveExplicitPathExp(org.Body.Name, project.Body.Name,
e, s, ident)
if err != nil {
return errs.NewErrorExitError("Failed to derive path exp", err)
}
for _, cred := range credentials {
body := *cred.Body
if len(args) > 0 && !isSecretNameInList(body.GetName(), args) {
continue
}
credPathExp := body.GetPathExp()
// If cred not contained in any builtPathExps, it is not
// within the search space specified by the flags.
if !credPathExp.Contains(builtPathExp) {
continue
}
// "Add" is defined in 'credential_set.go'. This
// handles the case where a secret is redefined in
// overlapping spaces.
if tree[e] == nil {
tree[e] = make(serviceCredentialMap)
}
if tree[e][s] == nil {
tree[e][s] = make(credentialSet)
}
tree[e][s].Add(cred)
}
}
}
fmt.Println("")
w := ansiterm.NewTabWriter(os.Stdout, 0, 0, 0, ' ', 0)
for e := range tree {
fmt.Fprintf(w, fmt.Sprintf("%s\t\t\t\t\n", ui.BoldString(e)+"/"))
for s := range tree[e] {
fmt.Fprintf(w, "\t%s\t\t\t\n", ui.BoldString(s)+"/")
if len(tree[e][s]) == 0 {
if verbose {
fmt.Fprintf(w, "\t\t%s\t\t\n", ui.FaintString("[empty]"))
}
continue
}
for c, cred := range tree[e][s] {
credCount++
if verbose {
credPath := displayPathExp((*cred.Body).GetPathExp()) + "/"
fmt.Fprintf(w, "\t\t%s\t (%s)\t\n", c, ui.FaintString(credPath+c))
} else {
fmt.Fprintf(w, "\t\t%s\t\t\n", c)
}
}
}
}
w.Flush()
fmt.Printf("\n(%s) secrets found\n", ui.FaintString(strconv.Itoa(credCount)))
return nil
}
func isSecretNameInList(secret string, list []string) bool {
for _, s := range list {
if s == secret {
return true
}
}
return false
}