forked from smallstep/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyset.go
304 lines (256 loc) 路 7.31 KB
/
keyset.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
package jwk
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"syscall"
"github.com/pkg/errors"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/jose"
"github.com/urfave/cli"
)
func keysetCommand() cli.Command {
return cli.Command{
Name: "keyset",
Usage: "add, remove, and find JWKs in JWK Sets",
UsageText: "**step crypto jwk keyset** <subcommand> [arguments] [global-flags] [subcommand-flags]",
Description: `**step crypto jwk set** command group provides facilities for managing and
inspecting JWK Sets. A is a JSON object that represents a set of JWKs. They
are defined in RFC7517.
A JWK Set is simply a JSON object with a "keys" member whose value is an array
of JWKs. Additional members are allowed in the object. They will be preserved
by this tool, but otherwise ignored. Duplicate member names are not allowed.
For examples, see **step help crypto jwk**.`,
Subcommands: cli.Commands{
keysetAddCommand(),
keysetRemoveCommand(),
keysetListCommand(),
keysetFindCommand(),
},
}
}
func keysetAddCommand() cli.Command {
return cli.Command{
Name: "add",
Action: cli.ActionFunc(keysetAddAction),
Usage: "a JWK to a JWK Set",
UsageText: "**step crypto jwk keyset add** <jwks-file>",
Description: `**step crypto jwk keyset add** reads a JWK from STDIN and adds it to the JWK
Set in <jwks-file>. Modifications to <jwks-file> are in-place. The file is
'flock'd while it's being read and modified.
## POSITIONAL ARGUMENTS
<jwks-file>
: File containing a JWK Set`,
}
}
func keysetRemoveCommand() cli.Command {
return cli.Command{
Name: "remove",
Action: cli.ActionFunc(keysetRemoveAction),
Usage: "a JWK from a JWK Set",
UsageText: "**step crypto jwk keyset remove** <jwks-file> [**--kid**=<kid>]",
Description: `**step crypto jwk keyset remove** removes the JWK with a key ID matching <kid>
from the JWK Set stored in <jwks-file>. Modifications to <jwks-file> are
in-place. The file is 'flock'd while it's being read and modified.
## POSITIONAL ARGUMENTS
<jwks-file>
: File containing a JWK Set`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "kid",
Usage: `The key ID of the JWK to remove from the JWK Set. <kid> is a case-sensitive
string.`,
},
},
}
}
func keysetListCommand() cli.Command {
return cli.Command{
Name: "list",
Action: cli.ActionFunc(keysetListAction),
Usage: "key IDs of JWKs in a JWK Set",
UsageText: "**step crypto jwk keyset list** <jwks-file>",
Description: `**step crypto jwk keyset list** lists the IDs ("kid" parameters) of JWKs in a
JWK Set.
## POSITIONAL ARGUMENTS
<jwks-file>
: File containing a JWK Set`,
}
}
func keysetFindCommand() cli.Command {
return cli.Command{
Name: "find",
Action: cli.ActionFunc(keysetFindAction),
Usage: "a JWK in a JWK Set",
UsageText: "**step crypto jwk keyset find** <jwks-file> [**--kid**=<kid>]",
Description: `**step crypto jwk keyset find** command locates the JWK with a key ID matching
<kid> from the JWK Set stored in <jwks-file>. The matching JWK is printed to
STDOUT.
## POSITIONAL ARGUMENTS
<jwks-file>
: File containing a JWK Set`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "kid",
Usage: `The key ID of the JWK to locate from the JWK Set. <kid> is a case-sensitive
string.`,
},
},
}
}
func keysetAddAction(ctx *cli.Context) error {
if err := errs.NumberOfArguments(ctx, 1); err != nil {
return err
}
b, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return errors.Wrap(err, "error reading STDIN")
}
// Attempt to parse an encrypted file
if b, err = jose.Decrypt("Please enter the password to decrypt JWK", b); err != nil {
return err
}
// Unmarshal the plain (or decrypted JWK)
var jwk jose.JSONWebKey
if err = json.Unmarshal(b, &jwk); err != nil {
return errors.New("error reading JWK: unsupported format")
}
jwksFile := ctx.Args().Get(0)
jwks, writeFunc, err := rwLockKeySet(jwksFile)
if err != nil {
return err
}
// According to RFC7517 there are cases where multiple keys can share the
// same "kid". One example is if they have different "kty" values but are
// considered to be equivalent alternatives by the application using them.
jwks.Keys = append(jwks.Keys, jwk)
return writeFunc(true)
}
func keysetRemoveAction(ctx *cli.Context) error {
if err := errs.NumberOfArguments(ctx, 1); err != nil {
return err
}
kid := ctx.String("kid")
jwksFile := ctx.Args().Get(0)
jwks, writeFunc, err := rwLockKeySet(jwksFile)
if err != nil {
return err
}
// Filtering without allocating
keys := jwks.Keys[:0]
for _, key := range jwks.Keys {
if key.KeyID != kid {
keys = append(keys, key)
}
}
jwks.Keys = keys
return writeFunc(true)
}
func keysetListAction(ctx *cli.Context) error {
if err := errs.NumberOfArguments(ctx, 1); err != nil {
return err
}
jwksFile := ctx.Args().Get(0)
jwks, writeFunc, err := rwLockKeySet(jwksFile)
if err != nil {
return err
}
for _, key := range jwks.Keys {
fmt.Println(key.KeyID)
}
return writeFunc(false)
}
func keysetFindAction(ctx *cli.Context) error {
if err := errs.NumberOfArguments(ctx, 1); err != nil {
return err
}
kid := ctx.String("kid")
jwksFile := ctx.Args().Get(0)
jwks, writeFunc, err := rwLockKeySet(jwksFile)
if err != nil {
return err
}
for _, key := range jwks.Keys {
if key.KeyID == kid {
b, err := json.MarshalIndent(key, "", " ")
if err != nil {
return errors.Wrap(err, "error marshaling JWK")
}
fmt.Println(string(b))
}
}
return writeFunc(false)
}
func rwLockKeySet(filename string) (jwks *jose.JSONWebKeySet, writeFunc func(bool) error, err error) {
var f *os.File
f, err = os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
err = errs.FileError(err, filename)
return
}
fd := int(f.Fd())
// non-blocking exclusive lock
err = syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB)
switch err {
case nil: // continue
case syscall.EWOULDBLOCK:
f.Close()
err = errors.Errorf("error reading %s: file is locked", filename)
return
default:
f.Close()
err = errors.Wrapf(err, "error locking %s", filename)
return
}
// close and unlock file on errors
defer func() {
if err != nil {
syscall.Flock(fd, syscall.LOCK_UN)
f.Close()
}
}()
// Read key set
var b []byte
b, err = ioutil.ReadAll(f)
if err != nil {
err = errors.Wrapf(err, "error reading %s", filename)
return
}
// Unmarshal the plain JWKSet
jwks = new(jose.JSONWebKeySet)
if len(b) > 0 {
if err = json.Unmarshal(b, jwks); err != nil {
err = errors.Wrapf(err, "error reading %s", filename)
return
}
}
writeFunc = func(write bool) (err error) {
if write {
if b, err1 := json.MarshalIndent(jwks, "", " "); err1 != nil {
err = errors.Wrapf(err1, "error marshaling %s", filename)
} else {
if err1 := f.Truncate(0); err1 != nil {
err = errors.Wrapf(err1, "error writing %s", filename)
} else {
n, err1 := f.WriteAt(b, 0)
switch {
case err1 != nil:
err = errors.Wrapf(err1, "error writing %s", filename)
case n < len(b):
err = errors.Wrapf(io.ErrShortWrite, "error writing %s", filename)
}
}
}
}
if err1 := syscall.Flock(fd, syscall.LOCK_UN); err1 != nil {
err = errors.Wrapf(err1, "error unlocking %s", filename)
}
if err1 := f.Close(); err1 != nil {
err = errors.Wrapf(err1, "error closing %s", filename)
}
return err
}
return
}