Debian Codegraph @

command/crypto/jwk/keyset.go

raw symbols SCIP
1 package jwk
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "io/ioutil"
8 "os"
9 "syscall"
10
11 "github.com/pkg/errors"
12 "github.com/smallstep/cli/errs"
13 "github.com/smallstep/cli/jose"
14 "github.com/smallstep/cli/utils/sysutils"
15 "github.com/urfave/cli"
16 )
17
18 func keysetCommand() cli.Command {
19 return cli.Command{
20 Name: "keyset",
21 Usage: "add, remove, and find JWKs in JWK Sets",
22 UsageText: "**step crypto jwk keyset** <subcommand> [arguments] [global-flags] [subcommand-flags]",
23 Description: `**step crypto jwk set** command group provides facilities for managing and
24 inspecting JWK Sets. A is a JSON object that represents a set of JWKs. They
25 are defined in RFC7517.
26
27 A JWK Set is simply a JSON object with a "keys" member whose value is an array
28 of JWKs. Additional members are allowed in the object. They will be preserved
29 by this tool, but otherwise ignored. Duplicate member names are not allowed.
30
31 For examples, see **step help crypto jwk**.`,
32 Subcommands: cli.Commands{
33 keysetAddCommand(),
34 keysetRemoveCommand(),
35 keysetListCommand(),
36 keysetFindCommand(),
37 },
38 }
39 }
40
41 func keysetAddCommand() cli.Command {
42 return cli.Command{
43 Name: "add",
44 Action: cli.ActionFunc(keysetAddAction),
45 Usage: "a JWK to a JWK Set",
46 UsageText: "**step crypto jwk keyset add** <jwks-file>",
47 Description: `**step crypto jwk keyset add** reads a JWK from STDIN and adds it to the JWK
48 Set in <jwks-file>. Modifications to <jwks-file> are in-place. The file is
49 'flock'd while it's being read and modified.
50
51 ## POSITIONAL ARGUMENTS
52
53 <jwks-file>
54 : File containing a JWK Set`,
55 }
56 }
57
58 func keysetRemoveCommand() cli.Command {
59 return cli.Command{
60 Name: "remove",
61 Action: cli.ActionFunc(keysetRemoveAction),
62 Usage: "a JWK from a JWK Set",
63 UsageText: "**step crypto jwk keyset remove** <jwks-file> [**--kid**=<kid>]",
64 Description: `**step crypto jwk keyset remove** removes the JWK with a key ID matching <kid>
65 from the JWK Set stored in <jwks-file>. Modifications to <jwks-file> are
66 in-place. The file is 'flock'd while it's being read and modified.
67
68 ## POSITIONAL ARGUMENTS
69
70 <jwks-file>
71 : File containing a JWK Set`,
72 Flags: []cli.Flag{
73 cli.StringFlag{
74 Name: "kid",
75 Usage: `The key ID of the JWK to remove from the JWK Set. <kid> is a case-sensitive
76 string.`,
77 },
78 },
79 }
80 }
81
82 func keysetListCommand() cli.Command {
83 return cli.Command{
84 Name: "list",
85 Action: cli.ActionFunc(keysetListAction),
86 Usage: "key IDs of JWKs in a JWK Set",
87 UsageText: "**step crypto jwk keyset list** <jwks-file>",
88 Description: `**step crypto jwk keyset list** lists the IDs ("kid" parameters) of JWKs in a
89 JWK Set.
90
91 ## POSITIONAL ARGUMENTS
92
93 <jwks-file>
94 : File containing a JWK Set`,
95 }
96 }
97
98 func keysetFindCommand() cli.Command {
99 return cli.Command{
100 Name: "find",
101 Action: cli.ActionFunc(keysetFindAction),
102 Usage: "a JWK in a JWK Set",
103 UsageText: "**step crypto jwk keyset find** <jwks-file> [**--kid**=<kid>]",
104 Description: `**step crypto jwk keyset find** command locates the JWK with a key ID matching
105 <kid> from the JWK Set stored in <jwks-file>. The matching JWK is printed to
106 STDOUT.
107
108 ## POSITIONAL ARGUMENTS
109
110 <jwks-file>
111 : File containing a JWK Set`,
112 Flags: []cli.Flag{
113 cli.StringFlag{
114 Name: "kid",
115 Usage: `The key ID of the JWK to locate from the JWK Set. <kid> is a case-sensitive
116 string.`,
117 },
118 },
119 }
120 }
121
122 func keysetAddAction(ctx *cli.Context) error {
123 if err := errs.NumberOfArguments(ctx, 1); err != nil {
124 return err
125 }
126
127 b, err := ioutil.ReadAll(os.Stdin)
128 if err != nil {
129 return errors.Wrap(err, "error reading STDIN")
130 }
131
132 // Attempt to parse an encrypted file
133 if b, err = jose.Decrypt("Please enter the password to decrypt JWK", b); err != nil {
134 return err
135 }
136
137 // Unmarshal the plain (or decrypted JWK)
138 var jwk jose.JSONWebKey
139 if err = json.Unmarshal(b, &jwk); err != nil {
140 return errors.New("error reading JWK: unsupported format")
141 }
142
143 jwksFile := ctx.Args().Get(0)
144 jwks, writeFunc, err := rwLockKeySet(jwksFile)
145 if err != nil {
146 return err
147 }
148
149 // According to RFC7517 there are cases where multiple keys can share the
150 // same "kid". One example is if they have different "kty" values but are
151 // considered to be equivalent alternatives by the application using them.
152 jwks.Keys = append(jwks.Keys, jwk)
153 return writeFunc(true)
154 }
155
156 func keysetRemoveAction(ctx *cli.Context) error {
157 if err := errs.NumberOfArguments(ctx, 1); err != nil {
158 return err
159 }
160
161 kid := ctx.String("kid")
162
163 jwksFile := ctx.Args().Get(0)
164 jwks, writeFunc, err := rwLockKeySet(jwksFile)
165 if err != nil {
166 return err
167 }
168
169 // Filtering without allocating
170 keys := jwks.Keys[:0]
171 for _, key := range jwks.Keys {
172 if key.KeyID != kid {
173 keys = append(keys, key)
174 }
175 }
176 jwks.Keys = keys
177 return writeFunc(true)
178 }
179
180 func keysetListAction(ctx *cli.Context) error {
181 if err := errs.NumberOfArguments(ctx, 1); err != nil {
182 return err
183 }
184
185 jwksFile := ctx.Args().Get(0)
186 jwks, writeFunc, err := rwLockKeySet(jwksFile)
187 if err != nil {
188 return err
189 }
190
191 for _, key := range jwks.Keys {
192 fmt.Println(key.KeyID)
193 }
194
195 return writeFunc(false)
196 }
197
198 func keysetFindAction(ctx *cli.Context) error {
199 if err := errs.NumberOfArguments(ctx, 1); err != nil {
200 return err
201 }
202
203 kid := ctx.String("kid")
204
205 jwksFile := ctx.Args().Get(0)
206 jwks, writeFunc, err := rwLockKeySet(jwksFile)
207 if err != nil {
208 return err
209 }
210
211 for _, key := range jwks.Keys {
212 if key.KeyID == kid {
213 b, err := json.MarshalIndent(key, "", " ")
214 if err != nil {
215 return errors.Wrap(err, "error marshaling JWK")
216 }
217 fmt.Println(string(b))
218 }
219 }
220
221 return writeFunc(false)
222 }
223
224 func rwLockKeySet(filename string) (jwks *jose.JSONWebKeySet, writeFunc func(bool) error, err error) {
225 var f *os.File
226
227 f, err = os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0600)
228 if err != nil {
229 err = errs.FileError(err, filename)
230 return
231 }
232
233 fd := int(f.Fd())
234
235 // non-blocking exclusive lock
236 err = sysutils.FileLock(fd)
237 switch err {
238 case nil: // continue
239 case syscall.EWOULDBLOCK:
240 f.Close()
241 err = errors.Errorf("error reading %s: file is locked", filename)
242 return
243 default:
244 f.Close()
245 err = errors.Wrapf(err, "error locking %s", filename)
246 return
247 }
248
249 // close and unlock file on errors
250 defer func() {
251 if err != nil {
252 sysutils.FileUnlock(fd)
253 f.Close()
254 }
255 }()
256
257 // Read key set
258 var b []byte
259 b, err = ioutil.ReadAll(f)
260 if err != nil {
261 err = errors.Wrapf(err, "error reading %s", filename)
262 return
263 }
264
265 // Unmarshal the plain JWKSet
266 jwks = new(jose.JSONWebKeySet)
267 if len(b) > 0 {
268 if err = json.Unmarshal(b, jwks); err != nil {
269 err = errors.Wrapf(err, "error reading %s", filename)
270 return
271 }
272 }
273
274 writeFunc = func(write bool) (err error) {
275 if write {
276 if b, err1 := json.MarshalIndent(jwks, "", " "); err1 != nil {
277 err = errors.Wrapf(err1, "error marshaling %s", filename)
278 } else {
279 if err1 := f.Truncate(0); err1 != nil {
280 err = errors.Wrapf(err1, "error writing %s", filename)
281 } else {
282 n, err1 := f.WriteAt(b, 0)
283 switch {
284 case err1 != nil:
285 err = errors.Wrapf(err1, "error writing %s", filename)
286 case n < len(b):
287 err = errors.Wrapf(io.ErrShortWrite, "error writing %s", filename)
288 }
289 }
290 }
291 }
292
293 if err1 := sysutils.FileUnlock(fd); err1 != nil {
294 err = errors.Wrapf(err1, "error unlocking %s", filename)
295 }
296
297 if err1 := f.Close(); err1 != nil {
298 err = errors.Wrapf(err1, "error closing %s", filename)
299 }
300
301 return err
302 }
303
304 return
305 }