module main import nspkg.tests.coracle as alpm import nspkg.engine import nspkg.tests.httpfixtures import os #include "@DIR/sandbox_probe.h" #include "@DIR/reference_log.h" type DownloadSandboxLog = fn (voidptr, u32, &u8) fn C.v_alpm_reference_log_install(voidptr, DownloadSandboxLog, voidptr) voidptr fn C.v_alpm_reference_log_remove(voidptr, voidptr) fn C.v_alpm_probe_install_signal() i32 fn C.v_alpm_probe_signal_number() i32 fn C.v_alpm_probe_owner(&char) i32 fn C.setsid() i32 struct Events { parent int mut: items []string logs []string wrong_process bool handle &engine.Handle = unsafe { nil } interrupt bool signal_group bool } fn sandbox_setup_log(context voidptr, level u32, message string) { filesystem := message.starts_with('filesystem access has been restricted to ') if !filesystem && !message.starts_with('successfully restricted ') { return } mut trace := unsafe { &Events(context) } trace.wrong_process = trace.wrong_process || os.getpid() != trace.parent trace.logs << if filesystem { '${level}:filesystem\n' } else { '${level}:${message}' } } fn native_setup_log(context voidptr, level engine.LogLevel, message string) { sandbox_setup_log(context, u32(level), message) } fn reference_setup_log(context voidptr, level u32, message &u8) { sandbox_setup_log(context, level, unsafe { tos_clone(message) }) } fn native_event(context voidptr, event engine.DownloadEvent) { mut trace := unsafe { &Events(context) } trace.wrong_process = trace.wrong_process || os.getpid() != trace.parent if event.kind == .init { trace.items << '${event.filename}|init|${event.optional}' } if event.kind == .completed { trace.items << '${event.filename}|done|${event.total}|${event.result}' } if trace.interrupt && event.kind == .init { trace.handle.interrupt_downloads_async() } if trace.signal_group && event.kind == .init { C.kill(0, C.SIGINT) } } fn reference_event(context voidptr, filename &u8, kind alpm.DownloadEventType, data voidptr) { mut trace := unsafe { &Events(context) } trace.wrong_process = trace.wrong_process || os.getpid() != trace.parent name := unsafe { cstring_to_vstring(filename) } if kind == .init { value := unsafe { &alpm.DownloadEventInit(data) } trace.items << '${name}|init|${value.optional != 0}' } if kind == .completed { value := unsafe { &alpm.DownloadEventCompleted(data) } trace.items << '${name}|done|${value.total}|${value.result}' } } fn reply(_ voidptr, request httpfixtures.Request) httpfixtures.Response { if request.path == '/signal.pkg.tar' { return httpfixtures.Response{ body: 'content', delay_ms: 1000 } } if request.path in ['/missing.pkg.tar', '/optional.pkg.tar.sig'] { return httpfixtures.Response{ status: 404, body: 'missing' } } if request.path.ends_with('.sig') { return httpfixtures.Response{ body: 'signature' } } if request.headers['if-modified-since'] == 'Tue, 14 Nov 2023 22:13:20 GMT' { return httpfixtures.Response{ status: 304 } } if request.headers['range'] == 'bytes=4-' { return httpfixtures.Response{ status: 206 body: 'ent' headers: { 'Content-Range': 'bytes 4-6/7' 'Last-Modified': 'Tue, 14 Nov 2023 22:13:20 GMT' } } } return httpfixtures.Response{ body: 'content' headers: { 'Last-Modified': 'Tue, 14 Nov 2023 22:13:20 GMT' } } } struct FetchState { parent int mut: calls int retained i32 = -1 wrong_process bool current bool } fn external_fetch(context voidptr, request engine.FetchRequest) int { mut state := unsafe { &FetchState(context) } state.calls++ state.wrong_process = state.wrong_process || os.getpid() != state.parent || C.getuid() != 0 if state.current { return 1 } path := request.directory + request.filename os.write_file(path, 'trusted') or { return -1 } state.retained = C.open(unsafe { &char(path.str) }, C.O_WRONLY) return 0 } fn main() { run() or { eprintln(err) exit(1) } } fn run() ! { if os.args.len != 4 { return error('expected base and two disable flags') } // terminal-signal tests must never signal the surrounding test runner's group. if C.setsid() < 0 { return os.last_error() } base := os.args[1] disable_fs := os.args[2] == 'off' disable_syscalls := os.args[3] == 'off' proxy := httpfixtures.local_only()! defer { proxy.restore() or { eprintln(err) } } mut server := httpfixtures.start(reply, unsafe { nil })! defer { server.close() or { eprintln(err) } } for scenario in ['plain', 'signed', 'optional', 'resumed', 'current', 'missing'] { old_cache := os.join_path(base, scenario, 'old') cache := os.join_path(base, scenario, 'native') os.mkdir_all(old_cache, mode: 0o755)! os.mkdir_all(cache, mode: 0o755)! old := alpm.initialize('/', base)! defer { old.release() or { eprintln(err) } } old.option_add_cachedir(old_cache)! old.option_set_sandboxuser('nobody')! old.option_set_disable_sandbox_filesystem(u16(disable_fs))! old.option_set_disable_sandbox_syscalls(u16(disable_syscalls))! old.option_set_remote_file_siglevel(unsafe { alpm.SigLevel(if scenario == 'signed' { 1 } else if scenario == 'optional' { 3 } else { 0 }) })! mut native := engine.initialize('/', base)! defer { native.release() or { eprintln(err) } } native.set_string_option(.sandbox_user, 'nobody')! native.set_integer_option(.disable_sandbox_filesystem, int(disable_fs))! native.set_integer_option(.disable_sandbox_syscalls, int(disable_syscalls))! mut expected := &Events{ parent: os.getpid() } mut actual := &Events{ parent: os.getpid(), handle: native } old.option_set_dlcb(reference_event, expected)! native.set_download_callback(native_event, actual)! adapter := C.v_alpm_reference_log_install(old, reference_setup_log, expected) defer { C.v_alpm_reference_log_remove(old, adapter) } native.set_log_callback(native_setup_log, actual)! name := '${scenario}.pkg.tar' if scenario == 'resumed' { for target in [old_cache, cache] { os.write_file(os.join_path(target, name + '.part'), 'cont')! } } if scenario == 'current' { for target in [old_cache, cache] { path := os.join_path(target, name) os.write_file(path, 'content')! os.utime(path, 1700000000, 1700000000)! } // fetch_pkgurl returns cached packages without a request; use a plain native refresh. report := native.download_files([engine.DownloadRequest{ url: server.url + '/' + name, filename: name }], cache)! assert !report.updated && report.files[0].result == 1 assert os.read_file(os.join_path(cache, name))! == 'content' assert !actual.wrong_process continue } mut urls := &alpm.List(unsafe { nil }) assert (&urls).append_strdup(server.url + '/' + name) != unsafe { nil } defer { urls.free_inner(C.free) urls.free() } mut expected_success := false if files := old.fetch_pkgurl(urls) { expected_success = true files.free_inner(C.free) files.free() } mut actual_success := false if _ := native.download_files([engine.DownloadRequest{ url: server.url + '/' + name filename: name allow_resume: true download_signature: scenario in [ 'signed', 'optional', ] signature_optional: scenario == 'optional' }], cache) { actual_success = true } assert actual_success == expected_success, '${scenario}: ${native.error()}' assert actual.items == expected.items, '${scenario}: ${actual.items} != ${expected.items}' assert actual.logs == expected.logs, '${scenario}: ${actual.logs} != ${expected.logs}' assert (actual.logs.len > 0) == (!disable_fs || !disable_syscalls) assert !actual.wrong_process && !expected.wrong_process mut old_files := os.ls(old_cache)! mut actual_files := os.ls(cache)! old_files.sort() actual_files.sort() assert actual_files == old_files, scenario for filename in old_files { file := os.join_path(cache, filename) assert C.v_alpm_probe_owner(unsafe { &char(file.str) }) == 1 assert os.read_file(os.join_path(old_cache, filename))! == os.read_file(os.join_path(cache, filename))! assert os.stat(os.join_path(old_cache, filename))!.mode & 0o777 == os.stat(os.join_path(cache, filename))!.mode & 0o777 } } cache := os.join_path(base, 'callbacks') os.mkdir_all(cache, mode: 0o755)! mut native := engine.initialize('/', base)! defer { native.release() or { eprintln(err) } } native.set_string_option(.sandbox_user, 'nobody')! native.set_integer_option(.disable_sandbox_filesystem, int(disable_fs))! native.set_integer_option(.disable_sandbox_syscalls, int(disable_syscalls))! mut trace := &Events{ parent: os.getpid(), handle: native, interrupt: true } native.set_download_callback(native_event, trace)! if _ := native.download_files([engine.DownloadRequest{ url: server.url + '/interrupt.pkg.tar', filename: 'interrupt.pkg.tar' }], cache) { return error('interruption succeeded') } assert native.errno() == .trans_abort, native.error().msg() trace.interrupt = false reused := native.download_files([engine.DownloadRequest{ url: server.url + '/interrupt.pkg.tar', filename: 'interrupt.pkg.tar' }], cache)! // a fast transfer may have completed before the parent processed cancellation. assert reused.files[0].result in [0, 1] assert os.read_file(os.join_path(cache, 'interrupt.pkg.tar'))! == 'content' if !disable_fs || !disable_syscalls { assert C.v_alpm_probe_install_signal() == 0 trace.signal_group = true if _ := native.download_files([engine.DownloadRequest{ url: server.url + '/signal.pkg.tar', filename: 'signal.pkg.tar' }], cache) { return error('terminal signal did not stop worker') } assert native.errno() == .retrieve assert C.v_alpm_probe_signal_number() == C.SIGINT trace.signal_group = false assert os.ls(cache)!.all(!it.starts_with('download-')) } mut fetch := &FetchState{ parent: os.getpid() } native.set_fetch_callback(external_fetch, fetch)! assert native.download_files([engine.DownloadRequest{ url: server.url + '/external.pkg.tar', filename: 'external.pkg.tar' }], cache)!.updated assert fetch.calls == 1 && !fetch.wrong_process assert fetch.retained >= 0 defer { assert C.close(fetch.retained) == 0 } assert C.write(fetch.retained, c'changed', 7) == 7 if !disable_fs || !disable_syscalls { assert os.read_file(os.join_path(cache, 'external.pkg.tar'))! == 'trusted' } fetch.current = true assert !native.download_files([engine.DownloadRequest{ url: server.url + '/external.pkg.tar', filename: 'external.pkg.tar' }], cache)!.updated assert fetch.calls == 2 && !fetch.wrong_process assert os.ls(cache)!.all(!it.starts_with('download-')) println('sandbox downloads verified') }