Debian Codegraph @

config/keys.go

raw
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package config
15
16 import (
17 "context"
18 "crypto/tls"
19 "errors"
20 "fmt"
21 "io/fs"
22
23 "github.com/notaryproject/notation-go/internal/slices"
24 "github.com/notaryproject/notation-go/log"
25 "github.com/notaryproject/notation-go/plugin"
26
27 "github.com/notaryproject/notation-go/dir"
28 set "github.com/notaryproject/notation-go/internal/container"
29 )
30
31 // X509KeyPair contains the paths of a public/private key pair files.
32 type X509KeyPair struct {
33 KeyPath string `json:"keyPath,omitempty"`
34 CertificatePath string `json:"certPath,omitempty"`
35 }
36
37 // ExternalKey contains the necessary information to delegate
38 // the signing operation to the named plugin.
39 type ExternalKey struct {
40 ID string `json:"id,omitempty"`
41 PluginName string `json:"pluginName,omitempty"`
42 PluginConfig map[string]string `json:"pluginConfig,omitempty"`
43 }
44
45 // KeySuite is a named key suite.
46 type KeySuite struct {
47 Name string `json:"name"`
48
49 *X509KeyPair
50 *ExternalKey
51 }
52
53 // SigningKeys reflects the signingkeys.json file.
54 type SigningKeys struct {
55 Default *string `json:"default,omitempty"`
56 Keys []KeySuite `json:"keys"`
57 }
58
59 // NewSigningKeys creates a new signingkeys config file
60 func NewSigningKeys() *SigningKeys {
61 return &SigningKeys{Keys: []KeySuite{}}
62 }
63
64 // Add adds new signing key
65 func (s *SigningKeys) Add(name, keyPath, certPath string, markDefault bool) error {
66 if name == "" {
67 return ErrKeyNameEmpty
68 }
69 _, err := tls.LoadX509KeyPair(certPath, keyPath)
70 if err != nil {
71 return err
72 }
73 ks := KeySuite{
74 Name: name,
75 X509KeyPair: &X509KeyPair{
76 KeyPath: keyPath,
77 CertificatePath: certPath,
78 },
79 }
80 return s.add(ks, markDefault)
81 }
82
83 // AddPlugin adds new plugin based signing key
84 func (s *SigningKeys) AddPlugin(ctx context.Context, keyName, id, pluginName string, pluginConfig map[string]string, markDefault bool) error {
85 logger := log.GetLogger(ctx)
86 logger.Debugf("Adding key with name %v and plugin name %v", keyName, pluginName)
87 if keyName == "" {
88 return ErrKeyNameEmpty
89 }
90 if id == "" {
91 return errors.New("missing key id")
92 }
93 if pluginName == "" {
94 return errors.New("plugin name cannot be empty")
95 }
96 mgr := plugin.NewCLIManager(dir.PluginFS())
97 _, err := mgr.Get(ctx, pluginName)
98 if err != nil {
99 return err
100 }
101 ks := KeySuite{
102 Name: keyName,
103 ExternalKey: &ExternalKey{
104 ID: id,
105 PluginName: pluginName,
106 PluginConfig: pluginConfig,
107 },
108 }
109 if err = s.add(ks, markDefault); err != nil {
110 logger.Error("Failed to add key with error: %v", err)
111 return err
112 }
113 logger.Debugf("Added key with name %s - {%+v}", keyName, ks)
114 return nil
115 }
116
117 // Get returns signing key for the given name
118 func (s *SigningKeys) Get(keyName string) (KeySuite, error) {
119 if keyName == "" {
120 return KeySuite{}, ErrKeyNameEmpty
121 }
122 idx := slices.IndexIsser(s.Keys, keyName)
123 if idx < 0 {
124 return KeySuite{}, KeyNotFoundError{KeyName: keyName}
125 }
126 return s.Keys[idx], nil
127 }
128
129 // GetDefault returns default signing key
130 func (s *SigningKeys) GetDefault() (KeySuite, error) {
131 if s.Default == nil {
132 return KeySuite{}, errors.New("default signing key not set." +
133 " Please set default signing key or specify a key name")
134 }
135 return s.Get(*s.Default)
136 }
137
138 // Remove deletes given signing keys and returns a slice of deleted key names
139 func (s *SigningKeys) Remove(keyName ...string) ([]string, error) {
140 var deletedNames []string
141 for _, name := range keyName {
142 if name == "" {
143 return deletedNames, ErrKeyNameEmpty
144 }
145 idx := slices.IndexIsser(s.Keys, name)
146 if idx < 0 {
147 return deletedNames, KeyNotFoundError{KeyName: name}
148 }
149 s.Keys = slices.Delete(s.Keys, idx)
150 deletedNames = append(deletedNames, name)
151 if s.Default != nil && *s.Default == name {
152 s.Default = nil
153 }
154 }
155 return deletedNames, nil
156 }
157
158 // UpdateDefault updates default signing key
159 func (s *SigningKeys) UpdateDefault(keyName string) error {
160 if keyName == "" {
161 return ErrKeyNameEmpty
162 }
163 if !slices.ContainsIsser(s.Keys, keyName) {
164 return KeyNotFoundError{KeyName: keyName}
165 }
166 s.Default = &keyName
167 return nil
168 }
169
170 // Save SigningKeys to signingkeys.json file
171 func (s *SigningKeys) Save() error {
172 path, err := dir.ConfigFS().SysPath(dir.PathSigningKeys)
173 if err != nil {
174 return err
175 }
176 if err := validateKeys(s); err != nil {
177 return err
178 }
179 return save(path, s)
180 }
181
182 // LoadSigningKeys reads the signingkeys.json file
183 // or return a default config if not found.
184 func LoadSigningKeys() (*SigningKeys, error) {
185 var config SigningKeys
186 err := load(dir.PathSigningKeys, &config)
187 if err != nil {
188 if errors.Is(err, fs.ErrNotExist) {
189 return NewSigningKeys(), nil
190 }
191 return nil, err
192 }
193 if err := validateKeys(&config); err != nil {
194 return nil, err
195 }
196 return &config, nil
197 }
198
199 // LoadExecSaveSigningKeys loads signing key, executes given function and
200 // then saves the signing key
201 func LoadExecSaveSigningKeys(fn func(keys *SigningKeys) error) error {
202 // core process
203 signingKeys, err := LoadSigningKeys()
204 if err != nil {
205 return err
206 }
207 if err := fn(signingKeys); err != nil {
208 return err
209 }
210 return signingKeys.Save()
211 }
212
213 // Is checks whether the given name is equal with the Name variable
214 func (k KeySuite) Is(name string) bool {
215 return k.Name == name
216 }
217
218 func (s *SigningKeys) add(key KeySuite, markDefault bool) error {
219 if slices.ContainsIsser(s.Keys, key.Name) {
220 return fmt.Errorf("signing key with name %q already exists", key.Name)
221 }
222 s.Keys = append(s.Keys, key)
223 if markDefault {
224 s.Default = &key.Name
225 }
226 return nil
227 }
228
229 func validateKeys(config *SigningKeys) error {
230 keys := config.Keys
231 uniqueKeyNames := set.NewWithSize[string](len(keys))
232 for _, key := range keys {
233 if len(key.Name) == 0 {
234 return fmt.Errorf("malformed %s: key name cannot be empty", dir.PathSigningKeys)
235 }
236 if uniqueKeyNames.Contains(key.Name) {
237 return fmt.Errorf("malformed %s: multiple keys with name '%s' found", dir.PathSigningKeys, key.Name)
238 }
239 uniqueKeyNames.Add(key.Name)
240 }
241 if config.Default != nil {
242 defaultKey := *config.Default
243 if len(defaultKey) == 0 {
244 return fmt.Errorf("malformed %s: default key name cannot be empty", dir.PathSigningKeys)
245 }
246 if !uniqueKeyNames.Contains(defaultKey) {
247 return fmt.Errorf("malformed %s: default key '%s' not found", dir.PathSigningKeys, defaultKey)
248 }
249 }
250 return nil
251 }