|
| 1 | +/* |
| 2 | +Copyright The Kubernetes Authors |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package testutils |
| 18 | + |
| 19 | +import ( |
| 20 | + "os" |
| 21 | + "os/exec" |
| 22 | + "strings" |
| 23 | + "sync" |
| 24 | + "syscall" |
| 25 | + "testing" |
| 26 | +) |
| 27 | + |
| 28 | +var ( |
| 29 | + isSupported bool |
| 30 | + checkOnce sync.Once |
| 31 | +) |
| 32 | + |
| 33 | +// IsSupported checks if unprivileged user namespaces are enabled on the host system. |
| 34 | +// It caches the result after the first check. |
| 35 | +func IsSupported() bool { |
| 36 | + checkOnce.Do(func() { |
| 37 | + cmd := exec.Command("sleep", "1") |
| 38 | + |
| 39 | + // Attempt to map ourselves to root inside the userns. |
| 40 | + cmd.SysProcAttr = &syscall.SysProcAttr{ |
| 41 | + Cloneflags: syscall.CLONE_NEWUSER, |
| 42 | + UidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getuid(), Size: 1}}, |
| 43 | + GidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getgid(), Size: 1}}, |
| 44 | + } |
| 45 | + |
| 46 | + if err := cmd.Start(); err != nil { |
| 47 | + return // User namespaces are likely restricted or not supported |
| 48 | + } |
| 49 | + |
| 50 | + defer func() { |
| 51 | + _ = cmd.Process.Kill() |
| 52 | + _ = cmd.Wait() |
| 53 | + }() |
| 54 | + |
| 55 | + isSupported = true |
| 56 | + }) |
| 57 | + |
| 58 | + return isSupported |
| 59 | +} |
| 60 | + |
| 61 | +// Run executes the given test function inside a user namespace where the |
| 62 | +// current user is mapped to root. This provides capabilities to create network |
| 63 | +// namespaces and netfilter rules without running as actual root on the host. |
| 64 | +// |
| 65 | +// extraCloneflags can be used to request additional namespace types |
| 66 | +// (e.g., syscall.CLONE_NEWNET). |
| 67 | +func Run(t *testing.T, f func(t *testing.T), extraCloneflags ...uintptr) { |
| 68 | + const subprocessEnvKey = "GO_USERNS_SUBPROCESS_KEY" |
| 69 | + |
| 70 | + // 1. If we are already inside the subprocess, run the actual test logic. |
| 71 | + if testIDString, ok := os.LookupEnv(subprocessEnvKey); ok && testIDString == "1" { |
| 72 | + t.Run("subprocess", f) |
| 73 | + return |
| 74 | + } |
| 75 | + |
| 76 | + // 2. If we are on the host, verify support before attempting to spawn. |
| 77 | + if !IsSupported() { |
| 78 | + t.Skip("Unprivileged user namespaces are not supported on this system") |
| 79 | + } |
| 80 | + |
| 81 | + // 3. Prepare the command to re-execute the current test binary. |
| 82 | + cmd := exec.Command(os.Args[0]) |
| 83 | + cmd.Args = []string{os.Args[0], "-test.run=" + t.Name() + "$", "-test.v=true"} |
| 84 | + |
| 85 | + for _, arg := range os.Args { |
| 86 | + if strings.HasPrefix(arg, "-test.testlogfile=") { |
| 87 | + cmd.Args = append(cmd.Args, arg) |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + cmd.Env = append(os.Environ(), subprocessEnvKey+"=1") |
| 92 | + // Include sbin in PATH, as some networking commands are not found otherwise. |
| 93 | + cmd.Env = append(cmd.Env, "PATH=/usr/local/sbin:/usr/sbin:/sbin:"+os.Getenv("PATH")) |
| 94 | + cmd.Stdin = os.Stdin |
| 95 | + |
| 96 | + // 4. Configure the namespace clone flags. |
| 97 | + cloneflags := uintptr(syscall.CLONE_NEWUSER) |
| 98 | + for _, flag := range extraCloneflags { |
| 99 | + cloneflags |= flag |
| 100 | + } |
| 101 | + |
| 102 | + // Map ourselves to root inside the new user namespace. |
| 103 | + cmd.SysProcAttr = &syscall.SysProcAttr{ |
| 104 | + Cloneflags: cloneflags, |
| 105 | + UidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getuid(), Size: 1}}, |
| 106 | + GidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getgid(), Size: 1}}, |
| 107 | + } |
| 108 | + |
| 109 | + // 5. Execute and capture output. |
| 110 | + out, err := cmd.CombinedOutput() |
| 111 | + |
| 112 | + // Prepending a newline makes the nested test output much easier to read |
| 113 | + // in the standard `go test` log format. |
| 114 | + t.Logf("\n%s", out) |
| 115 | + if err != nil { |
| 116 | + t.Fatalf("Subprocess execution failed: %v", err) |
| 117 | + } |
| 118 | +} |
0 commit comments