File: artifacts.go

package info (click to toggle)
golang-github-mendersoftware-mender-artifact 3.9.0%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, experimental
  • size: 4,136 kB
  • sloc: makefile: 128; sh: 128
file content (443 lines) | stat: -rw-r--r-- 11,806 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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Copyright 2022 Northern.tech AS
//
//    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 cli

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/mendersoftware/mender-artifact/areader"
	"github.com/mendersoftware/mender-artifact/artifact"
	"github.com/mendersoftware/mender-artifact/artifact/gcp"
	"github.com/mendersoftware/mender-artifact/awriter"
	"github.com/mendersoftware/mender-artifact/handlers"

	"github.com/pkg/errors"
	"github.com/urfave/cli"
)

type unpackedArtifact struct {
	origPath  string
	unpackDir string
	ar        *areader.Reader
	scripts   []string
	files     []string

	// Args needed to reconstruct the artifact
	writeArgs *awriter.WriteArtifactArgs
}

type writeUpdateStorer struct {
	// Dir to store files in
	dir string
	// Files that are stored. Will be filled in while storing
	names []string
}

func (w *writeUpdateStorer) Initialize(artifactHeaders,
	artifactAugmentedHeaders artifact.HeaderInfoer,
	payloadHeaders handlers.ArtifactUpdateHeaders) error {

	if artifactAugmentedHeaders != nil {
		return errors.New("Modifying augmented artifacts is not supported")
	}

	return nil
}

func (w *writeUpdateStorer) PrepareStoreUpdate() error {
	return nil
}

func (w *writeUpdateStorer) StoreUpdate(r io.Reader, info os.FileInfo) error {
	fullpath := filepath.Join(w.dir, info.Name())
	w.names = append(w.names, fullpath)
	fd, err := os.OpenFile(fullpath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
	if err != nil {
		return err
	}
	_, err = io.Copy(fd, r)
	return err
}

func (w *writeUpdateStorer) FinishStoreUpdate() error {
	return nil
}

func (w *writeUpdateStorer) NewUpdateStorer(
	updateType *string,
	payloadNum int,
) (handlers.UpdateStorer, error) {
	if payloadNum != 0 {
		return nil, errors.New("More than one payload or update file is not supported")
	}
	return w, nil
}

func scripts(scripts []string) (*artifact.Scripts, error) {
	scr := artifact.Scripts{}
	for _, scriptArg := range scripts {
		statInfo, err := os.Stat(scriptArg)
		if err != nil {
			return nil, errors.Wrapf(err, "can not stat script file: %s", scriptArg)
		}

		// Read either a directory, or add the script file directly.
		if statInfo.IsDir() {
			fileList, err := ioutil.ReadDir(scriptArg)
			if err != nil {
				return nil, errors.Wrapf(err, "can not list directory contents of: %s", scriptArg)
			}
			for _, nameInfo := range fileList {
				if err := scr.Add(filepath.Join(scriptArg, nameInfo.Name())); err != nil {
					return nil, err
				}
			}
		} else {
			if err := scr.Add(scriptArg); err != nil {
				return nil, err
			}
		}
	}
	return &scr, nil
}

type SigningKey interface {
	artifact.Signer
	artifact.Verifier
}

func getKey(c *cli.Context) (SigningKey, error) {
	var chosenOptions []string
	possibleOptions := []string{"key", "gcp-kms-key", "key-pkcs11"}
	for _, optName := range possibleOptions {
		if c.String(optName) == "" {
			continue
		}
		chosenOptions = append(chosenOptions, optName)
	}
	if len(chosenOptions) == 0 {
		return nil, nil
	} else if len(chosenOptions) > 1 {
		return nil, fmt.Errorf("too many signing keys given: %v", chosenOptions)
	}
	switch chosenOption := chosenOptions[0]; chosenOption {
	case "key":
		key, err := ioutil.ReadFile(c.String("key"))
		if err != nil {
			return nil, errors.Wrap(err, "Error reading key file")
		}

		// The "key" flag can either be public or private depending on the
		// command name. Explicitly map each command's name to which one it
		// should be, so we return the correct key type.
		publicKeyCommands := map[string]bool{
			"validate": true,
			"read":     true,
		}
		privateKeyCommands := map[string]bool{
			"rootfs-image":       true,
			"module-image":       true,
			"bootstrap-artifact": true,
			"sign":               true,
			"modify":             true,
			"copy":               true,
		}
		if publicKeyCommands[c.Command.Name] {
			return artifact.NewPKIVerifier(key)
		}
		if privateKeyCommands[c.Command.Name] {
			return artifact.NewPKISigner(key)
		}
		return nil, fmt.Errorf("unsupported command %q with %q flag, "+
			"please add command to allowlist", c.Command.Name, "key")
	case "gcp-kms-key":
		return gcp.NewKMSSigner(context.TODO(), c.String("gcp-kms-key"))
	case "key-pkcs11":
		return artifact.NewPKCS11Signer(c.String("key-pkcs11"))
	default:
		return nil, fmt.Errorf("unsupported signing key type %q", chosenOption)
	}
}

func unpackArtifact(name string) (ua *unpackedArtifact, err error) {
	ua = &unpackedArtifact{
		origPath: name,
	}

	f, err := os.Open(name)
	if err != nil {
		return nil, errors.Wrapf(err, "Can not open: %s", name)
	}
	defer f.Close()

	aReader := areader.NewReader(f)
	ua.ar = aReader

	tmpdir, err := ioutil.TempDir("", "mender-artifact")
	if err != nil {
		return nil, err
	}
	ua.unpackDir = tmpdir
	defer func() {
		if err != nil {
			os.RemoveAll(tmpdir)
		}
	}()

	sDir := filepath.Join(tmpdir, "scripts")
	err = os.Mkdir(sDir, 0755)
	if err != nil {
		return nil, err
	}
	storeScripts := func(r io.Reader, info os.FileInfo) error {
		sLocation := filepath.Join(sDir, info.Name())
		ua.scripts = append(ua.scripts, sLocation)
		f, fileErr := os.OpenFile(sLocation, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0755)
		if fileErr != nil {
			return errors.Wrapf(fileErr,
				"can not create script file: %v", sLocation)
		}
		defer f.Close()

		_, err = io.Copy(f, r)
		if err != nil {
			return errors.Wrapf(err,
				"can not write script file: %v", sLocation)
		}
		return nil
	}
	aReader.ScriptsReadCallback = storeScripts

	err = aReader.ReadArtifactHeaders()
	if err != nil {
		return nil, err
	}

	fDir := filepath.Join(tmpdir, "files")
	err = os.Mkdir(fDir, 0755)
	if err != nil {
		return nil, err
	}

	updateStore := &writeUpdateStorer{
		dir: fDir,
	}
	inst := aReader.GetHandlers()
	if len(inst) == 1 {
		inst[0].SetUpdateStorerProducer(updateStore)
	} else if len(inst) > 1 {
		return nil, errors.New("More than one payload not supported")
	}

	if err := aReader.ReadArtifactData(); err != nil {
		return nil, err
	}

	ua.files = updateStore.names

	updType := inst[0].GetUpdateType()
	if updType == nil {
		return nil, errors.New("nil update type is not allowed")
	}
	if len(inst) > 0 &&
		*inst[0].GetUpdateType() == "rootfs-image" &&
		len(ua.files) != 1 {

		return nil, errors.New("rootfs-image artifacts with more than one file not supported")
	}

	ua.writeArgs, err = reconstructArtifactWriteData(ua)
	return ua, err
}

func reconstructPayloadWriteData(
	info *artifact.Info,
	inst map[int]handlers.Installer,
) (upd *awriter.Updates,
	typeInfoV3 *artifact.TypeInfoV3,
	augTypeInfoV3 *artifact.TypeInfoV3,
	metaData map[string]interface{},
	augMetaData map[string]interface{},
	err error) {

	if len(inst) > 1 {
		err = errors.New("More than one payload not supported")
		return
	} else if len(inst) == 1 {
		var updateType *string
		upd = &awriter.Updates{}

		switch info.Version {
		case 1:
			err = errors.New("Mender-Artifact version 1 no longer supported")
			return
		case 2:
			updateType = inst[0].GetUpdateType()
			if updateType == nil {
				err = errors.New("nil update type is not allowed")
				return
			}
			upd.Updates = []handlers.Composer{handlers.NewRootfsV2(*updateType)}
		case 3:
			// Even rootfs images will be written using ModuleImage, which
			// is a superset
			var updType *string
			updType = inst[0].GetUpdateOriginalType()
			if *updType != "" {
				// If augmented artifact.
				upd.Augments = []handlers.Composer{handlers.NewModuleImage(*updType)}
				augTypeInfoV3 = &artifact.TypeInfoV3{
					Type:             updType,
					ArtifactDepends:  inst[0].GetUpdateOriginalDepends(),
					ArtifactProvides: inst[0].GetUpdateOriginalProvides(),
				}
				augMetaData = inst[0].GetUpdateOriginalMetaData()
			}

			updateType = inst[0].GetUpdateType()
			if updateType == nil {
				err = errors.New("nil update type is not allowed")
				return
			}
			upd.Updates = []handlers.Composer{handlers.NewModuleImage(*updateType)}

		default:
			err = errors.Errorf("unsupported artifact version: %d", info.Version)
			return
		}

		var uDepends artifact.TypeInfoDepends
		var uProvides artifact.TypeInfoProvides

		if uDepends, err = inst[0].GetUpdateDepends(); err != nil {
			return
		}
		if uProvides, err = inst[0].GetUpdateProvides(); err != nil {
			return
		}
		typeInfoV3 = &artifact.TypeInfoV3{
			Type:                   updateType,
			ArtifactDepends:        uDepends,
			ArtifactProvides:       uProvides,
			ClearsArtifactProvides: inst[0].GetUpdateOriginalClearsProvides(),
		}

		if metaData, err = inst[0].GetUpdateMetaData(); err != nil {
			return
		}
	}

	return
}

func reconstructArtifactWriteData(ua *unpackedArtifact) (*awriter.WriteArtifactArgs, error) {
	info := ua.ar.GetInfo()
	inst := ua.ar.GetHandlers()

	upd, typeInfoV3, augTypeInfoV3, metaData, augMetaData, err := reconstructPayloadWriteData(
		&info,
		inst,
	)
	if err != nil {
		return nil, err
	}

	if len(inst) == 1 {
		dataFiles := make([]*handlers.DataFile, 0, len(ua.files))
		for _, file := range ua.files {
			dataFiles = append(dataFiles, &handlers.DataFile{Name: file})
		}
		err := upd.Updates[0].SetUpdateFiles(dataFiles)
		if err != nil {
			return nil, errors.Wrap(err, "Cannot assign payload files")
		}
	} else if len(inst) > 1 {
		return nil, errors.New("Multiple payloads not supported")
	}

	scr, err := scripts(ua.scripts)
	if err != nil {
		return nil, err
	}

	name := ua.ar.GetArtifactName()

	args := &awriter.WriteArtifactArgs{
		Format:            info.Format,
		Version:           info.Version,
		Devices:           ua.ar.GetCompatibleDevices(),
		Name:              name,
		Updates:           upd,
		Scripts:           scr,
		Provides:          ua.ar.GetArtifactProvides(),
		Depends:           ua.ar.GetArtifactDepends(),
		TypeInfoV3:        typeInfoV3,
		MetaData:          metaData,
		AugmentTypeInfoV3: augTypeInfoV3,
		AugmentMetaData:   augMetaData,
	}

	return args, nil
}

func repack(comp artifact.Compressor, ua *unpackedArtifact, to io.Writer, key SigningKey) error {
	aWriter := awriter.NewWriter(to, comp)
	if key != nil {
		aWriter = awriter.NewWriterSigned(to, comp, key)
	}

	// for rootfs-images: Update rootfs-image.checksum provide if there is one.
	_, hasChecksumProvide := ua.writeArgs.TypeInfoV3.ArtifactProvides["rootfs-image.checksum"]
	// for rootfs-images: Update legacy rootfs_image_checksum provide if there is one.
	_, hasLegacyChecksumProvide := ua.writeArgs.TypeInfoV3.ArtifactProvides["rootfs_image_checksum"]
	if *ua.writeArgs.TypeInfoV3.Type == "rootfs-image" && (hasChecksumProvide ||
		hasLegacyChecksumProvide) {
		if len(ua.files) != 1 {
			return errors.New("Only rootfs-image Artifacts with one file are supported")
		}
		err := writeRootfsImageChecksum(
			ua.files[0],
			ua.writeArgs.TypeInfoV3,
			hasLegacyChecksumProvide,
		)
		if err != nil {
			return err
		}
	}

	return aWriter.WriteArtifact(ua.writeArgs)
}

func repackArtifact(comp artifact.Compressor, key SigningKey, ua *unpackedArtifact) error {
	tmp, err := ioutil.TempFile(filepath.Dir(ua.origPath), "mender-artifact")
	if err != nil {
		return err
	}
	defer os.Remove(tmp.Name())
	defer tmp.Close()

	if err = repack(comp, ua, tmp, key); err != nil {
		return err
	}

	tmp.Close()

	return os.Rename(tmp.Name(), ua.origPath)
}