nspkg / tests / sandbox_download_probe.v
277 lines · 261 sloc · 10.4 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1module main
2
3import nspkg.tests.coracle as alpm
4import nspkg.engine
5import nspkg.tests.httpfixtures
6import os
7
8#include "@DIR/sandbox_probe.h"
9#include "@DIR/reference_log.h"
10
11type DownloadSandboxLog = fn (voidptr, u32, &u8)
12
13fn C.v_alpm_reference_log_install(voidptr, DownloadSandboxLog, voidptr) voidptr
14fn C.v_alpm_reference_log_remove(voidptr, voidptr)
15
16fn C.v_alpm_probe_install_signal() i32
17fn C.v_alpm_probe_signal_number() i32
18fn C.v_alpm_probe_owner(&char) i32
19fn C.setsid() i32
20
21struct Events {
22 parent int
23mut:
24 items []string
25 logs []string
26 wrong_process bool
27 handle &engine.Handle = unsafe { nil }
28 interrupt bool
29 signal_group bool
30}
31
32fn sandbox_setup_log(context voidptr, level u32, message string) {
33 filesystem := message.starts_with('filesystem access has been restricted to ')
34 if !filesystem && !message.starts_with('successfully restricted ') { return }
35 mut trace := unsafe { &Events(context) }
36 trace.wrong_process = trace.wrong_process || os.getpid() != trace.parent
37 trace.logs << if filesystem { '${level}:filesystem\n' } else { '${level}:${message}' }
38}
39
40fn native_setup_log(context voidptr, level engine.LogLevel, message string) {
41 sandbox_setup_log(context, u32(level), message)
42}
43
44fn reference_setup_log(context voidptr, level u32, message &u8) {
45 sandbox_setup_log(context, level, unsafe { tos_clone(message) })
46}
47
48fn native_event(context voidptr, event engine.DownloadEvent) {
49 mut trace := unsafe { &Events(context) }
50 trace.wrong_process = trace.wrong_process || os.getpid() != trace.parent
51 if event.kind == .init { trace.items << '${event.filename}|init|${event.optional}' }
52 if event.kind == .completed {
53 trace.items << '${event.filename}|done|${event.total}|${event.result}'
54 }
55 if trace.interrupt && event.kind == .init { trace.handle.interrupt_downloads_async() }
56 if trace.signal_group && event.kind == .init { C.kill(0, C.SIGINT) }
57}
58
59fn reference_event(context voidptr, filename &u8, kind alpm.DownloadEventType, data voidptr) {
60 mut trace := unsafe { &Events(context) }
61 trace.wrong_process = trace.wrong_process || os.getpid() != trace.parent
62 name := unsafe { cstring_to_vstring(filename) }
63 if kind == .init {
64 value := unsafe { &alpm.DownloadEventInit(data) }
65 trace.items << '${name}|init|${value.optional != 0}'
66 }
67 if kind == .completed {
68 value := unsafe { &alpm.DownloadEventCompleted(data) }
69 trace.items << '${name}|done|${value.total}|${value.result}'
70 }
71}
72
73fn reply(_ voidptr, request httpfixtures.Request) httpfixtures.Response {
74 if request.path == '/signal.pkg.tar' {
75 return httpfixtures.Response{ body: 'content', delay_ms: 1000 }
76 }
77 if request.path in ['/missing.pkg.tar', '/optional.pkg.tar.sig'] {
78 return httpfixtures.Response{ status: 404, body: 'missing' }
79 }
80 if request.path.ends_with('.sig') { return httpfixtures.Response{ body: 'signature' } }
81 if request.headers['if-modified-since'] == 'Tue, 14 Nov 2023 22:13:20 GMT' {
82 return httpfixtures.Response{ status: 304 }
83 }
84 if request.headers['range'] == 'bytes=4-' {
85 return httpfixtures.Response{
86 status: 206
87 body: 'ent'
88 headers: {
89 'Content-Range': 'bytes 4-6/7'
90 'Last-Modified': 'Tue, 14 Nov 2023 22:13:20 GMT'
91 }
92 }
93 }
94 return httpfixtures.Response{
95 body: 'content'
96 headers: {
97 'Last-Modified': 'Tue, 14 Nov 2023 22:13:20 GMT'
98 }
99 }
100}
101
102struct FetchState {
103 parent int
104mut:
105 calls int
106 retained i32 = -1
107 wrong_process bool
108 current bool
109}
110
111fn external_fetch(context voidptr, request engine.FetchRequest) int {
112 mut state := unsafe { &FetchState(context) }
113 state.calls++
114 state.wrong_process = state.wrong_process || os.getpid() != state.parent || C.getuid() != 0
115 if state.current { return 1 }
116 path := request.directory + request.filename
117 os.write_file(path, 'trusted') or { return -1 }
118 state.retained = C.open(unsafe { &char(path.str) }, C.O_WRONLY)
119 return 0
120}
121
122fn main() {
123 run() or {
124 eprintln(err)
125 exit(1)
126 }
127}
128
129fn run() ! {
130 if os.args.len != 4 { return error('expected base and two disable flags') }
131 // terminal-signal tests must never signal the surrounding test runner's group.
132 if C.setsid() < 0 { return os.last_error() }
133 base := os.args[1]
134 disable_fs := os.args[2] == 'off'
135 disable_syscalls := os.args[3] == 'off'
136 proxy := httpfixtures.local_only()!
137 defer { proxy.restore() or { eprintln(err) } }
138 mut server := httpfixtures.start(reply, unsafe { nil })!
139 defer { server.close() or { eprintln(err) } }
140 for scenario in ['plain', 'signed', 'optional', 'resumed', 'current', 'missing'] {
141 old_cache := os.join_path(base, scenario, 'old')
142 cache := os.join_path(base, scenario, 'native')
143 os.mkdir_all(old_cache, mode: 0o755)!
144 os.mkdir_all(cache, mode: 0o755)!
145 old := alpm.initialize('/', base)!
146 defer { old.release() or { eprintln(err) } }
147 old.option_add_cachedir(old_cache)!
148 old.option_set_sandboxuser('nobody')!
149 old.option_set_disable_sandbox_filesystem(u16(disable_fs))!
150 old.option_set_disable_sandbox_syscalls(u16(disable_syscalls))!
151 old.option_set_remote_file_siglevel(unsafe {
152 alpm.SigLevel(if scenario == 'signed' {
153 1
154 } else if scenario == 'optional' {
155 3
156 } else {
157 0
158 })
159 })!
160 mut native := engine.initialize('/', base)!
161 defer { native.release() or { eprintln(err) } }
162 native.set_string_option(.sandbox_user, 'nobody')!
163 native.set_integer_option(.disable_sandbox_filesystem, int(disable_fs))!
164 native.set_integer_option(.disable_sandbox_syscalls, int(disable_syscalls))!
165 mut expected := &Events{ parent: os.getpid() }
166 mut actual := &Events{ parent: os.getpid(), handle: native }
167 old.option_set_dlcb(reference_event, expected)!
168 native.set_download_callback(native_event, actual)!
169 adapter := C.v_alpm_reference_log_install(old, reference_setup_log, expected)
170 defer { C.v_alpm_reference_log_remove(old, adapter) }
171 native.set_log_callback(native_setup_log, actual)!
172 name := '${scenario}.pkg.tar'
173 if scenario == 'resumed' {
174 for target in [old_cache, cache] {
175 os.write_file(os.join_path(target, name + '.part'), 'cont')!
176 }
177 }
178 if scenario == 'current' {
179 for target in [old_cache, cache] {
180 path := os.join_path(target, name)
181 os.write_file(path, 'content')!
182 os.utime(path, 1700000000, 1700000000)!
183 }
184 // fetch_pkgurl returns cached packages without a request; use a plain native refresh.
185 report := native.download_files([engine.DownloadRequest{ url: server.url + '/' + name, filename: name }], cache)!
186 assert !report.updated && report.files[0].result == 1
187 assert os.read_file(os.join_path(cache, name))! == 'content'
188 assert !actual.wrong_process
189 continue
190 }
191 mut urls := &alpm.List(unsafe { nil })
192 assert (&urls).append_strdup(server.url + '/' + name) != unsafe { nil }
193 defer {
194 urls.free_inner(C.free)
195 urls.free()
196 }
197 mut expected_success := false
198 if files := old.fetch_pkgurl(urls) {
199 expected_success = true
200 files.free_inner(C.free)
201 files.free()
202 }
203 mut actual_success := false
204 if _ := native.download_files([engine.DownloadRequest{
205 url: server.url + '/' + name
206 filename: name
207 allow_resume: true
208 download_signature: scenario in [
209 'signed',
210 'optional',
211 ]
212 signature_optional: scenario == 'optional'
213 }], cache) {
214 actual_success = true
215 }
216 assert actual_success == expected_success, '${scenario}: ${native.error()}'
217 assert actual.items == expected.items, '${scenario}: ${actual.items} != ${expected.items}'
218 assert actual.logs == expected.logs, '${scenario}: ${actual.logs} != ${expected.logs}'
219 assert (actual.logs.len > 0) == (!disable_fs || !disable_syscalls)
220 assert !actual.wrong_process && !expected.wrong_process
221 mut old_files := os.ls(old_cache)!
222 mut actual_files := os.ls(cache)!
223 old_files.sort()
224 actual_files.sort()
225 assert actual_files == old_files, scenario
226 for filename in old_files {
227 file := os.join_path(cache, filename)
228 assert C.v_alpm_probe_owner(unsafe { &char(file.str) }) == 1
229 assert os.read_file(os.join_path(old_cache, filename))! == os.read_file(os.join_path(cache, filename))!
230 assert os.stat(os.join_path(old_cache, filename))!.mode & 0o777 == os.stat(os.join_path(cache, filename))!.mode & 0o777
231 }
232 }
233 cache := os.join_path(base, 'callbacks')
234 os.mkdir_all(cache, mode: 0o755)!
235 mut native := engine.initialize('/', base)!
236 defer { native.release() or { eprintln(err) } }
237 native.set_string_option(.sandbox_user, 'nobody')!
238 native.set_integer_option(.disable_sandbox_filesystem, int(disable_fs))!
239 native.set_integer_option(.disable_sandbox_syscalls, int(disable_syscalls))!
240 mut trace := &Events{ parent: os.getpid(), handle: native, interrupt: true }
241 native.set_download_callback(native_event, trace)!
242 if _ := native.download_files([engine.DownloadRequest{ url: server.url + '/interrupt.pkg.tar', filename: 'interrupt.pkg.tar' }], cache) {
243 return error('interruption succeeded')
244 }
245 assert native.errno() == .trans_abort, native.error().msg()
246 trace.interrupt = false
247 reused := native.download_files([engine.DownloadRequest{ url: server.url + '/interrupt.pkg.tar', filename: 'interrupt.pkg.tar' }], cache)!
248 // a fast transfer may have completed before the parent processed cancellation.
249 assert reused.files[0].result in [0, 1]
250 assert os.read_file(os.join_path(cache, 'interrupt.pkg.tar'))! == 'content'
251 if !disable_fs || !disable_syscalls {
252 assert C.v_alpm_probe_install_signal() == 0
253 trace.signal_group = true
254 if _ := native.download_files([engine.DownloadRequest{ url: server.url + '/signal.pkg.tar', filename: 'signal.pkg.tar' }], cache) {
255 return error('terminal signal did not stop worker')
256 }
257 assert native.errno() == .retrieve
258 assert C.v_alpm_probe_signal_number() == C.SIGINT
259 trace.signal_group = false
260 assert os.ls(cache)!.all(!it.starts_with('download-'))
261 }
262 mut fetch := &FetchState{ parent: os.getpid() }
263 native.set_fetch_callback(external_fetch, fetch)!
264 assert native.download_files([engine.DownloadRequest{ url: server.url + '/external.pkg.tar', filename: 'external.pkg.tar' }], cache)!.updated
265 assert fetch.calls == 1 && !fetch.wrong_process
266 assert fetch.retained >= 0
267 defer { assert C.close(fetch.retained) == 0 }
268 assert C.write(fetch.retained, c'changed', 7) == 7
269 if !disable_fs || !disable_syscalls {
270 assert os.read_file(os.join_path(cache, 'external.pkg.tar'))! == 'trusted'
271 }
272 fetch.current = true
273 assert !native.download_files([engine.DownloadRequest{ url: server.url + '/external.pkg.tar', filename: 'external.pkg.tar' }], cache)!.updated
274 assert fetch.calls == 2 && !fetch.wrong_process
275 assert os.ls(cache)!.all(!it.starts_with('download-'))
276 println('sandbox downloads verified')
277}
278