File: image_test.go

package info (click to toggle)
apptainer 1.4.4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,748 kB
  • sloc: sh: 3,321; ansic: 1,706; awk: 414; python: 103; makefile: 54
file content (462 lines) | stat: -rw-r--r-- 11,089 bytes parent folder | download
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// Copyright (c) Contributors to the Apptainer project, established as
//   Apptainer a Series of LF Projects LLC.
//   For website terms of use, trademark policy, privacy policy and other
//   project policies see https://lfprojects.org/policies
// Copyright (c) 2019-2022, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.

package image

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"os/user"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"testing"

	"github.com/apptainer/apptainer/internal/pkg/image/unpacker"
	"github.com/apptainer/apptainer/internal/pkg/test"
	"github.com/apptainer/apptainer/internal/pkg/util/fs"

	imageSpecs "github.com/opencontainers/image-spec/specs-go/v1"
)

// We need a busybox SIF for these tests. We used to download it each time, but we have one
// around for some e2e tests already.
const busyboxSIF = "../../e2e/testdata/busybox_" + runtime.GOARCH + ".sif"

type ownerGroupTest struct {
	name       string
	owners     []string
	privileged bool
	shouldPass bool
}

type groupTest struct {
	name       string
	groups     []string
	privileged bool
	shouldPass bool
}

// Copy the test image to a temporary location so we don't accidentally clobber the original
func copyImage(t *testing.T) string {
	f, err := os.CreateTemp("", "image-")
	if err != nil {
		t.Fatalf("cannot create temporary file: %s\n", err)
	}
	name := f.Name()
	f.Close()

	if err := fs.CopyFileAtomic(busyboxSIF, name, 0o755); err != nil {
		t.Fatalf("Could not copy test image: %v", err)
	}
	return name
}

func checkPartition(t *testing.T, reader io.Reader) error {
	extracted := "/bin/busybox"
	dir := t.TempDir()

	s := unpacker.NewSquashfs()
	if s.HasUnsquashfs() {
		if err := s.ExtractFiles([]string{extracted}, reader, dir); err != nil {
			return fmt.Errorf("extraction failed: %s", err)
		}
		if !fs.IsExec(filepath.Join(dir, extracted)) {
			return fmt.Errorf("%s extraction failed", extracted)
		}
	}
	return nil
}

func checkSection(_ *testing.T, reader io.Reader) error {
	dec := json.NewDecoder(reader)
	imgSpec := &imageSpecs.ImageConfig{}
	if err := dec.Decode(imgSpec); err != nil {
		return fmt.Errorf("failed to decode oci image config")
	}
	if len(imgSpec.Cmd) == 0 {
		return fmt.Errorf("no command found")
	}
	if imgSpec.Cmd[0] != "sh" {
		return fmt.Errorf("unexpected value: %s instead of sh", imgSpec.Cmd[0])
	}
	return nil
}

func TestReader(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	test.DropPrivilege(t)
	defer test.ResetPrivilege(t)

	filename := copyImage(t)
	defer os.Remove(filename)

	for _, e := range []struct {
		fn       func(*Image, string, int) (io.Reader, error)
		fnCheck  func(*testing.T, io.Reader) error
		errCheck error
		name     string
		index    int
	}{
		{
			fn:       NewPartitionReader,
			fnCheck:  checkPartition,
			errCheck: ErrNoPartition,
			name:     RootFs,
			index:    -1,
		},
		{
			fn:       NewPartitionReader,
			fnCheck:  checkPartition,
			errCheck: ErrNoPartition,
			index:    0,
		},
		{
			fn:       NewSectionReader,
			fnCheck:  checkSection,
			errCheck: ErrNoSection,
			name:     SIFDescOCIConfigJSON,
			index:    -1,
		},
	} {
		// test with nil image parameter
		if _, err := e.fn(nil, "", -1); err == nil {
			t.Errorf("unexpected success with nil image parameter")
		}
		// test with non opened file
		if _, err := e.fn(&Image{}, "", -1); err == nil {
			t.Errorf("unexpected success with non opened file")
		}

		img, err := Init(filename, false)
		if err != nil {
			t.Fatal(err)
		}

		if img.Type != SIF {
			t.Errorf("unexpected image format: %v", img.Type)
		}
		_, err = img.GetRootFsPartition()
		if err != nil {
			t.Errorf("no root filesystem found")
		}
		// test without match criteria
		if _, err := e.fn(img, "", -1); err == nil {
			t.Errorf("unexpected success without match criteria")
		}
		// test with large index
		if _, err := e.fn(img, "", 999999); err == nil {
			t.Errorf("unexpected success with large index")
		}
		// test with unknown name
		if _, err := e.fn(img, "fakefile.name", -1); err != e.errCheck {
			t.Errorf("unexpected error with unknown name")
		}
		// test with match criteria
		if r, err := e.fn(img, e.name, e.index); err == e.errCheck {
			t.Error(err)
		} else {
			if err := e.fnCheck(t, r); err != nil {
				t.Error(err)
			}
		}
		img.File.Close()
	}
}

func TestAuthorizedPath(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	test.DropPrivilege(t)
	defer test.ResetPrivilege(t)

	tests := []struct {
		name       string
		path       []string
		shouldPass bool
	}{
		{
			name:       "empty path",
			path:       []string{""},
			shouldPass: false,
		},
		{
			name:       "invalid path",
			path:       []string{"/a/random/invalid/path"},
			shouldPass: false,
		},
		{
			name:       "valid path",
			path:       []string{"/"},
			shouldPass: true,
		},
	}

	// XXX(mem): This is what makes this test slow
	img, path := createImage(t)
	defer os.Remove(path)

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			auth, err := img.AuthorizedPath(test.path)
			if test.shouldPass == false && (auth == true && err == nil) {
				t.Fatal("invalid path was reported as authorized")
			}
			if test.shouldPass == true && (auth == false || err != nil) {
				if err != nil {
					t.Fatalf("valid path was reported as not authorized: %s", err)
				} else {
					t.Fatal("valid path was reported as not authorized")
				}
			}
		})
	}
}

func createImage(t *testing.T) (*Image, string) {
	// Create a temporary image
	path := copyImage(t)

	// Now load the image which will be used next for a bunch of tests
	img, err := Init(path, true)
	if err != nil {
		t.Fatal("impossible to load image for testing")
	}

	return img, path
}

func runAuthorizedOwnerTest(t *testing.T, testDescr ownerGroupTest, img *Image) {
	if testDescr.privileged == true {
		test.EnsurePrivilege(t)
	} else {
		test.DropPrivilege(t)
		defer test.ResetPrivilege(t)
	}

	auth, err := img.AuthorizedOwner(testDescr.owners)
	if testDescr.shouldPass == true && (auth == false || err != nil) {
		if err == nil {
			t.Fatalf("valid owner list reported as not authorized (%s)\n", strings.Join(testDescr.owners, ","))
		} else {
			t.Fatalf("valid test failed: %s\n", err)
		}
	}
	if testDescr.shouldPass == true && (auth == false || err != nil) {
		if err != nil {
			t.Fatalf("valid owner list was reported as not authorized: %s", err)
		} else {
			t.Fatal("valid owner list was reported as not authorized")
		}
	}
}

func TestRootAuthorizedOwner(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	// Function focusing only on executing the privileged case
	test.EnsurePrivilege(t)

	tests := []ownerGroupTest{
		/* This test fails with CircleCI because of weird user management that
		   would lead to crazy code so we deactivate it for now
		{
			name:       "root",
			privileged: true,
			owners:     []string{"root"},
			shouldPass: true,
		},
		*/
		{
			name:       "invalid root",
			privileged: true,
			owners:     []string{"foobar"},
			shouldPass: false,
		},
	}

	// XXX(mem): This is what makes this test slow
	img, path := createImage(t)
	defer os.Remove(path)

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			runAuthorizedOwnerTest(t, tt, img)
		})
	}
}

//nolint:dupl
func TestAuthorizedOwner(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	// We will create a runtime test based on the current user that assumes
	// this not a privileged test
	test.DropPrivilege(t)
	defer test.ResetPrivilege(t)

	// Note that we do not test the "root" case; the privileged cases are
	// tested in a separate function.
	tests := []ownerGroupTest{
		{
			name:       "empty owner list",
			privileged: false,
			owners:     []string{""},
			shouldPass: false,
		},
		{
			name:       "invalid owner list",
			privileged: false,
			owners:     []string{"2"},
			shouldPass: false,
		},
	}

	// We test with the current username, note that because we are under
	// test.DropPrivilege, this needs to be done a very specific way.
	uid := os.Getuid()
	me, err := user.LookupId(strconv.Itoa(uid))
	if err != nil {
		t.Fatalf("cannot get current user name for testing purposes: %s", err)
	}
	localUser := ownerGroupTest{
		name:       "valid owner list",
		privileged: false,
		owners:     []string{me.Username},
		shouldPass: true,
	}
	tests = append(tests, localUser)

	// XXX(mem): This is what makes this test slow
	img, path := createImage(t)
	defer os.Remove(path)

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			runAuthorizedOwnerTest(t, test, img)
		})
	}
}

func runAuthorizedGroupTest(t *testing.T, tt groupTest, img *Image) {
	if tt.privileged == true {
		test.EnsurePrivilege(t)
	} else {
		test.DropPrivilege(t)
		defer test.ResetPrivilege(t)
	}

	auth, err := img.AuthorizedGroup(tt.groups)
	if tt.shouldPass == false && (auth == true && err == nil) {
		t.Fatal("invalid group list was reported as authorized")
	}
	if tt.shouldPass == true && (auth == false || err != nil) {
		if err != nil {
			t.Fatalf("valid group list was reported as not authorized: %s", err)
		} else {
			t.Fatal("valid group list was reported as not authorized")
		}
	}
}

func TestPrivilegedAuthorizedGroup(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	test.EnsurePrivilege(t) // to make sure we create the image under the correct user

	tests := []groupTest{
		{
			name:       "root - empty group list",
			privileged: true,
			groups:     []string{""},
			shouldPass: false,
		},
		/* This case does not pass with CircleCI so we deactivate it for now
		{
			name:       "root",
			privileged: true,
			groups:     []string{"root"},
			shouldPass: true,
		},
		*/
	}

	// XXX(mem): This is what makes this test slow
	img, path := createImage(t)
	defer os.Remove(path)

	for _, tt := range tests {
		runAuthorizedGroupTest(t, tt, img)
	}
}

//nolint:dupl
func TestAuthorizedGroup(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	test.DropPrivilege(t)
	defer test.ResetPrivilege(t)

	// Note that we do not test the "root" case here, privileged cases are
	// performed in a separate function.
	tests := []groupTest{
		{
			name:       "empty group list",
			privileged: false,
			groups:     []string{""},
			shouldPass: false,
		},
		{
			name:       "invalid group list",
			privileged: false,
			groups:     []string{"-"},
			shouldPass: false,
		},
	}

	gid := os.Getgid()
	myGroup, err := user.LookupGroupId(strconv.Itoa(gid))
	if err != nil {
		t.Fatalf("cannot get group ID: %s\n", err)
	}

	validTest := groupTest{
		name:       "valid group list",
		privileged: false,
		groups:     []string{myGroup.Name},
		shouldPass: true,
	}
	tests = append(tests, validTest)

	// XXX(mem): This is what makes this test slow
	img, path := createImage(t)
	defer os.Remove(path)

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			runAuthorizedGroupTest(t, test, img)
		})
	}
}