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
//go:build linux

package builder_test

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"syscall"
	"testing"
)

const (
	busyboxURL  = "https://busybox.net/downloads/binaries/1.35.0-x86_64-linux-musl/busybox"
	busyboxSHA  = "6e123e7f3202a8c1e9b1f94d8941580a25135382b99e8d3e34fb858bba311348"
	busyboxFile = "busybox-1.35.0-x86_64"
)

// fetchBusybox downloads the static busybox binary into testdata/, verifies its
// SHA-256, and returns the path to the binary.  The test is skipped if the
// network is unavailable or -short is set.
func fetchBusybox(t *testing.T) string {
	t.Helper()
	if testing.Short() {
		t.Skip("skipping network fetch in -short mode")
	}

	cacheDir := filepath.Join("testdata")
	if err := os.MkdirAll(cacheDir, 0o755); err != nil {
		t.Fatalf("creating testdata dir: %v", err)
	}
	dst := filepath.Join(cacheDir, busyboxFile)

	// Verify cache hit.
	if _, err := os.Stat(dst); err == nil {
		if verifySHA256(t, dst, busyboxSHA) {
			return dst
		}
		// Bad cache entry — re-download.
		os.Remove(dst)
	}

	t.Log("downloading static busybox from", busyboxURL)
	resp, err := http.Get(busyboxURL)
	if err != nil {
		t.Skipf("cannot fetch busybox (offline?): %v", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		t.Skipf("busybox fetch returned HTTP %d", resp.StatusCode)
	}

	f, err := os.CreateTemp(cacheDir, "busybox-tmp-*")
	if err != nil {
		t.Fatalf("creating temp file: %v", err)
	}
	tmpPath := f.Name()
	defer func() { os.Remove(tmpPath) }()

	h := sha256.New()
	if _, err := io.Copy(io.MultiWriter(f, h), resp.Body); err != nil {
		f.Close()
		t.Fatalf("writing busybox: %v", err)
	}
	f.Close()

	got := hex.EncodeToString(h.Sum(nil))
	if got != busyboxSHA {
		t.Fatalf("busybox SHA-256 mismatch: got %s want %s", got, busyboxSHA)
	}
	if err := os.Chmod(tmpPath, 0o755); err != nil {
		t.Fatalf("chmod busybox: %v", err)
	}
	if err := os.Rename(tmpPath, dst); err != nil {
		t.Fatalf("installing busybox: %v", err)
	}
	t.Log("busybox cached at", dst)
	return dst
}

func verifySHA256(t *testing.T, path, want string) bool {
	t.Helper()
	f, err := os.Open(path)
	if err != nil {
		return false
	}
	defer f.Close()
	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return false
	}
	return hex.EncodeToString(h.Sum(nil)) == want
}

// userNSAvailable probes whether unprivileged user namespaces are available on
// this kernel.  Tests are skipped when they aren't.
func userNSAvailable(t *testing.T) {
	t.Helper()

	// Check the kernel knob first (not present on all distros).
	if data, err := os.ReadFile("/proc/sys/kernel/unprivileged_userns_clone"); err == nil {
		if len(data) > 0 && data[0] == '0' {
			t.Skip("unprivileged user namespaces disabled (unprivileged_userns_clone=0)")
		}
	}

	// Try to actually unshare to confirm it works.
	cmd := exec.Command("/proc/self/exe", "__builder_probe")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Cloneflags: syscall.CLONE_NEWUSER,
		UidMappings: []syscall.SysProcIDMap{
			{ContainerID: 0, HostID: os.Getuid(), Size: 1},
		},
		GidMappings: []syscall.SysProcIDMap{
			{ContainerID: 0, HostID: os.Getgid(), Size: 1},
		},
		GidMappingsEnableSetgroups: false,
	}
	if err := cmd.Run(); err != nil {
		// Exit 1 from the probe subcommand is expected (it exits immediately);
		// only a start failure (EPERM / EINVAL) means no userns.
		if exitErr, ok := err.(*exec.ExitError); ok {
			ws := exitErr.Sys().(syscall.WaitStatus)
			if ws.ExitStatus() == 42 {
				return // probe succeeded
			}
		}
		t.Skipf("user namespaces not available: %v", err)
	}
}

// busyboxDir creates a temp directory containing the busybox binary and a
// symlink "sh -> busybox".  It registers cleanup with t.Cleanup.
func busyboxDir(t *testing.T) string {
	t.Helper()
	bbPath := fetchBusybox(t)

	dir := t.TempDir()
	dst := filepath.Join(dir, "busybox")

	// Hard-link or copy into the temp dir.
	if err := linkOrCopy(bbPath, dst); err != nil {
		t.Fatalf("installing busybox into temp dir: %v", err)
	}
	if err := os.Chmod(dst, 0o755); err != nil {
		t.Fatalf("chmod busybox: %v", err)
	}
	if err := os.Symlink("busybox", filepath.Join(dir, "sh")); err != nil {
		t.Fatalf("symlink sh->busybox: %v", err)
	}
	return dir
}

func linkOrCopy(src, dst string) error {
	if err := os.Link(src, dst); err == nil {
		return nil
	}
	// Cross-device or not supported: copy.
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()
	_, err = io.Copy(out, in)
	return err
}

// probeSubcommand is the argv[1] value the busybox-probe child uses.
const probeSubcommand = "__builder_probe"

// handleProbe exits with status 42 when invoked as the probe child.
// Called from TestMain before the test framework initialises.
func handleProbe() {
	if len(os.Args) >= 2 && os.Args[1] == probeSubcommand {
		fmt.Println("probe ok")
		os.Exit(42)
	}
}