oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build linux
2
3package render
4
5import (
6 "bufio"
7 "context"
8 "fmt"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strconv"
13 "strings"
14 "sync/atomic"
15 "testing"
16 "time"
17
18 "golang.org/x/sys/unix"
19)
20
21// processTree starts a shell with two children and returns it once both
22// are running.
23func processTree(t *testing.T) *exec.Cmd {
24 t.Helper()
25 sh, err := exec.LookPath("sh")
26 if err != nil {
27 t.Skip("no sh")
28 }
29 cmd := exec.Command(sh, "-c", "sleep 30 & sleep 30 & wait")
30 if err := cmd.Start(); err != nil {
31 t.Fatal(err)
32 }
33 t.Cleanup(func() {
34 for _, pid := range descendants(cmd.Process.Pid) {
35 unix.Kill(pid, unix.SIGKILL)
36 }
37 cmd.Process.Kill()
38 cmd.Wait()
39 })
40 deadline := time.Now().Add(5 * time.Second)
41 for len(descendants(cmd.Process.Pid)) < 2 {
42 if time.Now().After(deadline) {
43 t.Fatal("the shell's children did not start")
44 }
45 time.Sleep(10 * time.Millisecond)
46 }
47 return cmd
48}
49
50// The sum is the whole tree's: the root and every process below it.
51func TestTreeRSSSumsTheTree(t *testing.T) {
52 cmd := processTree(t)
53 page := int64(os.Getpagesize())
54 root := residentPages(cmd.Process.Pid) * page
55 want := root
56 for _, pid := range descendants(cmd.Process.Pid) {
57 want += residentPages(pid) * page
58 }
59 got := treeRSS(cmd.Process.Pid)
60 if root <= 0 || got <= root || got < want*9/10 {
61 t.Fatalf("tree %d, root alone %d, processes summed %d", got, root, want)
62 }
63 if treeRSS(1<<30) != 0 {
64 t.Fatal("a process that does not exist holds memory")
65 }
66}
67
68// The watch kills over the limit, once, and not under it.
69func TestWatchMemory(t *testing.T) {
70 cmd := processTree(t)
71 sandbox := func() *Sandbox {
72 fd, err := unix.PidfdOpen(cmd.Process.Pid, 0)
73 if err != nil {
74 t.Skipf("pidfd_open: %v", err)
75 }
76 t.Cleanup(func() { unix.Close(fd) })
77 return &Sandbox{pidfd: fd, done: make(chan struct{})}
78 }
79 s := sandbox()
80 if s.initPID() != cmd.Process.Pid {
81 t.Fatalf("init %d, want %d", s.initPID(), cmd.Process.Pid)
82 }
83 var fired atomic.Int32
84 // Above the root's own memory, below the tree's.
85 limit := residentPages(cmd.Process.Pid)*int64(os.Getpagesize()) + 1
86 stop := watchMemory(s, limit, func() { fired.Add(1) })
87 deadline := time.Now().Add(2 * time.Second)
88 for fired.Load() == 0 && time.Now().Before(deadline) {
89 time.Sleep(10 * time.Millisecond)
90 }
91 time.Sleep(3 * memoryEvery)
92 stop()
93 if fired.Load() != 1 {
94 t.Fatalf("over the limit: fired %d times", fired.Load())
95 }
96 stop = watchMemory(sandbox(), 1<<40, func() { fired.Add(1) })
97 time.Sleep(3 * memoryEvery)
98 stop()
99 if fired.Load() != 1 {
100 t.Fatal("fired under the limit")
101 }
102}
103
104// Every process in the sandbox, the browser's included, has the call's
105// memory limit as its data segment's soft and hard limit.
106func TestSandboxHasTheMemoryLimit(t *testing.T) {
107 cfg := testConfig(t, true)
108 ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
109 defer cancel()
110 s, err := Launch(ctx, cfg)
111 if err != nil {
112 t.Fatal(err)
113 }
114 defer s.Close()
115 // The fake browser answers once it runs.
116 s.FromBrowser.SetReadDeadline(time.Now().Add(10 * time.Second))
117 s.ToBrowser.WriteString("ping\x00")
118 if reply, err := readFrame(bufio.NewReader(s.FromBrowser), 64); err != nil || string(reply) != "ping" {
119 t.Fatalf("the browser did not start: %q %v", reply, err)
120 }
121 want := fmt.Sprintf("%d", MemoryLimit)
122 var browser, sandbox bool
123 for _, pid := range descendants(s.cmd.Process.Pid) {
124 raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/limits")
125 if err != nil {
126 continue
127 }
128 cmdline, _ := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/cmdline")
129 name := strings.ReplaceAll(string(cmdline), "\x00", " ")
130 switch {
131 case strings.HasPrefix(name, BrowserPath+" "):
132 browser = true
133 case strings.HasPrefix(name, binaryPath+" "+Subcommand):
134 sandbox = true
135 default:
136 continue
137 }
138 var soft, hard string
139 for _, line := range strings.Split(string(raw), "\n") {
140 if rest, ok := strings.CutPrefix(line, "Max data size"); ok {
141 if f := strings.Fields(rest); len(f) >= 2 {
142 soft, hard = f[0], f[1]
143 }
144 }
145 }
146 if soft != want || hard != want {
147 t.Errorf("%s: data size %s soft, %s hard, want %s", name, soft, hard, want)
148 }
149 }
150 if !browser || !sandbox {
151 t.Fatalf("browser %v, render-sandbox %v found below bubblewrap", browser, sandbox)
152 }
153}
154
155// The sandbox's /tmp holds at most TmpSize: a writer filling it gets
156// ENOSPC near the bound.
157func TestSandboxTmpIsBounded(t *testing.T) {
158 cfg := testConfig(t, false)
159 r := runProbe(t, cfg, "fill-tmp")
160 if r.Fill == nil || !strings.Contains(r.Fill.Err, "no space left on device") {
161 t.Fatalf("fill %+v", r.Fill)
162 }
163 if r.Fill.Bytes > TmpSize || r.Fill.Bytes < TmpSize-(8<<20) {
164 t.Fatalf("wrote %d bytes before %s, bound %d", r.Fill.Bytes, r.Fill.Err, TmpSize)
165 }
166}
167
168// Render's out directory is the runner's: refused, before any sandbox
169// starts, unless it is absolute, clean, empty, private, this user's and
170// reached through no symlink.
171func TestRenderRefusesItsOutDir(t *testing.T) {
172 // A launch that would start: only the out directory stops it.
173 cfg := testConfig(t, true)
174 used := testOut(t)
175 must(t, os.WriteFile(filepath.Join(used, "x"), nil, 0o600))
176 open := testOut(t)
177 must(t, os.Chmod(open, 0o755))
178 link := filepath.Join(tempDir(t), "link")
179 must(t, os.Symlink(testOut(t), link))
180 file := filepath.Join(tempDir(t), "file")
181 must(t, os.WriteFile(file, nil, 0o600))
182 forked := noFork(t)
183 for name, c := range map[string]struct{ dir, why string }{
184 "relative": {"out", "output path"},
185 "unclean": {testOut(t) + "/", "output path"},
186 "used": {used, "not empty"},
187 "open": {open, "not private"},
188 "symlinked": {link, "symbolic links"},
189 "a file": {file, "not a directory"},
190 "missing": {filepath.Join(tempDir(t), "absent"), "no such file"},
191 "root's": {"/usr", "only this user can write"},
192 } {
193 _, err := Render(context.Background(), cfg, c.dir, []Page{{Path: "/", Viewport: Phone}})
194 if err == nil || !strings.Contains(err.Error(), c.why) {
195 t.Errorf("%s: %v, want %q", name, err, c.why)
196 }
197 }
198 if *forked {
199 t.Fatal("a sandbox started")
200 }
201 // A good one is held and written through.
202 dir := testOut(t)
203 root, err := openOut(dir)
204 if err != nil {
205 t.Fatal(err)
206 }
207 defer root.Close()
208 must(t, root.WriteFile("page-1.png", []byte("x"), 0o600))
209 if _, err := os.Stat(filepath.Join(dir, "page-1.png")); err != nil {
210 t.Fatal(err)
211 }
212}
213