File: chown_test.go

package info (click to toggle)
golang-github-containers-common 0.62.2%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,436 kB
  • sloc: makefile: 131; sh: 102
file content (124 lines) | stat: -rw-r--r-- 2,014 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
package chown

import (
	"os"
	"runtime"
	"syscall"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestDangerousHostPath(t *testing.T) {
	if runtime.GOOS != "linux" {
		t.Skip("Current paths are supported only by Linux")
	}

	tests := []struct {
		Path             string
		Expected         bool
		ExpectError      bool
		ExpectedErrorMsg string
	}{
		{
			"/tmp",
			true,
			false,
			"",
		},
		{
			t.TempDir(), // Create a temp dir that is not dangerous
			false,
			false,
			"",
		},
		{
			"/doesnotexist",
			false,
			true,
			"no such file or directory",
		},
	}

	for _, test := range tests {
		result, err := DangerousHostPath(test.Path)
		if test.ExpectError {
			assert.Error(t, err)
			assert.Contains(t, err.Error(), test.ExpectedErrorMsg)
		} else {
			assert.NoError(t, err)
			assert.Equal(t, test.Expected, result)
		}
	}
}

func TestChangeHostPathOwnership(t *testing.T) {
	if runtime.GOOS != "linux" {
		t.Skip("Current paths are supported only by Linux")
	}

	// Create a temp dir that is not dangerous
	td := t.TempDir()

	// Get host path info
	f, err := os.Lstat(td)
	if err != nil {
		t.Fatal(err)
	}

	// Get current ownership
	currentUID := int(f.Sys().(*syscall.Stat_t).Uid)
	currentGID := int(f.Sys().(*syscall.Stat_t).Gid)

	tests := []struct {
		Path             string
		Recursive        bool
		UID              int
		GID              int
		ExpectError      bool
		ExpectedErrorMsg string
	}{
		{
			"/doesnotexist",
			false,
			0,
			0,
			true,
			"no such file or directory",
		},
		{
			"/tmp",
			false,
			0,
			0,
			true,
			"is not allowed",
		},
		{
			td,
			false,
			currentUID,
			currentGID,
			false,
			"",
		},
		{
			td,
			true,
			currentUID,
			currentGID,
			false,
			"",
		},
	}

	for _, test := range tests {
		err := ChangeHostPathOwnership(test.Path, test.Recursive, test.UID, test.GID)
		if test.ExpectError {
			assert.Error(t, err)
			assert.Contains(t, err.Error(), test.ExpectedErrorMsg)
		} else {
			assert.NoError(t, err)
		}
	}
}