File: key.go

package info (click to toggle)
golang-github-notaryproject-notation 1.2.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,160 kB
  • sloc: sh: 202; makefile: 67
file content (278 lines) | stat: -rw-r--r-- 7,040 bytes parent folder | download | duplicates (2)
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
// Copyright The Notary Project Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/notaryproject/notation-go/config"

	"github.com/notaryproject/notation-go/log"
	"github.com/notaryproject/notation/internal/cmd"
	"github.com/notaryproject/notation/internal/ioutil"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
)

var (
	keyDefaultFlag = &pflag.Flag{
		Name:  "default",
		Usage: "mark as default",
	}
	setKeyDefaultFlag = func(fs *pflag.FlagSet, p *bool) {
		fs.BoolVarP(p, keyDefaultFlag.Name, keyDefaultFlag.Shorthand, false, keyDefaultFlag.Usage)
	}
)

type keyAddOpts struct {
	cmd.LoggingFlagOpts
	name         string
	plugin       string
	id           string
	pluginConfig []string
	isDefault    bool
}

type keyUpdateOpts struct {
	cmd.LoggingFlagOpts
	name      string
	isDefault bool
}

type keyDeleteOpts struct {
	cmd.LoggingFlagOpts
	names []string
}

func keyCommand() *cobra.Command {
	command := &cobra.Command{
		Use:   "key",
		Short: "Manage keys used for signing",
		Long: `Manage keys used for signing

Example - Add a key to signing key list:
  notation key add --plugin <plugin_name> --id <key_id> <key_name>

Example - List keys used for signing:
  notation key ls

Example - Update the default signing key:
  notation key set --default <key_name>

Example - Delete the key from signing key list:
  notation key delete <key_name>...
`,
	}
	command.AddCommand(keyAddCommand(nil), keyUpdateCommand(nil), keyListCommand(), keyDeleteCommand(nil))

	return command
}

func keyAddCommand(opts *keyAddOpts) *cobra.Command {
	if opts == nil {
		opts = &keyAddOpts{}
	}
	command := &cobra.Command{
		Use:   "add --plugin <plugin_name> [flags] <key_name>",
		Short: "Add key to Notation signing key list",
		Args: func(cmd *cobra.Command, args []string) error {
			if len(args) != 1 {
				return errors.New("either missing key name or unnecessary parameters passed")
			}
			opts.name = args[0]
			return nil
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			return addKey(cmd.Context(), opts)
		},
	}
	opts.LoggingFlagOpts.ApplyFlags(command.Flags())
	command.Flags().StringVar(&opts.plugin, "plugin", "", "signing plugin name")
	command.MarkFlagRequired("plugin")

	command.Flags().StringVar(&opts.id, "id", "", "key id (required if --plugin is set)")

	cmd.SetPflagPluginConfig(command.Flags(), &opts.pluginConfig)
	setKeyDefaultFlag(command.Flags(), &opts.isDefault)

	return command
}

func keyUpdateCommand(opts *keyUpdateOpts) *cobra.Command {
	if opts == nil {
		opts = &keyUpdateOpts{}
	}
	command := &cobra.Command{
		Use:     "update [flags] <key_name>",
		Aliases: []string{"set"},
		Short:   "Update key in Notation signing key list",
		Args: func(cmd *cobra.Command, args []string) error {
			if len(args) == 0 {
				return errors.New("missing key name")
			}
			opts.name = args[0]
			return nil
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			return updateKey(cmd.Context(), opts)
		},
	}

	opts.LoggingFlagOpts.ApplyFlags(command.Flags())
	setKeyDefaultFlag(command.Flags(), &opts.isDefault)

	return command
}

func keyListCommand() *cobra.Command {
	return &cobra.Command{
		Use:     "list [flags]",
		Aliases: []string{"ls"},
		Short:   "List keys used for signing",
		RunE: func(cmd *cobra.Command, args []string) error {
			return listKeys()
		},
	}
}

func keyDeleteCommand(opts *keyDeleteOpts) *cobra.Command {
	if opts == nil {
		opts = &keyDeleteOpts{}
	}

	command := &cobra.Command{
		Use:   "delete [flags] <key_name>...",
		Short: "Remove key from Notation signing key list",
		Args: func(cmd *cobra.Command, args []string) error {
			if len(args) == 0 {
				return errors.New("missing key names")
			}
			opts.names = args
			return nil
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			return deleteKeys(cmd.Context(), opts)
		},
	}
	opts.LoggingFlagOpts.ApplyFlags(command.Flags())

	return command
}

func addKey(ctx context.Context, opts *keyAddOpts) error {
	// set log level
	ctx = opts.LoggingFlagOpts.InitializeLogger(ctx)

	pluginConfig, err := cmd.ParseFlagMap(opts.pluginConfig, cmd.PflagPluginConfig.Name)
	if err != nil {
		return err
	}

	// core process
	exec := func(s *config.SigningKeys) error {
		return s.AddPlugin(ctx, opts.name, opts.id, opts.plugin, pluginConfig, opts.isDefault)
	}
	if err := config.LoadExecSaveSigningKeys(exec); err != nil {
		return err
	}

	if opts.isDefault {
		fmt.Printf("%s: marked as default\n", opts.name)
	} else {
		fmt.Println(opts.name)
	}

	return nil
}

func updateKey(ctx context.Context, opts *keyUpdateOpts) error {
	// set log level
	ctx = opts.LoggingFlagOpts.InitializeLogger(ctx)
	logger := log.GetLogger(ctx)

	if !opts.isDefault {
		logger.Warn("--default flag is not set, command did not take effect")
		return nil
	}

	// core process
	exec := func(s *config.SigningKeys) error {
		return s.UpdateDefault(opts.name)
	}
	if err := config.LoadExecSaveSigningKeys(exec); err != nil {
		return err
	}

	// write out
	fmt.Printf("%s: marked as default\n", opts.name)
	return nil
}

func listKeys() error {
	// core process
	signingKeys, err := config.LoadSigningKeys()
	if err != nil {
		return err
	}

	// write out
	return ioutil.PrintKeyMap(os.Stdout, signingKeys.Default, signingKeys.Keys)
}

func deleteKeys(ctx context.Context, opts *keyDeleteOpts) error {
	// set log level
	ctx = opts.LoggingFlagOpts.InitializeLogger(ctx)
	logger := log.GetLogger(ctx)

	// core process
	var deletedNames []string
	var prevDefault string
	exec := func(s *config.SigningKeys) error {
		if s.Default != nil {
			prevDefault = *s.Default
		}
		var err error
		deletedNames, err = s.Remove(opts.names...)
		if err != nil {
			logger.Errorf("Keys deletion failed to complete with error: %v", err)
		}
		return err
	}
	if err := config.LoadExecSaveSigningKeys(exec); err != nil {
		return err
	}

	// write out
	if len(deletedNames) == 1 {
		name := deletedNames[0]
		if name == prevDefault {
			fmt.Printf("Removed default key %s from Notation signing key list. The source key still exists.\n", name)
		} else {
			fmt.Printf("Removed %s from Notation signing key list. The source key still exists.\n", name)
		}
	} else if len(deletedNames) > 1 {
		fmt.Println("Removed the following keys from Notation signing key list. The source keys still exist.")
		for _, name := range deletedNames {
			if name == prevDefault {
				fmt.Println(name, "(default)")
			} else {
				fmt.Println(name)
			}
		}
	}
	return nil
}