-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.go
328 lines (281 loc) · 8.11 KB
/
plugin.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
// Package keyring provides password store functionality.
package keyring
import (
"bufio"
"context"
_ "embed"
"errors"
"fmt"
"os"
"strings"
"golang.org/x/term"
"github.com/launchrctl/launchr"
"github.com/launchrctl/launchr/pkg/action"
"github.com/launchrctl/launchr/pkg/jsonschema"
)
const (
procGetKeyValue = "keyring.GetKeyValue"
errTplNotFoundURL = "%s not found in keyring. Use `%s keyring:login` to add it."
errTplNotFoundKey = "%s not found in keyring. Use `%s keyring:set` to add it."
)
var passphrase string
var (
//go:embed action.login.yaml
actionLoginYaml []byte
//go:embed action.logout.yaml
actionLogoutYaml []byte
//go:embed action.set.yaml
actionSetYaml []byte
//go:embed action.unset.yaml
actionUnsetYaml []byte
//go:embed action.purge.yaml
actionPurgeYaml []byte
)
func init() {
launchr.RegisterPlugin(&Plugin{})
}
// Plugin is [launchr.Plugin] plugin providing a keyring.
type Plugin struct {
k Keyring
cfg launchr.Config
}
// PluginInfo implements [launchr.Plugin] interface.
func (p *Plugin) PluginInfo() launchr.PluginInfo {
return launchr.PluginInfo{}
}
// OnAppInit implements [launchr.Plugin] interface.
func (p *Plugin) OnAppInit(app launchr.App) error {
app.GetService(&p.cfg)
p.k = newKeyringService(p.cfg)
app.AddService(p.k)
var m action.Manager
app.GetService(&m)
addValueProcessors(m, p.k)
return nil
}
// GetKeyValueProcessorOptions is a [action.ValueProcessorOptions] struct.
type GetKeyValueProcessorOptions struct {
Key string `yaml:"key"`
}
// Validate implements [action.ValueProcessorOptions] interface.
func (o *GetKeyValueProcessorOptions) Validate() error {
if o.Key == "" {
return fmt.Errorf(`option "key" is required for %q processor`, procGetKeyValue)
}
return nil
}
// addValueProcessors adds a keyring [action.ValueProcessor] to [action.Manager].
func addValueProcessors(m action.Manager, keyring Keyring) {
m.AddValueProcessor(procGetKeyValue, action.GenericValueProcessor[*GetKeyValueProcessorOptions]{
Types: []jsonschema.Type{jsonschema.String},
Fn: func(v any, opts *GetKeyValueProcessorOptions, ctx action.ValueProcessorContext) (any, error) {
return processGetByKey(v, opts, ctx, keyring)
},
})
}
func processGetByKey(value any, opts *GetKeyValueProcessorOptions, ctx action.ValueProcessorContext, k Keyring) (any, error) {
val, ok := value.(string)
if !ok && value != nil {
return val, fmt.Errorf(
"string type is expected for %q processor. Change value type or remove the processor",
procGetKeyValue,
)
}
if ctx.IsChanged {
launchr.Term().Warning().Printfln("Skipping processor %q, value is not empty. Value will remain unchanged", procGetKeyValue)
launchr.Log().Warn("skipping processor, value is not empty", "processor", procGetKeyValue)
return value, nil
}
v, err := k.GetForKey(opts.Key)
if err != nil {
return value, buildNotFoundError(opts.Key, errTplNotFoundKey, err)
}
return v.Value, nil
}
// DiscoverActions implements [launchr.ActionDiscoveryPlugin] interface.
func (p *Plugin) DiscoverActions(_ context.Context) ([]*action.Action, error) {
// Action login.
loginCmd := action.NewFromYAML("keyring:login", actionLoginYaml)
loginCmd.SetRuntime(action.NewFnRuntime(func(_ context.Context, a *action.Action) error {
input := a.Input()
creds := CredentialsItem{
Username: input.Opt("username").(string),
Password: input.Opt("password").(string),
URL: input.Opt("url").(string),
}
return login(p.k, creds)
}))
// Action logout.
logoutCmd := action.NewFromYAML("keyring:logout", actionLogoutYaml)
logoutCmd.SetRuntime(action.NewFnRuntime(func(_ context.Context, a *action.Action) error {
input := a.Input()
all := input.Opt("all").(bool)
if all == input.IsArgChanged("url") {
return fmt.Errorf("please, either provide an URL or use --all flag")
}
url, _ := input.Arg("url").(string)
return logout(p.k, url, all)
}))
// Action set.
setKeyCmd := action.NewFromYAML("keyring:set", actionSetYaml)
setKeyCmd.SetRuntime(action.NewFnRuntime(func(_ context.Context, a *action.Action) error {
input := a.Input()
key := KeyValueItem{
Key: input.Arg("key").(string),
}
key.Value, _ = input.Arg("value").(string)
return saveKey(p.k, key)
}))
// Action unset.
unsetKeyCmd := action.NewFromYAML("keyring:unset", actionUnsetYaml)
unsetKeyCmd.SetRuntime(action.NewFnRuntime(func(_ context.Context, a *action.Action) error {
input := a.Input()
all := input.Opt("all").(bool)
if all == input.IsArgChanged("key") {
return fmt.Errorf("please, either target key or use --all flag")
}
key, _ := input.Arg("key").(string)
return removeKey(p.k, key, all)
}))
// Action purge.
purgeCmd := action.NewFromYAML("keyring:purge", actionPurgeYaml)
purgeCmd.SetRuntime(action.NewFnRuntime(func(_ context.Context, _ *action.Action) error {
return purge(p.k)
}))
return []*action.Action{
loginCmd,
logoutCmd,
setKeyCmd,
unsetKeyCmd,
purgeCmd,
}, nil
}
// CobraAddCommands implements [launchr.CobraPlugin] interface to provide keyring functionality.
func (p *Plugin) CobraAddCommands(rootCmd *launchr.Command) error {
rootCmd.PersistentFlags().StringVarP(&passphrase, "keyring-passphrase", "", "", "Passphrase for keyring encryption/decryption")
return nil
}
func buildNotFoundError(item, template string, err error) error {
if !errors.Is(err, ErrNotFound) {
return err
}
version := launchr.Version()
return fmt.Errorf(template, item, version.Name)
}
func login(k Keyring, creds CredentialsItem) error {
// Ask for login elements if some elements are empty.
if creds.isEmpty() {
err := RequestCredentialsFromTty(&creds)
if err != nil {
return err
}
}
err := k.AddItem(creds)
if err != nil {
return err
}
return k.Save()
}
func saveKey(k Keyring, item KeyValueItem) error {
// Ask for login elements if some elements are empty.
if item.isEmpty() {
err := RequestKeyValueFromTty(&item)
if err != nil {
return err
}
}
err := k.AddItem(item)
if err != nil {
return err
}
return k.Save()
}
// RequestCredentialsFromTty gets credentials from tty.
func RequestCredentialsFromTty(creds *CredentialsItem) error {
return withTerminal(func(in, out *os.File) error {
return credentialsFromTty(creds, in, out)
})
}
func credentialsFromTty(creds *CredentialsItem, in *os.File, out *os.File) error {
reader := bufio.NewReader(in)
if creds.URL == "" {
fmt.Fprint(out, "URL: ")
url, err := reader.ReadString('\n')
if err != nil {
return err
}
creds.URL = strings.TrimSpace(url)
}
if creds.Username == "" {
fmt.Fprint(out, "Username: ")
username, err := reader.ReadString('\n')
if err != nil {
return err
}
creds.Username = strings.TrimSpace(username)
}
if creds.Password == "" {
fmt.Fprint(out, "Password: ")
bytePassword, err := term.ReadPassword(int(in.Fd()))
fmt.Fprint(out, "\n")
if err != nil {
return err
}
creds.Password = strings.TrimSpace(string(bytePassword))
}
return nil
}
// RequestKeyValueFromTty gets key-value pair from tty.
func RequestKeyValueFromTty(item *KeyValueItem) error {
return withTerminal(func(in, out *os.File) error {
return keyValueFromTty(item, in, out)
})
}
func keyValueFromTty(item *KeyValueItem, in *os.File, out *os.File) error {
reader := bufio.NewReader(in)
if item.Key == "" {
fmt.Fprint(out, "Key: ")
username, err := reader.ReadString('\n')
if err != nil {
return err
}
item.Key = strings.TrimSpace(username)
}
if item.Value == "" {
fmt.Fprint(out, "Value: ")
byteValue, err := term.ReadPassword(int(in.Fd()))
fmt.Fprint(out, "\n")
if err != nil {
return err
}
item.Value = strings.TrimSpace(string(byteValue))
}
return nil
}
func logout(k Keyring, url string, all bool) error {
var err error
if all {
err = k.CleanStorage(CredentialsItem{})
} else {
err = k.RemoveByURL(url)
}
if err != nil {
return buildNotFoundError(url, errTplNotFoundURL, err)
}
return k.Save()
}
func removeKey(k Keyring, key string, all bool) error {
var err error
if all {
err = k.CleanStorage(KeyValueItem{})
} else {
err = k.RemoveByKey(key)
}
if err != nil {
return buildNotFoundError(key, errTplNotFoundKey, err)
}
return k.Save()
}
func purge(k Keyring) error {
return k.Destroy()
}