This repository has been archived by the owner on Feb 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
generate.go
301 lines (250 loc) · 8.15 KB
/
generate.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
package secrethub
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/secrethub/secrethub-cli/internals/cli"
"github.com/secrethub/secrethub-cli/internals/cli/clip"
"github.com/secrethub/secrethub-cli/internals/cli/ui"
"github.com/secrethub/secrethub-go/internals/api"
"github.com/secrethub/secrethub-go/internals/errio"
"github.com/secrethub/secrethub-go/pkg/randchar"
"github.com/docker/go-units"
"github.com/spf13/cobra"
)
var (
errGenerate = errio.Namespace("generate")
// ErrInvalidRandLength is returned when an invalid length is given.
ErrInvalidRandLength = errGenerate.Code("invalid_rand_length").Error("The secret length must be larger than 0")
ErrCannotUseLengthArgAndFlag = errGenerate.Code("length_arg_and_flag").Error("length cannot be provided as an argument and a flag at the same time")
ErrCouldNotFindCharSet = errGenerate.Code("charset_not_found").ErrorPref("could not find charset: %s")
ErrMinFlagInvalidInteger = errGenerate.Code("min_flag_invalid_int").ErrorPref("second part of --min flag is not an integer: %s")
ErrInvalidMinFlag = errGenerate.Code("min_flag_invalid").ErrorPref("min flag must be of the form <charset name>:<minimum count>, invalid min flag: %s")
)
const defaultLength = 22
// GenerateSecretCommand generates a new secret and writes to the output path.
type GenerateSecretCommand struct {
symbolsFlag bool
generator randchar.Generator
io ui.IO
lengthFlag intValue
firstArg cli.StringValue
secondArg cli.StringValue
lengthArg intValue
charsetFlag charsetValue
mins minRuleValue
copyToClipboard bool
newClient newClientFunc
clipWriter ClipboardWriter
}
// NewGenerateSecretCommand creates a new GenerateSecretCommand.
func NewGenerateSecretCommand(io ui.IO, newClient newClientFunc) *GenerateSecretCommand {
return &GenerateSecretCommand{
io: io,
newClient: newClient,
clipWriter: &ClipboardWriterAutoClear{
clipper: clip.NewClipboard(),
},
}
}
// Register registers the command, arguments and flags on the provided Registerer.
func (cmd *GenerateSecretCommand) Register(r cli.Registerer) {
clause := r.Command("generate", "Generate a random secret.")
clause.Flags().VarP(&cmd.lengthFlag, "length", "l", "The length of the generated secret.")
clause.Cmd.Flag("length").DefValue = strconv.Itoa(defaultLength)
clause.Flags().Var(&cmd.mins, "min", "<charset>:<n> Ensure that the resulting password contains at least n characters from the given character set. Note that adding constraints reduces the strength of the secret. When possible, avoid any constraints.")
clause.Flags().BoolVarP(&cmd.copyToClipboard, "clip", "c", false, "Copy the generated value to the clipboard. The clipboard is automatically cleared after "+units.HumanDuration(clearClipboardAfter)+".")
_ = cmd.charsetFlag.Set("alphanumeric")
clause.Flags().Var(&cmd.charsetFlag, "charset", "Define the set of characters to randomly generate a password from. Options are all, alphanumeric, numeric, lowercase, uppercase, letters, symbols and human-readable. Multiple character sets can be combined by supplying them in a comma separated list.")
clause.Cmd.Flag("charset").DefValue = "alphanumeric"
_ = clause.Cmd.RegisterFlagCompletionFunc("charset", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"all", "alphanumeric", "numeric", "lowercase", "uppercase", "letters", "symbols", "human-readable"}, cobra.ShellCompDirectiveDefault
})
clause.Flags().BoolVarP(&cmd.symbolsFlag, "symbols", "s", false, "Include symbols in secret.")
clause.Cmd.Flag("symbols").Hidden = true
clause.BindAction(cmd.Run)
clause.BindArguments([]cli.Argument{
{Value: &cmd.firstArg, Name: "secret-path", Required: true, Placeholder: secretPathPlaceHolder, Description: "The path to write the generated secret to."},
{Value: &cmd.secondArg, Name: "rand-command", Required: false, Hidden: true},
{Value: &cmd.lengthArg, Name: "length", Required: false, Hidden: true},
})
}
// before configures the command using the flag values.
func (cmd *GenerateSecretCommand) before() error {
useSymbols, err := cmd.useSymbols()
if err != nil {
return err
}
charset := cmd.charsetFlag.v
if useSymbols {
charset = charset.Add(randchar.Symbols)
}
cmd.generator, err = randchar.NewRand(charset, cmd.mins.v...)
if err != nil {
return err
}
return nil
}
// Run generates a new secret and writes to the output path.
func (cmd *GenerateSecretCommand) Run() error {
err := cmd.before()
if err != nil {
return err
}
return cmd.run()
}
// run generates a new secret and writes to the output path.
func (cmd *GenerateSecretCommand) run() error {
length, err := cmd.length()
if err != nil {
return err
}
path, err := cmd.path()
if err != nil {
return err
}
if length <= 0 {
return ErrInvalidRandLength
}
data, err := cmd.generator.Generate(length)
if err != nil {
return err
}
client, err := cmd.newClient()
if err != nil {
return err
}
version, err := client.Secrets().Write(path, data)
if err != nil {
return err
}
fmt.Fprintf(cmd.io.Output(), "A randomly generated secret has been written to %s:%d.\n", path, version.Version)
if cmd.copyToClipboard {
err = cmd.clipWriter.Write(data)
if err != nil {
return err
}
fmt.Fprintf(
cmd.io.Output(),
"The generated value has been copied to the clipboard. It will be cleared after %s.\n",
units.HumanDuration(clearClipboardAfter),
)
}
return nil
}
func (cmd *GenerateSecretCommand) length() (int, error) {
if cmd.lengthArg.IsSet() && cmd.lengthFlag.IsSet() {
return 0, ErrCannotUseLengthArgAndFlag
}
if cmd.lengthFlag.IsSet() {
return cmd.lengthFlag.Get(), nil
}
if cmd.lengthArg.IsSet() {
return cmd.lengthArg.Get(), nil
}
return defaultLength, nil
}
func (cmd *GenerateSecretCommand) path() (string, error) {
if cmd.firstArg.Value == "rand" {
return cmd.secondArg.Value, api.ValidateSecretPath(cmd.secondArg.Value)
}
if cmd.secondArg.Value != "" {
return "", fmt.Errorf("unexpected %s", cmd.secondArg.Value)
}
if cmd.lengthArg.IsSet() {
return "", fmt.Errorf("unexpected %d", cmd.lengthArg.Get())
}
return cmd.firstArg.Value, api.ValidateSecretPath(cmd.firstArg.Value)
}
func (cmd *GenerateSecretCommand) useSymbols() (bool, error) {
if cmd.symbolsFlag {
return true, nil
}
useSymbolsEnv := os.Getenv("SECRETHUB_GENERATE_RAND_SYMBOLS")
if useSymbolsEnv != "" {
b, err := strconv.ParseBool(useSymbolsEnv)
if err != nil {
return false, err
}
return b, nil
}
return false, nil
}
type minRuleValue struct {
v []randchar.Option
}
func (ov *minRuleValue) Type() string {
return "minRuleValue"
}
func (ov *minRuleValue) String() string {
return ""
}
func (ov *minRuleValue) Set(flagValue string) error {
elements := strings.Split(flagValue, ":")
if len(elements) != 2 {
return ErrInvalidMinFlag(flagValue)
}
count, err := strconv.Atoi(elements[1])
if err != nil {
return ErrMinFlagInvalidInteger(elements[1])
}
charset, found := randchar.CharsetByName(elements[0])
if !found {
return ErrCouldNotFindCharSet(elements[0])
}
ov.v = append(ov.v, randchar.Min(count, charset))
return nil
}
func (ov *minRuleValue) IsCumulative() bool {
return true
}
type charsetValue struct {
v randchar.Charset
}
func (cv *charsetValue) Type() string {
return "charsetValue"
}
func (cv *charsetValue) String() string {
return ""
}
func (cv *charsetValue) Set(flagValue string) error {
charsetNames := strings.Split(flagValue, ",")
for _, charsetName := range charsetNames {
charset, ok := randchar.CharsetByName(charsetName)
if !ok {
return ErrCouldNotFindCharSet(charsetName)
}
cv.v = cv.v.Add(charset)
}
return nil
}
func (cv *charsetValue) IsCumulative() bool {
return true
}
type intValue struct {
v *int
}
func (iv *intValue) Type() string {
return "intValue"
}
func (iv *intValue) Get() int {
if iv.v == nil {
return 0
}
return *iv.v
}
func (iv *intValue) IsSet() bool {
return iv.v != nil
}
func (iv *intValue) Set(s string) error {
f, err := strconv.ParseFloat(s, 64)
if err == nil {
v := (int)(f)
iv.v = &v
}
return err
}
func (iv *intValue) String() string {
return fmt.Sprintf("%v", iv.v)
}