@ship.zone/runner 2.1.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/.smartconfig.json +118 -3
  2. package/changelog.md +101 -0
  3. package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
  4. package/dist_rust/runnerworkspace_linux_amd64_musl.third-party-notices.json +679 -0
  5. package/dist_rust/runnerworkspace_linux_amd64_musl.third-party-notices.txt +15719 -0
  6. package/dist_rust/runnerworkspace_linux_amd64_musl.tsrust-build.json +5 -5
  7. package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
  8. package/dist_rust/runnerworkspace_linux_arm64_musl.third-party-notices.json +679 -0
  9. package/dist_rust/runnerworkspace_linux_arm64_musl.third-party-notices.txt +15719 -0
  10. package/dist_rust/runnerworkspace_linux_arm64_musl.tsrust-build.json +5 -5
  11. package/dist_ts/00_commitinfo_data.d.ts +8 -0
  12. package/dist_ts/00_commitinfo_data.js +9 -0
  13. package/dist_ts/api-client.d.ts +47 -0
  14. package/dist_ts/api-client.js +600 -0
  15. package/dist_ts/artifact-manager.d.ts +11 -0
  16. package/dist_ts/artifact-manager.js +140 -0
  17. package/dist_ts/attempt-state.d.ts +18 -0
  18. package/dist_ts/attempt-state.js +151 -0
  19. package/dist_ts/cache-manager.d.ts +13 -0
  20. package/dist_ts/cache-manager.js +300 -0
  21. package/dist_ts/cli-entry.d.ts +2 -0
  22. package/dist_ts/cli-entry.js +18 -0
  23. package/dist_ts/cli.d.ts +14 -0
  24. package/dist_ts/cli.js +243 -0
  25. package/dist_ts/config.d.ts +8 -0
  26. package/dist_ts/config.js +495 -0
  27. package/dist_ts/egress-proxy.d.ts +99 -0
  28. package/dist_ts/egress-proxy.js +607 -0
  29. package/dist_ts/errors.d.ts +41 -0
  30. package/dist_ts/errors.js +90 -0
  31. package/dist_ts/filesystem.d.ts +73 -0
  32. package/dist_ts/filesystem.js +207 -0
  33. package/dist_ts/index.d.ts +20 -0
  34. package/dist_ts/index.js +21 -0
  35. package/dist_ts/interfaces.d.ts +685 -0
  36. package/dist_ts/interfaces.js +3 -0
  37. package/dist_ts/log-sender.d.ts +26 -0
  38. package/dist_ts/log-sender.js +124 -0
  39. package/dist_ts/microvm-executor.d.ts +90 -0
  40. package/dist_ts/microvm-executor.js +1045 -0
  41. package/dist_ts/node-version.d.ts +11 -0
  42. package/dist_ts/node-version.js +43 -0
  43. package/dist_ts/npm-grants.d.ts +9 -0
  44. package/dist_ts/npm-grants.js +44 -0
  45. package/dist_ts/oci-registry.d.ts +73 -0
  46. package/dist_ts/oci-registry.js +508 -0
  47. package/dist_ts/plugins.d.ts +23 -0
  48. package/dist_ts/plugins.js +27 -0
  49. package/dist_ts/protocol-validator.d.ts +39 -0
  50. package/dist_ts/protocol-validator.js +488 -0
  51. package/dist_ts/redactor.d.ts +78 -0
  52. package/dist_ts/redactor.js +235 -0
  53. package/dist_ts/registration-state.d.ts +16 -0
  54. package/dist_ts/registration-state.js +171 -0
  55. package/dist_ts/runner.d.ts +65 -0
  56. package/dist_ts/runner.js +912 -0
  57. package/dist_ts/source-workspace.d.ts +10 -0
  58. package/dist_ts/source-workspace.js +125 -0
  59. package/dist_ts/spec-version.d.ts +11 -0
  60. package/dist_ts/spec-version.js +41 -0
  61. package/dist_ts/staging-scavenger.d.ts +7 -0
  62. package/dist_ts/staging-scavenger.js +63 -0
  63. package/dist_ts/state-owner.d.ts +74 -0
  64. package/dist_ts/state-owner.js +291 -0
  65. package/dist_ts/transfer-archive.d.ts +78 -0
  66. package/dist_ts/transfer-archive.js +1619 -0
  67. package/dist_ts/validation.d.ts +11 -0
  68. package/dist_ts/validation.js +79 -0
  69. package/dist_ts/vsock-protocol.d.ts +130 -0
  70. package/dist_ts/vsock-protocol.js +336 -0
  71. package/dist_ts/wire-schema.d.ts +10 -0
  72. package/dist_ts/wire-schema.js +114 -0
  73. package/native-notices/crates/bitflags-2.13.1/license-apache +201 -0
  74. package/native-notices/crates/bitflags-2.13.1/license-mit +25 -0
  75. package/native-notices/crates/cc-1.8.0/license-apache +201 -0
  76. package/native-notices/crates/cc-1.8.0/license-mit +25 -0
  77. package/native-notices/crates/cfg-if-1.0.4/license-apache +201 -0
  78. package/native-notices/crates/cfg-if-1.0.4/license-mit +25 -0
  79. package/native-notices/crates/cfg_aliases-0.2.2/license +9 -0
  80. package/native-notices/crates/cfg_aliases-0.2.2/notices.md +26 -0
  81. package/native-notices/crates/find-msvc-tools-0.1.14/license-apache +201 -0
  82. package/native-notices/crates/find-msvc-tools-0.1.14/license-mit +25 -0
  83. package/native-notices/crates/itoa-1.0.18/license-apache +176 -0
  84. package/native-notices/crates/itoa-1.0.18/license-mit +23 -0
  85. package/native-notices/crates/libc-0.2.189/license-apache +176 -0
  86. package/native-notices/crates/libc-0.2.189/license-mit +25 -0
  87. package/native-notices/crates/memchr-2.8.3/copying +3 -0
  88. package/native-notices/crates/memchr-2.8.3/license-mit +21 -0
  89. package/native-notices/crates/memchr-2.8.3/unlicense +24 -0
  90. package/native-notices/crates/nix-0.30.1/license +21 -0
  91. package/native-notices/crates/proc-macro2-1.0.107/license-apache +176 -0
  92. package/native-notices/crates/proc-macro2-1.0.107/license-mit +23 -0
  93. package/native-notices/crates/quote-1.0.47/license-apache +176 -0
  94. package/native-notices/crates/quote-1.0.47/license-mit +23 -0
  95. package/native-notices/crates/serde-1.0.229/license-apache +176 -0
  96. package/native-notices/crates/serde-1.0.229/license-mit +23 -0
  97. package/native-notices/crates/serde_core-1.0.229/license-apache +176 -0
  98. package/native-notices/crates/serde_core-1.0.229/license-mit +23 -0
  99. package/native-notices/crates/serde_derive-1.0.229/license-apache +176 -0
  100. package/native-notices/crates/serde_derive-1.0.229/license-mit +23 -0
  101. package/native-notices/crates/serde_json-1.0.151/license-apache +176 -0
  102. package/native-notices/crates/serde_json-1.0.151/license-mit +23 -0
  103. package/native-notices/crates/shlex-2.0.1/license-apache +13 -0
  104. package/native-notices/crates/shlex-2.0.1/license-mit +21 -0
  105. package/native-notices/crates/syn-3.0.3/license-apache +176 -0
  106. package/native-notices/crates/syn-3.0.3/license-mit +23 -0
  107. package/native-notices/crates/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/license-apache +201 -0
  108. package/native-notices/crates/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/license-mit +25 -0
  109. package/native-notices/crates/tikv-jemallocator-0.7.0/license-apache +201 -0
  110. package/native-notices/crates/tikv-jemallocator-0.7.0/license-mit +25 -0
  111. package/native-notices/crates/unicode-ident-1.0.24/license-apache +176 -0
  112. package/native-notices/crates/unicode-ident-1.0.24/license-mit +23 -0
  113. package/native-notices/crates/unicode-ident-1.0.24/license-unicode +39 -0
  114. package/native-notices/crates/zmij-1.0.23/license-mit +23 -0
  115. package/native-notices/manifest.json +763 -0
  116. package/native-notices/native/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/jemalloc-5.3.1/jemalloc-copying +27 -0
  117. package/native-notices/readme.md +46 -0
  118. package/native-notices/runtime/gcc/gpl-3.0.txt +674 -0
  119. package/native-notices/runtime/gcc/runtime-library-exception-3.1.txt +73 -0
  120. package/native-notices/runtime/libunwind-22.1.2/license.txt +311 -0
  121. package/native-notices/runtime/musl-1.2.5/copyright +193 -0
  122. package/native-notices/rust/compiler-builtins-license.txt +275 -0
  123. package/native-notices/rust/copyright-library.html +8266 -0
  124. package/native-notices/rust/crates/addr2line-0.25.1/license-apache +201 -0
  125. package/native-notices/rust/crates/addr2line-0.25.1/license-mit +25 -0
  126. package/native-notices/rust/crates/adler2-2.0.1/license-0bsd +12 -0
  127. package/native-notices/rust/crates/adler2-2.0.1/license-apache +201 -0
  128. package/native-notices/rust/crates/adler2-2.0.1/license-mit +23 -0
  129. package/native-notices/rust/crates/memchr-2.7.6/copying +3 -0
  130. package/native-notices/rust/crates/memchr-2.7.6/license-mit +21 -0
  131. package/native-notices/rust/crates/memchr-2.7.6/unlicense +24 -0
  132. package/native-notices/rust/crates/miniz_oxide-0.8.9/license +25 -0
  133. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-apache.md +177 -0
  134. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-mit.md +24 -0
  135. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-zlib.md +14 -0
  136. package/native-notices/rust/crates/object-0.37.3/license-apache +201 -0
  137. package/native-notices/rust/crates/object-0.37.3/license-mit +25 -0
  138. package/native-notices/rust/licenses/apache-2.0.txt +73 -0
  139. package/native-notices/rust/licenses/bsd-2-clause.txt +9 -0
  140. package/native-notices/rust/licenses/cc-by-sa-4.0.txt +427 -0
  141. package/native-notices/rust/licenses/gcc-exception-3.1.txt +30 -0
  142. package/native-notices/rust/licenses/gpl-2.0-only.txt +133 -0
  143. package/native-notices/rust/licenses/gpl-3.0-or-later.txt +202 -0
  144. package/native-notices/rust/licenses/isc.txt +7 -0
  145. package/native-notices/rust/licenses/llvm-exception.txt +15 -0
  146. package/native-notices/rust/licenses/mit.txt +9 -0
  147. package/native-notices/rust/licenses/ncsa.txt +29 -0
  148. package/native-notices/rust/licenses/ofl-1.1.txt +43 -0
  149. package/native-notices/rust/licenses/unicode-3.0.txt +39 -0
  150. package/package.json +31 -26
  151. package/readme.md +157 -95
  152. package/rust/.cargo/config.toml +1 -1
  153. package/rust/Cargo.lock +1 -0
  154. package/rust/Cargo.toml +3 -2
  155. package/rust/src/cpio.rs +147 -0
  156. package/rust/src/extfs.rs +747 -0
  157. package/rust/src/guest.rs +2411 -0
  158. package/rust/src/lib.rs +197 -1
  159. package/rust/src/main.rs +7 -2
  160. package/rust/src/oci_tar.rs +842 -0
  161. package/rust-toolchain.toml +4 -0
  162. package/ts/00_commitinfo_data.ts +2 -2
  163. package/ts/api-client.ts +29 -8
  164. package/ts/artifact-manager.ts +9 -7
  165. package/ts/attempt-state.ts +75 -84
  166. package/ts/cache-manager.ts +22 -28
  167. package/ts/cli-entry.ts +17 -0
  168. package/ts/cli.ts +86 -53
  169. package/ts/config.ts +146 -62
  170. package/ts/egress-proxy.ts +649 -0
  171. package/ts/errors.ts +19 -0
  172. package/ts/filesystem.ts +316 -0
  173. package/ts/index.ts +20 -15
  174. package/ts/interfaces.ts +105 -23
  175. package/ts/log-sender.ts +4 -4
  176. package/ts/microvm-executor.ts +1265 -0
  177. package/ts/node-version.ts +49 -0
  178. package/ts/npm-grants.ts +49 -0
  179. package/ts/oci-registry.ts +649 -0
  180. package/ts/plugins.ts +25 -3
  181. package/ts/protocol-validator.ts +34 -30
  182. package/ts/redactor.ts +2 -2
  183. package/ts/registration-state.ts +82 -90
  184. package/ts/runner.ts +81 -34
  185. package/ts/source-workspace.ts +11 -8
  186. package/ts/spec-version.ts +2 -2
  187. package/ts/staging-scavenger.ts +37 -26
  188. package/ts/state-owner.ts +353 -0
  189. package/ts/transfer-archive.ts +214 -243
  190. package/ts/validation.ts +1 -1
  191. package/ts/vsock-protocol.ts +437 -0
  192. package/ts/wire-schema.ts +3 -3
  193. package/deno.json +0 -56
  194. package/deno.lock +0 -1495
  195. package/dist_npm/mod.d.ts +0 -967
  196. package/dist_npm/mod.js +0 -10058
  197. package/mod.ts +0 -8
  198. package/musl-copyright.md +0 -81
  199. package/third-party-licenses.md +0 -187
  200. package/ts/oci-executor.ts +0 -3137
@@ -0,0 +1,2411 @@
1
+ use crate::oci_tar::{
2
+ normalize_tar_path, read_tar_entries, write_tar_entry, write_tar_trailer, TarEntry,
3
+ TarEntryKind,
4
+ };
5
+ use crate::{measure_tree, Error};
6
+ use serde::{Deserialize, Serialize};
7
+ use std::collections::BTreeMap;
8
+ use std::ffi::{CStr, CString, OsStr};
9
+ use std::fs::{self, File, OpenOptions};
10
+ use std::io::{self, Read, Write};
11
+ use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
12
+ use std::os::unix::ffi::OsStrExt;
13
+ use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
14
+ use std::os::unix::net::UnixListener;
15
+ use std::path::{Component, Path, PathBuf};
16
+ use std::time::{Duration, Instant};
17
+
18
+ pub const VSOCK_PORT: u32 = 1024;
19
+ const AF_VSOCK: libc::c_int = 40;
20
+ const VMADDR_CID_ANY: u32 = 0xFFFF_FFFF;
21
+
22
+ pub const FRAME_JSON_REQ: u8 = 0x01;
23
+ pub const FRAME_JSON_RES: u8 = 0x02;
24
+ pub const FRAME_DATA: u8 = 0x03;
25
+ pub const FRAME_DATA_EOF: u8 = 0x04;
26
+ pub const FRAME_STDOUT: u8 = 0x05;
27
+ pub const FRAME_STDERR: u8 = 0x06;
28
+ pub const FRAME_CANCEL: u8 = 0x07;
29
+
30
+ const MAXIMUM_FRAME_BYTES: usize = 4 * 1024 * 1024;
31
+ const STREAM_CHUNK_BYTES: usize = 32 * 1024;
32
+ const MAXIMUM_STEP_OUTPUT_POLL_MS: libc::c_int = 50;
33
+
34
+ #[repr(C)]
35
+ struct SockAddrVm {
36
+ svm_family: libc::sa_family_t,
37
+ svm_reserved1: u16,
38
+ svm_port: u32,
39
+ svm_cid: u32,
40
+ svm_zero: [u8; 4],
41
+ }
42
+
43
+ #[derive(Deserialize)]
44
+ #[serde(rename_all = "camelCase")]
45
+ struct BuildBaseImage {
46
+ name: String,
47
+ image: String,
48
+ }
49
+
50
+ #[derive(Deserialize)]
51
+ #[serde(rename_all = "camelCase")]
52
+ struct BuildRegistryGrant {
53
+ registry: String,
54
+ username: String,
55
+ secret: String,
56
+ }
57
+
58
+ #[derive(Deserialize)]
59
+ #[serde(tag = "op", rename_all = "snake_case")]
60
+ #[allow(clippy::large_enum_variant)]
61
+ enum GuestRequest {
62
+ Hello,
63
+ PrepareWorkspace {
64
+ #[serde(rename = "workspaceSizeBytes")]
65
+ workspace_size_bytes: u64,
66
+ #[serde(rename = "maximumWorkspaceEntries")]
67
+ maximum_workspace_entries: u64,
68
+ uid: u32,
69
+ gid: u32,
70
+ #[serde(default)]
71
+ mode: Option<String>,
72
+ #[serde(default, rename = "npmrcContent")]
73
+ npmrc_content: Option<String>,
74
+ },
75
+ ImportTar {
76
+ #[serde(rename = "maximumBytes")]
77
+ maximum_bytes: u64,
78
+ #[serde(rename = "maximumEntries")]
79
+ maximum_entries: u64,
80
+ uid: u32,
81
+ gid: u32,
82
+ },
83
+ RunStep {
84
+ command: Vec<String>,
85
+ env: BTreeMap<String, String>,
86
+ #[serde(rename = "workingDirectory")]
87
+ working_directory: String,
88
+ uid: u32,
89
+ gid: u32,
90
+ #[serde(default, rename = "rootMode")]
91
+ root_mode: bool,
92
+ #[serde(rename = "timeoutMs")]
93
+ timeout_ms: u64,
94
+ #[serde(rename = "memoryBytes")]
95
+ memory_bytes: u64,
96
+ cpus: f64,
97
+ pids: u64,
98
+ #[serde(rename = "sharedMemoryBytes")]
99
+ shared_memory_bytes: u64,
100
+ #[serde(rename = "temporarySizeBytes")]
101
+ temporary_size_bytes: u64,
102
+ #[serde(rename = "maximumWorkspaceBytes")]
103
+ maximum_workspace_bytes: u64,
104
+ #[serde(rename = "maximumWorkspaceEntries")]
105
+ maximum_workspace_entries: u64,
106
+ },
107
+ RunImageBuild {
108
+ context: String,
109
+ dockerfile: String,
110
+ #[serde(default)]
111
+ target: Option<String>,
112
+ platform: String,
113
+ #[serde(default, rename = "buildArgs")]
114
+ build_args: BTreeMap<String, String>,
115
+ #[serde(default)]
116
+ secrets: BTreeMap<String, String>,
117
+ #[serde(default)]
118
+ labels: BTreeMap<String, String>,
119
+ #[serde(default, rename = "baseImages")]
120
+ base_images: Vec<BuildBaseImage>,
121
+ #[serde(default, rename = "npmrcContent")]
122
+ npmrc_content: Option<String>,
123
+ #[serde(rename = "pushRegistry")]
124
+ push_registry: String,
125
+ #[serde(rename = "pushRepository")]
126
+ push_repository: String,
127
+ #[serde(default)]
128
+ grants: Vec<BuildRegistryGrant>,
129
+ #[serde(rename = "timeoutMs")]
130
+ timeout_ms: u64,
131
+ #[serde(default, rename = "importCacheDir")]
132
+ import_cache_dir: Option<String>,
133
+ #[serde(default, rename = "exportCacheDir")]
134
+ export_cache_dir: Option<String>,
135
+ #[serde(default, rename = "buildctlPath")]
136
+ buildctl_path: Option<String>,
137
+ },
138
+ ExportTar {
139
+ selections: Vec<String>,
140
+ #[serde(rename = "maximumBytes")]
141
+ maximum_bytes: u64,
142
+ #[serde(rename = "maximumEntries")]
143
+ maximum_entries: u64,
144
+ },
145
+ Shutdown,
146
+ }
147
+
148
+ #[derive(Serialize)]
149
+ struct ErrorResponse {
150
+ ok: bool,
151
+ error: String,
152
+ }
153
+
154
+ #[derive(Serialize)]
155
+ #[serde(rename_all = "camelCase")]
156
+ struct HelloResponse {
157
+ ok: bool,
158
+ version: &'static str,
159
+ os: &'static str,
160
+ architecture: &'static str,
161
+ }
162
+
163
+ #[derive(Serialize)]
164
+ #[serde(rename_all = "camelCase")]
165
+ struct SimpleOkResponse {
166
+ ok: bool,
167
+ }
168
+
169
+ #[derive(Serialize)]
170
+ #[serde(rename_all = "camelCase")]
171
+ struct TransferResponse {
172
+ ok: bool,
173
+ bytes: u64,
174
+ entries: u64,
175
+ }
176
+
177
+ #[derive(Serialize)]
178
+ #[serde(rename_all = "camelCase")]
179
+ struct StepResponse {
180
+ ok: bool,
181
+ exit_code: Option<i32>,
182
+ signal: Option<i32>,
183
+ timed_out: bool,
184
+ canceled: bool,
185
+ oom_killed: bool,
186
+ workspace_bytes: u64,
187
+ workspace_entries: u64,
188
+ }
189
+
190
+ #[derive(Serialize)]
191
+ #[serde(rename_all = "camelCase")]
192
+ struct ImageBuildResponse {
193
+ ok: bool,
194
+ exit_code: Option<i32>,
195
+ timed_out: bool,
196
+ canceled: bool,
197
+ manifest_digest: Option<String>,
198
+ media_type: Option<String>,
199
+ size_bytes: Option<u64>,
200
+ cache_exported: bool,
201
+ }
202
+
203
+ struct GuestContext {
204
+ pid1_mode: bool,
205
+ oci_rootfs: PathBuf,
206
+ vm_rootfs: PathBuf,
207
+ workspace_dir: PathBuf,
208
+ npmrc_dir: Option<PathBuf>,
209
+ step_counter: u64,
210
+ }
211
+
212
+ fn read_frame<R: Read>(reader: &mut R) -> io::Result<Option<(u8, Vec<u8>)>> {
213
+ let mut header = [0u8; 5];
214
+ let mut offset = 0;
215
+ while offset < 5 {
216
+ let n = reader.read(&mut header[offset..])?;
217
+ if n == 0 {
218
+ if offset == 0 {
219
+ return Ok(None);
220
+ }
221
+ return Err(io::Error::new(
222
+ io::ErrorKind::UnexpectedEof,
223
+ "truncated frame header",
224
+ ));
225
+ }
226
+ offset += n;
227
+ }
228
+ let len = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize;
229
+ let kind = header[4];
230
+ if len > MAXIMUM_FRAME_BYTES {
231
+ return Err(io::Error::new(
232
+ io::ErrorKind::InvalidData,
233
+ "frame exceeds maximum allowed size",
234
+ ));
235
+ }
236
+ let mut payload = vec![0u8; len];
237
+ if len > 0 {
238
+ reader.read_exact(&mut payload)?;
239
+ }
240
+ Ok(Some((kind, payload)))
241
+ }
242
+
243
+ fn write_frame<W: Write>(writer: &mut W, kind: u8, payload: &[u8]) -> io::Result<()> {
244
+ let mut header = [0u8; 5];
245
+ header[0..4].copy_from_slice(&(payload.len() as u32).to_be_bytes());
246
+ header[4] = kind;
247
+ writer.write_all(&header)?;
248
+ if !payload.is_empty() {
249
+ writer.write_all(payload)?;
250
+ }
251
+ writer.flush()
252
+ }
253
+
254
+ fn send_json<W: Write, T: Serialize>(writer: &mut W, value: &T) -> io::Result<()> {
255
+ let bytes = serde_json::to_vec(value)
256
+ .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
257
+ write_frame(writer, FRAME_JSON_RES, &bytes)
258
+ }
259
+
260
+ fn send_error<W: Write>(writer: &mut W, message: impl Into<String>) -> io::Result<()> {
261
+ send_json(
262
+ writer,
263
+ &ErrorResponse {
264
+ ok: false,
265
+ error: message.into(),
266
+ },
267
+ )
268
+ }
269
+
270
+ fn read_data_stream<R: Read>(reader: &mut R, max_bytes: u64) -> Result<Vec<u8>, String> {
271
+ let mut out = Vec::new();
272
+ loop {
273
+ let Some((kind, payload)) = read_frame(reader).map_err(|e| e.to_string())? else {
274
+ return Err("stream closed before EOF frame".into());
275
+ };
276
+ match kind {
277
+ FRAME_DATA => {
278
+ if (out.len() as u64).saturating_add(payload.len() as u64) > max_bytes {
279
+ return Err("streamed data exceeds maximum allowed size".into());
280
+ }
281
+ out.extend_from_slice(&payload);
282
+ }
283
+ FRAME_DATA_EOF => return Ok(out),
284
+ _ => return Err("unexpected frame type during data stream".into()),
285
+ }
286
+ }
287
+ }
288
+
289
+ fn handle_connection<S: Read + Write + AsRawFd>(
290
+ stream: &mut S,
291
+ ctx: &mut GuestContext,
292
+ ) -> Result<bool, Error> {
293
+ loop {
294
+ let frame = match read_frame(stream) {
295
+ Ok(Some(f)) => f,
296
+ Ok(None) => return Ok(false),
297
+ Err(_) => return Ok(false),
298
+ };
299
+ let (kind, payload) = frame;
300
+ if kind != FRAME_JSON_REQ {
301
+ let _ = send_error(stream, "expected JSON request frame");
302
+ return Ok(false);
303
+ }
304
+ let req: GuestRequest = match serde_json::from_slice(&payload) {
305
+ Ok(r) => r,
306
+ Err(e) => {
307
+ let _ = send_error(stream, format!("invalid request JSON: {e}"));
308
+ continue;
309
+ }
310
+ };
311
+
312
+ match req {
313
+ GuestRequest::Hello => {
314
+ let _ = send_json(
315
+ stream,
316
+ &HelloResponse {
317
+ ok: true,
318
+ version: env!("CARGO_PKG_VERSION"),
319
+ os: std::env::consts::OS,
320
+ architecture: std::env::consts::ARCH,
321
+ },
322
+ );
323
+ }
324
+ GuestRequest::PrepareWorkspace {
325
+ workspace_size_bytes,
326
+ maximum_workspace_entries,
327
+ uid,
328
+ gid,
329
+ mode,
330
+ npmrc_content,
331
+ } => match prepare_workspace(
332
+ ctx,
333
+ workspace_size_bytes,
334
+ maximum_workspace_entries,
335
+ uid,
336
+ gid,
337
+ mode.as_deref(),
338
+ npmrc_content.as_deref(),
339
+ ) {
340
+ Ok(()) => {
341
+ let _ = send_json(stream, &SimpleOkResponse { ok: true });
342
+ }
343
+ Err(msg) => {
344
+ let _ = send_error(stream, msg);
345
+ }
346
+ },
347
+ GuestRequest::ImportTar {
348
+ maximum_bytes,
349
+ maximum_entries,
350
+ uid,
351
+ gid,
352
+ } => {
353
+ let max_stream = maximum_bytes
354
+ .saturating_add(maximum_entries.saturating_mul(1024))
355
+ .saturating_add(1024 * 1024);
356
+ match read_data_stream(stream, max_stream)
357
+ .and_then(|tar_bytes| {
358
+ extract_tar_to_workspace(
359
+ &ctx.workspace_dir,
360
+ &tar_bytes,
361
+ maximum_bytes,
362
+ maximum_entries,
363
+ uid,
364
+ gid,
365
+ ctx.pid1_mode,
366
+ )
367
+ }) {
368
+ Ok((bytes, entries)) => {
369
+ let _ = send_json(
370
+ stream,
371
+ &TransferResponse {
372
+ ok: true,
373
+ bytes,
374
+ entries,
375
+ },
376
+ );
377
+ }
378
+ Err(msg) => {
379
+ let _ = send_error(stream, msg);
380
+ }
381
+ }
382
+ }
383
+ GuestRequest::RunStep {
384
+ command,
385
+ env,
386
+ working_directory,
387
+ uid,
388
+ gid,
389
+ root_mode,
390
+ timeout_ms,
391
+ memory_bytes,
392
+ cpus,
393
+ pids,
394
+ shared_memory_bytes,
395
+ temporary_size_bytes,
396
+ maximum_workspace_bytes,
397
+ maximum_workspace_entries,
398
+ } => {
399
+ ctx.step_counter += 1;
400
+ match execute_step(
401
+ stream,
402
+ ctx,
403
+ StepSpec {
404
+ seq: ctx.step_counter,
405
+ command,
406
+ env,
407
+ working_directory,
408
+ uid,
409
+ gid,
410
+ root_mode,
411
+ timeout_ms,
412
+ memory_bytes,
413
+ cpus,
414
+ pids,
415
+ shared_memory_bytes,
416
+ temporary_size_bytes,
417
+ maximum_workspace_bytes,
418
+ maximum_workspace_entries,
419
+ },
420
+ ) {
421
+ Ok(res) => {
422
+ let _ = send_json(stream, &res);
423
+ }
424
+ Err(msg) => {
425
+ let _ = send_error(stream, msg);
426
+ }
427
+ }
428
+ }
429
+ GuestRequest::RunImageBuild {
430
+ context,
431
+ dockerfile,
432
+ target,
433
+ platform,
434
+ build_args,
435
+ secrets,
436
+ labels,
437
+ base_images,
438
+ npmrc_content,
439
+ push_registry,
440
+ push_repository,
441
+ grants,
442
+ timeout_ms,
443
+ import_cache_dir,
444
+ export_cache_dir,
445
+ buildctl_path,
446
+ } => {
447
+ match execute_image_build(
448
+ stream,
449
+ ctx,
450
+ ImageBuildSpec {
451
+ context,
452
+ dockerfile,
453
+ target,
454
+ platform,
455
+ build_args,
456
+ secrets,
457
+ labels,
458
+ base_images,
459
+ npmrc_content,
460
+ push_registry,
461
+ push_repository,
462
+ grants,
463
+ timeout_ms,
464
+ import_cache_dir,
465
+ export_cache_dir,
466
+ buildctl_path,
467
+ },
468
+ ) {
469
+ Ok(res) => {
470
+ let _ = send_json(stream, &res);
471
+ }
472
+ Err(msg) => {
473
+ let _ = send_error(stream, msg);
474
+ }
475
+ }
476
+ }
477
+ GuestRequest::ExportTar {
478
+ selections,
479
+ maximum_bytes,
480
+ maximum_entries,
481
+ } => match build_export_tar(
482
+ &ctx.workspace_dir,
483
+ &selections,
484
+ maximum_bytes,
485
+ maximum_entries,
486
+ ) {
487
+ Ok((tar_bytes, bytes, entries)) => {
488
+ let mut failed = false;
489
+ for chunk in tar_bytes.chunks(STREAM_CHUNK_BYTES) {
490
+ if write_frame(stream, FRAME_DATA, chunk).is_err() {
491
+ failed = true;
492
+ break;
493
+ }
494
+ }
495
+ if !failed && write_frame(stream, FRAME_DATA_EOF, &[]).is_ok() {
496
+ let _ = send_json(
497
+ stream,
498
+ &TransferResponse {
499
+ ok: true,
500
+ bytes,
501
+ entries,
502
+ },
503
+ );
504
+ }
505
+ }
506
+ Err(msg) => {
507
+ let _ = send_error(stream, msg);
508
+ }
509
+ },
510
+ GuestRequest::Shutdown => {
511
+ let _ = send_json(stream, &SimpleOkResponse { ok: true });
512
+ return Ok(true);
513
+ }
514
+ }
515
+ }
516
+ }
517
+
518
+ fn prepare_workspace(
519
+ ctx: &mut GuestContext,
520
+ workspace_size_bytes: u64,
521
+ maximum_workspace_entries: u64,
522
+ uid: u32,
523
+ gid: u32,
524
+ mode: Option<&str>,
525
+ npmrc_content: Option<&str>,
526
+ ) -> Result<(), String> {
527
+ fs::create_dir_all(&ctx.workspace_dir)
528
+ .map_err(|e| format!("unable to create workspace directory: {e}"))?;
529
+ if ctx.pid1_mode {
530
+ // Ensure clean mount before remounting bounded tmpfs.
531
+ let target = CString::new(ctx.workspace_dir.as_os_str().as_bytes())
532
+ .map_err(|_| "invalid workspace path".to_owned())?;
533
+ unsafe {
534
+ libc::umount2(target.as_ptr(), libc::MNT_DETACH);
535
+ }
536
+ let source = CString::new("tmpfs").unwrap();
537
+ let fstype = CString::new("tmpfs").unwrap();
538
+ let inode_limit = maximum_workspace_entries.saturating_add(16);
539
+ let opts = CString::new(format!(
540
+ "size={workspace_size_bytes},nr_inodes={inode_limit},mode=0755,uid={uid},gid={gid}"
541
+ ))
542
+ .map_err(|_| "invalid tmpfs options".to_owned())?;
543
+ let rc = unsafe {
544
+ libc::mount(
545
+ source.as_ptr(),
546
+ target.as_ptr(),
547
+ fstype.as_ptr(),
548
+ libc::MS_NODEV | libc::MS_NOSUID,
549
+ opts.as_ptr().cast(),
550
+ )
551
+ };
552
+ if rc != 0 {
553
+ return Err(format!(
554
+ "unable to mount bounded workspace tmpfs: {}",
555
+ io::Error::last_os_error()
556
+ ));
557
+ }
558
+ if mode == Some("vm") {
559
+ // Mount a writable overlayfs over read-only /oci-rootfs so `vm` steps persist files
560
+ // across steps without mutating /dev/vda.
561
+ let _ = fs::create_dir_all("/run/vm-overlay/upper");
562
+ let _ = fs::create_dir_all("/run/vm-overlay/work");
563
+ let _ = fs::create_dir_all(&ctx.vm_rootfs);
564
+ let ovl = CString::new("overlay").unwrap();
565
+ let dst = CString::new(ctx.vm_rootfs.as_os_str().as_bytes()).unwrap();
566
+ let ovl_opts = CString::new(
567
+ "lowerdir=/oci-rootfs,upperdir=/run/vm-overlay/upper,workdir=/run/vm-overlay/work",
568
+ )
569
+ .unwrap();
570
+ let rc = unsafe {
571
+ libc::mount(
572
+ ovl.as_ptr(),
573
+ dst.as_ptr(),
574
+ ovl.as_ptr(),
575
+ 0,
576
+ ovl_opts.as_ptr().cast(),
577
+ )
578
+ };
579
+ if rc != 0 {
580
+ return Err(format!(
581
+ "unable to mount writable vm overlay rootfs: {}",
582
+ io::Error::last_os_error()
583
+ ));
584
+ }
585
+ }
586
+ } else {
587
+ // In unprivileged test mode, clear any existing workspace contents.
588
+ if let Ok(read_dir) = fs::read_dir(&ctx.workspace_dir) {
589
+ for entry in read_dir.flatten() {
590
+ let path = entry.path();
591
+ if path.is_dir() && !path.is_symlink() {
592
+ let _ = fs::remove_dir_all(&path);
593
+ } else {
594
+ let _ = fs::remove_file(&path);
595
+ }
596
+ }
597
+ }
598
+ }
599
+
600
+ // Materialize read-only npmrc outside /workspace when npmRead grants are present.
601
+ if let Some(content) = npmrc_content {
602
+ let npmrc_dir = if ctx.pid1_mode {
603
+ PathBuf::from("/run/shipzone-npmrc")
604
+ } else {
605
+ ctx.workspace_dir
606
+ .parent()
607
+ .unwrap_or_else(|| Path::new("/tmp"))
608
+ .join(".shipzone-npmrc")
609
+ };
610
+ fs::create_dir_all(&npmrc_dir)
611
+ .map_err(|e| format!("unable to create npmrc directory: {e}"))?;
612
+ if ctx.pid1_mode {
613
+ let t = CString::new(npmrc_dir.as_os_str().as_bytes()).unwrap();
614
+ let tmpfs = CString::new("tmpfs").unwrap();
615
+ let opts = CString::new("size=65536,mode=0755").unwrap();
616
+ unsafe {
617
+ libc::umount2(t.as_ptr(), libc::MNT_DETACH);
618
+ libc::mount(
619
+ tmpfs.as_ptr(),
620
+ t.as_ptr(),
621
+ tmpfs.as_ptr(),
622
+ libc::MS_NODEV | libc::MS_NOSUID | libc::MS_NOEXEC,
623
+ opts.as_ptr().cast(),
624
+ );
625
+ }
626
+ }
627
+ let npmrc_file = npmrc_dir.join("npmrc");
628
+ let _ = fs::set_permissions(&npmrc_file, fs::Permissions::from_mode(0o600));
629
+ let mut f = OpenOptions::new()
630
+ .write(true)
631
+ .create(true)
632
+ .truncate(true)
633
+ .mode(0o444)
634
+ .open(&npmrc_file)
635
+ .map_err(|e| format!("unable to write npmrc file: {e}"))?;
636
+ f.write_all(content.as_bytes())
637
+ .map_err(|e| format!("unable to write npmrc content: {e}"))?;
638
+ let _ = fs::set_permissions(&npmrc_file, fs::Permissions::from_mode(0o444));
639
+ if ctx.pid1_mode {
640
+ let t = CString::new(npmrc_dir.as_os_str().as_bytes()).unwrap();
641
+ unsafe {
642
+ libc::mount(
643
+ std::ptr::null(),
644
+ t.as_ptr(),
645
+ std::ptr::null(),
646
+ libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY,
647
+ std::ptr::null(),
648
+ );
649
+ }
650
+ }
651
+ ctx.npmrc_dir = Some(npmrc_dir);
652
+ } else {
653
+ ctx.npmrc_dir = None;
654
+ }
655
+ Ok(())
656
+ }
657
+
658
+ fn extract_tar_to_workspace(
659
+ workspace: &Path,
660
+ tar_bytes: &[u8],
661
+ maximum_bytes: u64,
662
+ maximum_entries: u64,
663
+ uid: u32,
664
+ gid: u32,
665
+ apply_chown: bool,
666
+ ) -> Result<(u64, u64), String> {
667
+ let mut cursor = io::Cursor::new(tar_bytes);
668
+ let entries = read_tar_entries(&mut cursor, maximum_bytes, maximum_entries as usize)
669
+ .map_err(|e| e.to_string())?;
670
+ let mut logical_bytes: u64 = 0;
671
+ let mut entry_count: u64 = 0;
672
+
673
+ for entry in entries {
674
+ let parts = normalize_tar_path(&entry.path).map_err(|e| e.to_string())?;
675
+ if parts.is_empty() {
676
+ continue;
677
+ }
678
+ let mut dest = workspace.to_path_buf();
679
+ for part in &parts {
680
+ dest.push(part);
681
+ }
682
+ if let Some(parent) = dest.parent() {
683
+ fs::create_dir_all(parent).map_err(|e| format!("unable to create parent dir: {e}"))?;
684
+ }
685
+ entry_count = entry_count
686
+ .checked_add(1)
687
+ .ok_or_else(|| "workspace entry count overflow".to_owned())?;
688
+ if entry_count > maximum_entries {
689
+ return Err("workspace entry count exceeds limit".into());
690
+ }
691
+ match entry.kind {
692
+ TarEntryKind::Directory => {
693
+ fs::create_dir_all(&dest).map_err(|e| format!("unable to create dir: {e}"))?;
694
+ let _ = fs::set_permissions(&dest, fs::Permissions::from_mode(entry.mode & 0o777));
695
+ }
696
+ TarEntryKind::File(data) => {
697
+ logical_bytes = logical_bytes
698
+ .checked_add(data.len() as u64)
699
+ .ok_or_else(|| "workspace byte count overflow".to_owned())?;
700
+ if logical_bytes > maximum_bytes {
701
+ return Err("workspace bytes exceed limit".into());
702
+ }
703
+ let mut file = OpenOptions::new()
704
+ .write(true)
705
+ .create(true)
706
+ .truncate(true)
707
+ .mode(entry.mode & 0o777)
708
+ .open(&dest)
709
+ .map_err(|e| format!("unable to write workspace file: {e}"))?;
710
+ file.write_all(&data)
711
+ .map_err(|e| format!("unable to write file contents: {e}"))?;
712
+ }
713
+ TarEntryKind::Symlink(target) => {
714
+ let target_os = OsStr::from_bytes(&target);
715
+ if target_os.as_bytes().starts_with(b"/") {
716
+ return Err("absolute symlinks are not allowed in workspace".into());
717
+ }
718
+ let _ = fs::remove_file(&dest);
719
+ std::os::unix::fs::symlink(target_os, &dest)
720
+ .map_err(|e| format!("unable to create symlink: {e}"))?;
721
+ }
722
+ TarEntryKind::Hardlink(_) => {
723
+ return Err("hardlinks are not allowed in workspace transfer".into());
724
+ }
725
+ }
726
+ if apply_chown {
727
+ let cpath = CString::new(dest.as_os_str().as_bytes())
728
+ .map_err(|_| "invalid workspace entry path".to_owned())?;
729
+ unsafe {
730
+ libc::lchown(cpath.as_ptr(), uid, gid);
731
+ }
732
+ }
733
+ }
734
+
735
+ Ok((logical_bytes, entry_count))
736
+ }
737
+
738
+ fn validate_relative_selection(selection: &str) -> Result<PathBuf, String> {
739
+ if selection.is_empty() || selection.starts_with('/') || selection.contains('\0') {
740
+ return Err("selection path must be relative".into());
741
+ }
742
+ let path = Path::new(selection);
743
+ let mut normalized = PathBuf::new();
744
+ for component in path.components() {
745
+ match component {
746
+ Component::Normal(part) => normalized.push(part),
747
+ Component::CurDir => {}
748
+ _ => return Err("selection path cannot traverse parent directories".into()),
749
+ }
750
+ }
751
+ if normalized.as_os_str().is_empty() {
752
+ return Err("selection path cannot be empty".into());
753
+ }
754
+ Ok(normalized)
755
+ }
756
+
757
+ fn symlink_stays_within_workspace(
758
+ parent_rel: &Path,
759
+ target: &Path,
760
+ ) -> Result<(), String> {
761
+ if target.is_absolute() {
762
+ return Err("symlink target escapes its allowed root".into());
763
+ }
764
+ let mut depth: usize = parent_rel.components().count();
765
+ for component in target.components() {
766
+ match component {
767
+ Component::CurDir => {}
768
+ Component::Normal(_) => depth += 1,
769
+ Component::ParentDir => {
770
+ if depth == 0 {
771
+ return Err("symlink target escapes its allowed root".into());
772
+ }
773
+ depth -= 1;
774
+ }
775
+ _ => return Err("symlink target escapes its allowed root".into()),
776
+ }
777
+ }
778
+ Ok(())
779
+ }
780
+
781
+ fn build_export_tar(
782
+ workspace: &Path,
783
+ selections: &[String],
784
+ maximum_bytes: u64,
785
+ maximum_entries: u64,
786
+ ) -> Result<(Vec<u8>, u64, u64), String> {
787
+ let root_meta =
788
+ fs::symlink_metadata(workspace).map_err(|e| format!("unable to stat workspace: {e}"))?;
789
+ let root_dev = root_meta.dev();
790
+
791
+ let mut out = Vec::new();
792
+ let mut bytes_total: u64 = 0;
793
+ let mut entries_total: u64 = 0;
794
+ let mut emitted_paths: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
795
+
796
+ #[allow(clippy::too_many_arguments)]
797
+ fn collect(
798
+ workspace: &Path,
799
+ rel: &Path,
800
+ root_dev: u64,
801
+ maximum_bytes: u64,
802
+ maximum_entries: u64,
803
+ out: &mut Vec<u8>,
804
+ bytes_total: &mut u64,
805
+ entries_total: &mut u64,
806
+ emitted: &mut std::collections::BTreeSet<String>,
807
+ depth: usize,
808
+ ) -> Result<(), String> {
809
+ if depth > 256 {
810
+ return Err("workspace traversal depth exceeded".into());
811
+ }
812
+ let rel_str = rel
813
+ .to_str()
814
+ .ok_or_else(|| "non-UTF-8 path in workspace export".to_owned())?
815
+ .to_owned();
816
+ if !emitted.insert(rel_str.clone()) {
817
+ return Ok(());
818
+ }
819
+ let abs = workspace.join(rel);
820
+ let meta = match fs::symlink_metadata(&abs) {
821
+ Ok(m) => m,
822
+ Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
823
+ Err(e) => return Err(format!("unable to stat export entry: {e}")),
824
+ };
825
+ if meta.dev() != root_dev {
826
+ return Err("workspace export cannot cross filesystem boundaries".into());
827
+ }
828
+ *entries_total = entries_total
829
+ .checked_add(1)
830
+ .ok_or_else(|| "export entry count overflow".to_owned())?;
831
+ if *entries_total > maximum_entries {
832
+ return Err("export entry count exceeds limit".into());
833
+ }
834
+ let ft = meta.file_type();
835
+ let mode = meta.mode() & 0o777;
836
+ let mtime = meta.mtime().max(0) as u64;
837
+ if ft.is_symlink() {
838
+ let target =
839
+ fs::read_link(&abs).map_err(|e| format!("unable to read symlink: {e}"))?;
840
+ let parent_rel = rel.parent().unwrap_or_else(|| Path::new(""));
841
+ symlink_stays_within_workspace(parent_rel, &target)?;
842
+ write_tar_entry(
843
+ out,
844
+ &TarEntry {
845
+ path: rel_str,
846
+ mode: 0o777,
847
+ uid: 0,
848
+ gid: 0,
849
+ mtime,
850
+ kind: TarEntryKind::Symlink(target.as_os_str().as_bytes().to_vec()),
851
+ },
852
+ )
853
+ .map_err(|e| e.to_string())?;
854
+ } else if ft.is_file() {
855
+ if meta.nlink() > 1 {
856
+ return Err("hardlinked files are not allowed in workspace export".into());
857
+ }
858
+ *bytes_total = bytes_total
859
+ .checked_add(meta.len())
860
+ .ok_or_else(|| "export byte count overflow".to_owned())?;
861
+ if *bytes_total > maximum_bytes {
862
+ return Err("export bytes exceed limit".into());
863
+ }
864
+ let data = fs::read(&abs).map_err(|e| format!("unable to read export file: {e}"))?;
865
+ write_tar_entry(
866
+ out,
867
+ &TarEntry {
868
+ path: rel_str,
869
+ mode,
870
+ uid: 0,
871
+ gid: 0,
872
+ mtime,
873
+ kind: TarEntryKind::File(data),
874
+ },
875
+ )
876
+ .map_err(|e| e.to_string())?;
877
+ } else if ft.is_dir() {
878
+ write_tar_entry(
879
+ out,
880
+ &TarEntry {
881
+ path: rel_str,
882
+ mode,
883
+ uid: 0,
884
+ gid: 0,
885
+ mtime,
886
+ kind: TarEntryKind::Directory,
887
+ },
888
+ )
889
+ .map_err(|e| e.to_string())?;
890
+ let mut children: Vec<PathBuf> = fs::read_dir(&abs)
891
+ .map_err(|e| format!("unable to read directory: {e}"))?
892
+ .filter_map(|e| e.ok().map(|entry| rel.join(entry.file_name())))
893
+ .collect();
894
+ children.sort();
895
+ for child_rel in children {
896
+ collect(
897
+ workspace,
898
+ &child_rel,
899
+ root_dev,
900
+ maximum_bytes,
901
+ maximum_entries,
902
+ out,
903
+ bytes_total,
904
+ entries_total,
905
+ emitted,
906
+ depth + 1,
907
+ )?;
908
+ }
909
+ } else {
910
+ return Err("special filesystem entries are not allowed".into());
911
+ }
912
+ Ok(())
913
+ }
914
+
915
+ for sel in selections {
916
+ let rel = validate_relative_selection(sel)?;
917
+ // Check no intermediate ancestor is a symlink before descending.
918
+ let mut cursor = workspace.to_path_buf();
919
+ if let Some(parent) = rel.parent() {
920
+ for comp in parent.components() {
921
+ cursor.push(comp);
922
+ if let Ok(m) = fs::symlink_metadata(&cursor)
923
+ && m.file_type().is_symlink()
924
+ {
925
+ return Err("selection traverses a symbolic link".into());
926
+ }
927
+ }
928
+ }
929
+ collect(
930
+ workspace,
931
+ &rel,
932
+ root_dev,
933
+ maximum_bytes,
934
+ maximum_entries,
935
+ &mut out,
936
+ &mut bytes_total,
937
+ &mut entries_total,
938
+ &mut emitted_paths,
939
+ 0,
940
+ )?;
941
+ }
942
+
943
+ write_tar_trailer(&mut out).map_err(|e| e.to_string())?;
944
+ Ok((out, bytes_total, entries_total))
945
+ }
946
+
947
+ struct StepSpec {
948
+ seq: u64,
949
+ command: Vec<String>,
950
+ env: BTreeMap<String, String>,
951
+ working_directory: String,
952
+ uid: u32,
953
+ gid: u32,
954
+ root_mode: bool,
955
+ timeout_ms: u64,
956
+ memory_bytes: u64,
957
+ cpus: f64,
958
+ pids: u64,
959
+ shared_memory_bytes: u64,
960
+ temporary_size_bytes: u64,
961
+ maximum_workspace_bytes: u64,
962
+ maximum_workspace_entries: u64,
963
+ }
964
+
965
+ fn make_pipe() -> Result<(OwnedFd, OwnedFd), String> {
966
+ let mut fds = [0 as libc::c_int; 2];
967
+ let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) };
968
+ if rc != 0 {
969
+ return Err(format!("pipe2 failed: {}", io::Error::last_os_error()));
970
+ }
971
+ unsafe { Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) }
972
+ }
973
+
974
+ fn set_nonblocking(fd: RawFd) {
975
+ unsafe {
976
+ let flags = libc::fcntl(fd, libc::F_GETFL);
977
+ if flags >= 0 {
978
+ libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
979
+ }
980
+ }
981
+ }
982
+
983
+ fn create_step_cgroup(seq: u64, memory_bytes: u64, cpus: f64, pids: u64) -> Option<PathBuf> {
984
+ let root = Path::new("/sys/fs/cgroup");
985
+ if !root.join("cgroup.controllers").exists() {
986
+ return None;
987
+ }
988
+ let _ = fs::write(root.join("cgroup.subtree_control"), "+memory +cpu +pids");
989
+ let leaf = root.join(format!("step-{seq}"));
990
+ if fs::create_dir(&leaf).is_err() {
991
+ return None;
992
+ }
993
+ let _ = fs::write(leaf.join("memory.max"), format!("{memory_bytes}\n"));
994
+ let _ = fs::write(leaf.join("memory.swap.max"), "0\n");
995
+ let quota_us = ((cpus * 100_000.0).round() as u64).max(1_000);
996
+ let _ = fs::write(leaf.join("cpu.max"), format!("{quota_us} 100000\n"));
997
+ let _ = fs::write(leaf.join("pids.max"), format!("{pids}\n"));
998
+ Some(leaf)
999
+ }
1000
+
1001
+ fn kill_and_cleanup_cgroup(leaf: &Path) -> bool {
1002
+ let _ = fs::write(leaf.join("cgroup.kill"), "1\n");
1003
+ let oom_killed = fs::read_to_string(leaf.join("memory.events"))
1004
+ .ok()
1005
+ .and_then(|text| {
1006
+ text.lines().find_map(|line| {
1007
+ let rest = line.strip_prefix("oom_kill ")?;
1008
+ rest.trim().parse::<u64>().ok().map(|n| n > 0)
1009
+ })
1010
+ })
1011
+ .unwrap_or(false);
1012
+ for _ in 0..20 {
1013
+ if fs::remove_dir(leaf).is_ok() {
1014
+ break;
1015
+ }
1016
+ std::thread::sleep(Duration::from_millis(25));
1017
+ }
1018
+ oom_killed
1019
+ }
1020
+
1021
+ fn resolve_executable(program: &str, path_env: Option<&str>) -> CString {
1022
+ if program.contains('/') {
1023
+ return CString::new(program).unwrap_or_else(|_| CString::new("/bin/false").unwrap());
1024
+ }
1025
+ let search = path_env.unwrap_or("/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
1026
+ for dir in search.split(':') {
1027
+ if dir.is_empty() {
1028
+ continue;
1029
+ }
1030
+ let candidate = Path::new(dir).join(program);
1031
+ if let Ok(meta) = fs::metadata(&candidate)
1032
+ && meta.is_file()
1033
+ && (meta.mode() & 0o111) != 0
1034
+ && let Ok(c) = CString::new(candidate.as_os_str().as_bytes())
1035
+ {
1036
+ return c;
1037
+ }
1038
+ }
1039
+ CString::new(program).unwrap_or_else(|_| CString::new("/bin/false").unwrap())
1040
+ }
1041
+
1042
+ #[cfg(target_os = "linux")]
1043
+ unsafe fn bring_up_loopback() {
1044
+ let sock = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) };
1045
+ if sock < 0 {
1046
+ return;
1047
+ }
1048
+ let mut ifr: libc::ifreq = unsafe { std::mem::zeroed() };
1049
+ ifr.ifr_name[0] = b'l' as libc::c_char;
1050
+ ifr.ifr_name[1] = b'o' as libc::c_char;
1051
+ if unsafe { libc::ioctl(sock, libc::SIOCGIFFLAGS as _, &mut ifr) } == 0 {
1052
+ unsafe {
1053
+ ifr.ifr_ifru.ifru_flags |= (libc::IFF_UP | libc::IFF_RUNNING) as libc::c_short;
1054
+ libc::ioctl(sock, libc::SIOCSIFFLAGS as _, &mut ifr);
1055
+ }
1056
+ }
1057
+ unsafe {
1058
+ libc::close(sock);
1059
+ }
1060
+ }
1061
+
1062
+ #[cfg(target_os = "linux")]
1063
+ unsafe fn drop_all_capabilities() {
1064
+ const PR_CAPBSET_DROP: libc::c_int = 24;
1065
+ const PR_CAP_AMBIENT: libc::c_int = 47;
1066
+ const PR_CAP_AMBIENT_CLEAR_ALL: libc::c_ulong = 4;
1067
+ const LINUX_CAPABILITY_VERSION_3: u32 = 0x2008_0522;
1068
+
1069
+ #[repr(C)]
1070
+ struct CapHeader {
1071
+ version: u32,
1072
+ pid: i32,
1073
+ }
1074
+ #[repr(C)]
1075
+ struct CapData {
1076
+ effective: u32,
1077
+ permitted: u32,
1078
+ inheritable: u32,
1079
+ }
1080
+
1081
+ for cap in 0..64 {
1082
+ unsafe {
1083
+ libc::prctl(PR_CAPBSET_DROP, cap, 0, 0, 0);
1084
+ }
1085
+ }
1086
+ unsafe {
1087
+ libc::prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0);
1088
+ }
1089
+ let header = CapHeader {
1090
+ version: LINUX_CAPABILITY_VERSION_3,
1091
+ pid: 0,
1092
+ };
1093
+ let data = [
1094
+ CapData {
1095
+ effective: 0,
1096
+ permitted: 0,
1097
+ inheritable: 0,
1098
+ },
1099
+ CapData {
1100
+ effective: 0,
1101
+ permitted: 0,
1102
+ inheritable: 0,
1103
+ },
1104
+ ];
1105
+ unsafe {
1106
+ libc::syscall(libc::SYS_capset, &header, data.as_ptr());
1107
+ }
1108
+ }
1109
+
1110
+ #[cfg(target_os = "linux")]
1111
+ unsafe fn setup_pid1_step_sandbox(
1112
+ target_rootfs: &Path,
1113
+ workspace_dir: &Path,
1114
+ npmrc_dir: Option<&Path>,
1115
+ spec: &StepSpec,
1116
+ ) -> Result<(), &'static str> {
1117
+ let oci_rootfs = target_rootfs;
1118
+ // Isolate mount, IPC, UTS, and network namespaces (loopback only).
1119
+ if unsafe {
1120
+ libc::unshare(
1121
+ libc::CLONE_NEWNS | libc::CLONE_NEWIPC | libc::CLONE_NEWUTS | libc::CLONE_NEWNET,
1122
+ )
1123
+ } != 0
1124
+ {
1125
+ return Err("unshare failed");
1126
+ }
1127
+ unsafe {
1128
+ bring_up_loopback();
1129
+ }
1130
+
1131
+ // Make all mounts private so our changes never leak back.
1132
+ let slash = CString::new("/").unwrap();
1133
+ let none = CString::new("none").unwrap();
1134
+ if unsafe {
1135
+ libc::mount(
1136
+ none.as_ptr(),
1137
+ slash.as_ptr(),
1138
+ std::ptr::null(),
1139
+ libc::MS_REC | libc::MS_PRIVATE,
1140
+ std::ptr::null(),
1141
+ )
1142
+ } != 0
1143
+ {
1144
+ return Err("mount MS_PRIVATE failed");
1145
+ }
1146
+
1147
+ // Bind-mount oci_rootfs onto itself so it is a mount point for pivot_root.
1148
+ let rootfs_c = CString::new(oci_rootfs.as_os_str().as_bytes()).map_err(|_| "bad rootfs")?;
1149
+ if unsafe {
1150
+ libc::mount(
1151
+ rootfs_c.as_ptr(),
1152
+ rootfs_c.as_ptr(),
1153
+ std::ptr::null(),
1154
+ libc::MS_BIND | libc::MS_REC,
1155
+ std::ptr::null(),
1156
+ )
1157
+ } != 0
1158
+ {
1159
+ return Err("bind-mount oci rootfs failed");
1160
+ }
1161
+
1162
+ // Mount /workspace read-write inside oci_rootfs.
1163
+ let ws_src = CString::new(workspace_dir.as_os_str().as_bytes()).map_err(|_| "bad ws")?;
1164
+ let ws_dst =
1165
+ CString::new(oci_rootfs.join("workspace").as_os_str().as_bytes()).map_err(|_| "bad ws")?;
1166
+ if unsafe {
1167
+ libc::mount(
1168
+ ws_src.as_ptr(),
1169
+ ws_dst.as_ptr(),
1170
+ std::ptr::null(),
1171
+ libc::MS_BIND,
1172
+ std::ptr::null(),
1173
+ )
1174
+ } != 0
1175
+ {
1176
+ return Err("bind-mount workspace failed");
1177
+ }
1178
+
1179
+ // Mount bounded /tmp inside oci_rootfs.
1180
+ let tmpfs_c = CString::new("tmpfs").unwrap();
1181
+ let tmp_dst =
1182
+ CString::new(oci_rootfs.join("tmp").as_os_str().as_bytes()).map_err(|_| "bad tmp")?;
1183
+ let tmp_opts = CString::new(format!("size={},mode=1777", spec.temporary_size_bytes))
1184
+ .map_err(|_| "bad tmp opts")?;
1185
+ if unsafe {
1186
+ libc::mount(
1187
+ tmpfs_c.as_ptr(),
1188
+ tmp_dst.as_ptr(),
1189
+ tmpfs_c.as_ptr(),
1190
+ libc::MS_NODEV | libc::MS_NOSUID,
1191
+ tmp_opts.as_ptr().cast(),
1192
+ )
1193
+ } != 0
1194
+ {
1195
+ return Err("mount /tmp failed");
1196
+ }
1197
+
1198
+ // Mount minimal /dev tmpfs + bind standard safe device nodes + /dev/shm.
1199
+ let dev_dst =
1200
+ CString::new(oci_rootfs.join("dev").as_os_str().as_bytes()).map_err(|_| "bad dev")?;
1201
+ let dev_opts = CString::new("size=65536,mode=0755").unwrap();
1202
+ if unsafe {
1203
+ libc::mount(
1204
+ tmpfs_c.as_ptr(),
1205
+ dev_dst.as_ptr(),
1206
+ tmpfs_c.as_ptr(),
1207
+ libc::MS_NOSUID | libc::MS_NOEXEC,
1208
+ dev_opts.as_ptr().cast(),
1209
+ )
1210
+ } != 0
1211
+ {
1212
+ return Err("mount /dev failed");
1213
+ }
1214
+ for dev_name in ["null", "zero", "full", "random", "urandom", "tty"] {
1215
+ let host_dev = Path::new("/dev").join(dev_name);
1216
+ let guest_dev = oci_rootfs.join("dev").join(dev_name);
1217
+ if host_dev.exists() {
1218
+ let _ = OpenOptions::new().write(true).create(true).truncate(false).open(&guest_dev);
1219
+ let s = CString::new(host_dev.as_os_str().as_bytes()).unwrap();
1220
+ let d = CString::new(guest_dev.as_os_str().as_bytes()).unwrap();
1221
+ unsafe {
1222
+ libc::mount(s.as_ptr(), d.as_ptr(), std::ptr::null(), libc::MS_BIND, std::ptr::null());
1223
+ }
1224
+ }
1225
+ }
1226
+ let shm_dir = oci_rootfs.join("dev/shm");
1227
+ let _ = fs::create_dir(&shm_dir);
1228
+ let shm_dst = CString::new(shm_dir.as_os_str().as_bytes()).unwrap();
1229
+ let shm_opts = CString::new(format!("size={},mode=1777", spec.shared_memory_bytes))
1230
+ .map_err(|_| "bad shm opts")?;
1231
+ if unsafe {
1232
+ libc::mount(
1233
+ tmpfs_c.as_ptr(),
1234
+ shm_dst.as_ptr(),
1235
+ tmpfs_c.as_ptr(),
1236
+ libc::MS_NODEV | libc::MS_NOSUID | libc::MS_NOEXEC,
1237
+ shm_opts.as_ptr().cast(),
1238
+ )
1239
+ } != 0
1240
+ {
1241
+ return Err("mount /dev/shm failed");
1242
+ }
1243
+
1244
+ // Mount fresh /proc inside oci_rootfs.
1245
+ let proc_c = CString::new("proc").unwrap();
1246
+ let proc_dst =
1247
+ CString::new(oci_rootfs.join("proc").as_os_str().as_bytes()).map_err(|_| "bad proc")?;
1248
+ if unsafe {
1249
+ libc::mount(
1250
+ proc_c.as_ptr(),
1251
+ proc_dst.as_ptr(),
1252
+ proc_c.as_ptr(),
1253
+ libc::MS_NODEV | libc::MS_NOSUID | libc::MS_NOEXEC,
1254
+ std::ptr::null(),
1255
+ )
1256
+ } != 0
1257
+ {
1258
+ return Err("mount /proc failed");
1259
+ }
1260
+
1261
+ // Bind-mount read-only npmrc directory inside the rootfs when npmRead grants are active.
1262
+ if let Some(src_npmrc) = npmrc_dir {
1263
+ let dst_npmrc = oci_rootfs.join("run/shipzone-npmrc");
1264
+ let _ = fs::create_dir_all(&dst_npmrc);
1265
+ let s = CString::new(src_npmrc.as_os_str().as_bytes()).map_err(|_| "bad npmrc")?;
1266
+ let d = CString::new(dst_npmrc.as_os_str().as_bytes()).map_err(|_| "bad npmrc")?;
1267
+ unsafe {
1268
+ libc::mount(s.as_ptr(), d.as_ptr(), std::ptr::null(), libc::MS_BIND, std::ptr::null());
1269
+ libc::mount(
1270
+ std::ptr::null(),
1271
+ d.as_ptr(),
1272
+ std::ptr::null(),
1273
+ libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY,
1274
+ std::ptr::null(),
1275
+ );
1276
+ }
1277
+ }
1278
+
1279
+ // pivot_root into oci_rootfs using /tmp/.oldroot as put_old, then detach & remove oldroot.
1280
+ let put_old = oci_rootfs.join("tmp/.oldroot");
1281
+ fs::create_dir(&put_old).map_err(|_| "mkdir put_old failed")?;
1282
+ let put_old_c = CString::new(put_old.as_os_str().as_bytes()).unwrap();
1283
+ if unsafe { libc::syscall(libc::SYS_pivot_root, rootfs_c.as_ptr(), put_old_c.as_ptr()) } != 0 {
1284
+ return Err("pivot_root failed");
1285
+ }
1286
+ if unsafe { libc::chdir(slash.as_ptr()) } != 0 {
1287
+ return Err("chdir / failed");
1288
+ }
1289
+ let old_in_new = CString::new("/tmp/.oldroot").unwrap();
1290
+ unsafe {
1291
+ libc::umount2(old_in_new.as_ptr(), libc::MNT_DETACH);
1292
+ }
1293
+ let _ = fs::remove_dir("/tmp/.oldroot");
1294
+
1295
+ if !spec.root_mode {
1296
+ // OCI mode: remount root filesystem read-only and drop all privileges to numeric uid:gid.
1297
+ unsafe {
1298
+ libc::mount(
1299
+ std::ptr::null(),
1300
+ slash.as_ptr(),
1301
+ std::ptr::null(),
1302
+ libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY,
1303
+ std::ptr::null(),
1304
+ );
1305
+ }
1306
+ if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
1307
+ return Err("PR_SET_NO_NEW_PRIVS failed");
1308
+ }
1309
+ unsafe {
1310
+ libc::setgroups(0, std::ptr::null());
1311
+ }
1312
+ if unsafe { libc::setresgid(spec.gid, spec.gid, spec.gid) } != 0 {
1313
+ return Err("setresgid failed");
1314
+ }
1315
+ if unsafe { libc::setresuid(spec.uid, spec.uid, spec.uid) } != 0 {
1316
+ return Err("setresuid failed");
1317
+ }
1318
+ unsafe {
1319
+ drop_all_capabilities();
1320
+ }
1321
+ }
1322
+ Ok(())
1323
+ }
1324
+
1325
+ fn execute_step<S: Read + Write + AsRawFd>(
1326
+ stream: &mut S,
1327
+ ctx: &GuestContext,
1328
+ spec: StepSpec,
1329
+ ) -> Result<StepResponse, String> {
1330
+ if spec.command.is_empty() {
1331
+ return Err("step command must not be empty".into());
1332
+ }
1333
+ let (stdout_r, stdout_w) = make_pipe()?;
1334
+ let (stderr_r, stderr_w) = make_pipe()?;
1335
+ set_nonblocking(stdout_r.as_raw_fd());
1336
+ set_nonblocking(stderr_r.as_raw_fd());
1337
+
1338
+ let cgroup_leaf = if ctx.pid1_mode {
1339
+ create_step_cgroup(spec.seq, spec.memory_bytes, spec.cpus, spec.pids)
1340
+ } else {
1341
+ None
1342
+ };
1343
+
1344
+ let argv: Vec<CString> = spec
1345
+ .command
1346
+ .iter()
1347
+ .map(|arg| CString::new(arg.as_bytes()).map_err(|_| "command arg contains NUL".to_owned()))
1348
+ .collect::<Result<_, _>>()?;
1349
+ let envp: Vec<CString> = spec
1350
+ .env
1351
+ .iter()
1352
+ .map(|(k, v)| {
1353
+ CString::new(format!("{k}={v}")).map_err(|_| "env contains NUL".to_owned())
1354
+ })
1355
+ .collect::<Result<_, _>>()?;
1356
+
1357
+ let pid = unsafe { libc::fork() };
1358
+ if pid < 0 {
1359
+ return Err(format!("fork failed: {}", io::Error::last_os_error()));
1360
+ }
1361
+ if pid == 0 {
1362
+ // Child process.
1363
+ unsafe {
1364
+ libc::dup2(stdout_w.as_raw_fd(), libc::STDOUT_FILENO);
1365
+ libc::dup2(stderr_w.as_raw_fd(), libc::STDERR_FILENO);
1366
+ let devnull = libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY);
1367
+ if devnull >= 0 {
1368
+ libc::dup2(devnull, libc::STDIN_FILENO);
1369
+ libc::close(devnull);
1370
+ }
1371
+ }
1372
+ drop(stdout_r);
1373
+ drop(stdout_w);
1374
+ drop(stderr_r);
1375
+ drop(stderr_w);
1376
+
1377
+ if let Some(ref leaf) = cgroup_leaf {
1378
+ let _ = fs::write(leaf.join("cgroup.procs"), format!("{}\n", std::process::id()));
1379
+ }
1380
+
1381
+ if ctx.pid1_mode {
1382
+ // Double-fork inside a new PID namespace so step processes cannot see PID 1 or escape.
1383
+ if unsafe { libc::unshare(libc::CLONE_NEWPID) } != 0 {
1384
+ unsafe { libc::_exit(126) };
1385
+ }
1386
+ let inner = unsafe { libc::fork() };
1387
+ if inner < 0 {
1388
+ unsafe { libc::_exit(126) };
1389
+ }
1390
+ if inner > 0 {
1391
+ let mut status: libc::c_int = 0;
1392
+ unsafe {
1393
+ libc::waitpid(inner, &mut status, 0);
1394
+ if libc::WIFEXITED(status) {
1395
+ libc::_exit(libc::WEXITSTATUS(status));
1396
+ }
1397
+ if libc::WIFSIGNALED(status) {
1398
+ libc::_exit(128 + libc::WTERMSIG(status));
1399
+ }
1400
+ libc::_exit(1);
1401
+ }
1402
+ }
1403
+ #[cfg(target_os = "linux")]
1404
+ {
1405
+ let target_rootfs = if spec.root_mode {
1406
+ &ctx.vm_rootfs
1407
+ } else {
1408
+ &ctx.oci_rootfs
1409
+ };
1410
+ if let Err(msg) = unsafe {
1411
+ setup_pid1_step_sandbox(
1412
+ target_rootfs,
1413
+ &ctx.workspace_dir,
1414
+ ctx.npmrc_dir.as_deref(),
1415
+ &spec,
1416
+ )
1417
+ } {
1418
+ let _ = io::stderr().write_all(msg.as_bytes());
1419
+ unsafe { libc::_exit(126) };
1420
+ }
1421
+ }
1422
+ let cwd = CString::new(spec.working_directory.as_bytes())
1423
+ .unwrap_or_else(|_| CString::new("/workspace").unwrap());
1424
+ if unsafe { libc::chdir(cwd.as_ptr()) } != 0 {
1425
+ unsafe { libc::_exit(126) };
1426
+ }
1427
+ } else {
1428
+ // Unprivileged test mode: run inside workspace_dir without root mounts.
1429
+ let cwd = if spec.working_directory == "/workspace" {
1430
+ ctx.workspace_dir.clone()
1431
+ } else if let Some(rel) = spec.working_directory.strip_prefix("/workspace/") {
1432
+ ctx.workspace_dir.join(rel)
1433
+ } else {
1434
+ ctx.workspace_dir.clone()
1435
+ };
1436
+ if let Ok(cwd_c) = CString::new(cwd.as_os_str().as_bytes()) {
1437
+ let _ = unsafe { libc::chdir(cwd_c.as_ptr()) };
1438
+ }
1439
+ }
1440
+
1441
+ let exec_path = resolve_executable(&spec.command[0], spec.env.get("PATH").map(String::as_str));
1442
+ let mut argv_ptrs: Vec<*const libc::c_char> = argv.iter().map(|s| s.as_ptr()).collect();
1443
+ argv_ptrs.push(std::ptr::null());
1444
+ let mut envp_ptrs: Vec<*const libc::c_char> = envp.iter().map(|s| s.as_ptr()).collect();
1445
+ envp_ptrs.push(std::ptr::null());
1446
+
1447
+ unsafe {
1448
+ libc::execve(exec_path.as_ptr(), argv_ptrs.as_ptr(), envp_ptrs.as_ptr());
1449
+ let err = io::Error::last_os_error();
1450
+ let msg = format!("execve failed: {err}\n");
1451
+ let _ = io::stderr().write_all(msg.as_bytes());
1452
+ libc::_exit(127);
1453
+ }
1454
+ }
1455
+
1456
+ // Parent process: close write ends, stream stdout/stderr, watch cancel + deadline.
1457
+ drop(stdout_w);
1458
+ drop(stderr_w);
1459
+
1460
+ let deadline = Instant::now() + Duration::from_millis(spec.timeout_ms.max(1));
1461
+ let mut stdout_open = true;
1462
+ let mut stderr_open = true;
1463
+ let mut timed_out = false;
1464
+ let mut canceled = false;
1465
+ let mut killed = false;
1466
+ let mut exit_status: Option<libc::c_int> = None;
1467
+ let mut buf = [0u8; STREAM_CHUNK_BYTES];
1468
+
1469
+ let kill_child = |pid: libc::pid_t, cgroup: &Option<PathBuf>| {
1470
+ if let Some(leaf) = cgroup {
1471
+ let _ = fs::write(leaf.join("cgroup.kill"), "1\n");
1472
+ }
1473
+ unsafe {
1474
+ libc::kill(pid, libc::SIGKILL);
1475
+ }
1476
+ };
1477
+
1478
+ while stdout_open || stderr_open || exit_status.is_none() {
1479
+ if !killed && Instant::now() >= deadline {
1480
+ timed_out = true;
1481
+ killed = true;
1482
+ kill_child(pid, &cgroup_leaf);
1483
+ }
1484
+
1485
+ let mut pollfds: Vec<libc::pollfd> = Vec::with_capacity(3);
1486
+ if stdout_open {
1487
+ pollfds.push(libc::pollfd {
1488
+ fd: stdout_r.as_raw_fd(),
1489
+ events: libc::POLLIN,
1490
+ revents: 0,
1491
+ });
1492
+ }
1493
+ if stderr_open {
1494
+ pollfds.push(libc::pollfd {
1495
+ fd: stderr_r.as_raw_fd(),
1496
+ events: libc::POLLIN,
1497
+ revents: 0,
1498
+ });
1499
+ }
1500
+ if !killed {
1501
+ pollfds.push(libc::pollfd {
1502
+ fd: stream.as_raw_fd(),
1503
+ events: libc::POLLIN,
1504
+ revents: 0,
1505
+ });
1506
+ }
1507
+
1508
+ if !pollfds.is_empty() {
1509
+ unsafe {
1510
+ libc::poll(
1511
+ pollfds.as_mut_ptr(),
1512
+ pollfds.len() as libc::nfds_t,
1513
+ MAXIMUM_STEP_OUTPUT_POLL_MS,
1514
+ );
1515
+ }
1516
+ }
1517
+
1518
+ for pfd in &pollfds {
1519
+ if pfd.revents == 0 {
1520
+ continue;
1521
+ }
1522
+ if pfd.fd == stdout_r.as_raw_fd() {
1523
+ loop {
1524
+ let n = unsafe {
1525
+ libc::read(stdout_r.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len())
1526
+ };
1527
+ if n > 0 {
1528
+ let _ = write_frame(stream, FRAME_STDOUT, &buf[..n as usize]);
1529
+ } else if n == 0 {
1530
+ stdout_open = false;
1531
+ break;
1532
+ } else {
1533
+ let err = io::Error::last_os_error();
1534
+ if err.kind() == io::ErrorKind::WouldBlock {
1535
+ break;
1536
+ }
1537
+ stdout_open = false;
1538
+ break;
1539
+ }
1540
+ }
1541
+ } else if pfd.fd == stderr_r.as_raw_fd() {
1542
+ loop {
1543
+ let n = unsafe {
1544
+ libc::read(stderr_r.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len())
1545
+ };
1546
+ if n > 0 {
1547
+ let _ = write_frame(stream, FRAME_STDERR, &buf[..n as usize]);
1548
+ } else if n == 0 {
1549
+ stderr_open = false;
1550
+ break;
1551
+ } else {
1552
+ let err = io::Error::last_os_error();
1553
+ if err.kind() == io::ErrorKind::WouldBlock {
1554
+ break;
1555
+ }
1556
+ stderr_open = false;
1557
+ break;
1558
+ }
1559
+ }
1560
+ } else if pfd.fd == stream.as_raw_fd() {
1561
+ match read_frame(stream) {
1562
+ Ok(Some((FRAME_CANCEL, _))) | Ok(None) | Err(_) => {
1563
+ canceled = true;
1564
+ killed = true;
1565
+ kill_child(pid, &cgroup_leaf);
1566
+ }
1567
+ Ok(Some(_)) => {}
1568
+ }
1569
+ }
1570
+ }
1571
+
1572
+ if exit_status.is_none() {
1573
+ let mut st: libc::c_int = 0;
1574
+ let waited = unsafe { libc::waitpid(pid, &mut st, libc::WNOHANG) };
1575
+ if waited == pid {
1576
+ exit_status = Some(st);
1577
+ }
1578
+ }
1579
+ }
1580
+
1581
+ let oom_killed = match cgroup_leaf {
1582
+ Some(ref leaf) => kill_and_cleanup_cgroup(leaf),
1583
+ None => false,
1584
+ };
1585
+
1586
+ let (exit_code, signal) = match exit_status {
1587
+ Some(st) if libc::WIFEXITED(st) => (Some(libc::WEXITSTATUS(st)), None),
1588
+ Some(st) if libc::WIFSIGNALED(st) => (None, Some(libc::WTERMSIG(st))),
1589
+ _ => (None, None),
1590
+ };
1591
+
1592
+ let counts = measure_tree(
1593
+ &ctx.workspace_dir,
1594
+ spec.maximum_workspace_bytes,
1595
+ spec.maximum_workspace_entries,
1596
+ )
1597
+ .map_err(|e| e.to_string())?;
1598
+
1599
+ Ok(StepResponse {
1600
+ ok: true,
1601
+ exit_code,
1602
+ signal,
1603
+ timed_out,
1604
+ canceled,
1605
+ oom_killed,
1606
+ workspace_bytes: counts.bytes,
1607
+ workspace_entries: counts.entries,
1608
+ })
1609
+ }
1610
+
1611
+ fn mount_fs(source: &str, target: &str, fstype: &str, flags: libc::c_ulong, data: Option<&str>) {
1612
+ let _ = fs::create_dir_all(target);
1613
+ let s = CString::new(source).unwrap();
1614
+ let t = CString::new(target).unwrap();
1615
+ let f = CString::new(fstype).unwrap();
1616
+ let d = data.and_then(|v| CString::new(v).ok());
1617
+ let ptr = d.as_ref().map_or(std::ptr::null(), |c| c.as_ptr().cast());
1618
+ unsafe {
1619
+ libc::mount(s.as_ptr(), t.as_ptr(), f.as_ptr(), flags, ptr);
1620
+ }
1621
+ }
1622
+
1623
+ fn listen_vsock(port: u32) -> Result<OwnedFd, Error> {
1624
+ let fd = unsafe { libc::socket(AF_VSOCK, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0) };
1625
+ if fd < 0 {
1626
+ return Err(Error::new("unable to create AF_VSOCK socket"));
1627
+ }
1628
+ let owned = unsafe { OwnedFd::from_raw_fd(fd) };
1629
+ let addr = SockAddrVm {
1630
+ svm_family: AF_VSOCK as libc::sa_family_t,
1631
+ svm_reserved1: 0,
1632
+ svm_port: port,
1633
+ svm_cid: VMADDR_CID_ANY,
1634
+ svm_zero: [0; 4],
1635
+ };
1636
+ let rc = unsafe {
1637
+ libc::bind(
1638
+ owned.as_raw_fd(),
1639
+ (&addr as *const SockAddrVm).cast(),
1640
+ std::mem::size_of::<SockAddrVm>() as libc::socklen_t,
1641
+ )
1642
+ };
1643
+ if rc != 0 {
1644
+ return Err(Error::new("unable to bind AF_VSOCK listener"));
1645
+ }
1646
+ if unsafe { libc::listen(owned.as_raw_fd(), 4) } != 0 {
1647
+ return Err(Error::new("unable to listen on AF_VSOCK socket"));
1648
+ }
1649
+ Ok(owned)
1650
+ }
1651
+
1652
+ struct ImageBuildSpec {
1653
+ context: String,
1654
+ dockerfile: String,
1655
+ target: Option<String>,
1656
+ platform: String,
1657
+ build_args: BTreeMap<String, String>,
1658
+ secrets: BTreeMap<String, String>,
1659
+ labels: BTreeMap<String, String>,
1660
+ base_images: Vec<BuildBaseImage>,
1661
+ npmrc_content: Option<String>,
1662
+ push_registry: String,
1663
+ push_repository: String,
1664
+ grants: Vec<BuildRegistryGrant>,
1665
+ timeout_ms: u64,
1666
+ import_cache_dir: Option<String>,
1667
+ export_cache_dir: Option<String>,
1668
+ buildctl_path: Option<String>,
1669
+ }
1670
+
1671
+ fn base64_encode(input: &[u8]) -> String {
1672
+ const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1673
+ let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
1674
+ for chunk in input.chunks(3) {
1675
+ let b0 = u32::from(chunk[0]);
1676
+ let b1 = if chunk.len() > 1 { u32::from(chunk[1]) } else { 0 };
1677
+ let b2 = if chunk.len() > 2 { u32::from(chunk[2]) } else { 0 };
1678
+ let triple = (b0 << 16) | (b1 << 8) | b2;
1679
+ out.push(TABLE[((triple >> 18) & 0x3f) as usize] as char);
1680
+ out.push(TABLE[((triple >> 12) & 0x3f) as usize] as char);
1681
+ out.push(if chunk.len() > 1 {
1682
+ TABLE[((triple >> 6) & 0x3f) as usize] as char
1683
+ } else {
1684
+ '='
1685
+ });
1686
+ out.push(if chunk.len() > 2 {
1687
+ TABLE[(triple & 0x3f) as usize] as char
1688
+ } else {
1689
+ '='
1690
+ });
1691
+ }
1692
+ out
1693
+ }
1694
+
1695
+ /// Builds the BuildKit source policy JSON enforcing `@ship.zone/ci-spec`:
1696
+ /// DENY `docker-image://*` followed by ALLOW of exact SHA-256 digest-pinned references (last match wins).
1697
+ fn buildkit_source_policy_json() -> String {
1698
+ serde_json::json!({
1699
+ "rules": [
1700
+ {
1701
+ "action": "DENY",
1702
+ "selector": { "identifier": "docker-image://*" }
1703
+ },
1704
+ {
1705
+ "action": "ALLOW",
1706
+ "selector": {
1707
+ "identifier": "docker-image://.*@sha256:[a-f0-9]{64}$",
1708
+ "matchType": "REGEX"
1709
+ }
1710
+ }
1711
+ ]
1712
+ })
1713
+ .to_string()
1714
+ }
1715
+
1716
+ fn execute_image_build<S: Read + Write + AsRawFd>(
1717
+ stream: &mut S,
1718
+ ctx: &GuestContext,
1719
+ spec: ImageBuildSpec,
1720
+ ) -> Result<ImageBuildResponse, String> {
1721
+ let runtime_root = if ctx.pid1_mode {
1722
+ PathBuf::from("/run/shipzone-build")
1723
+ } else {
1724
+ ctx.workspace_dir
1725
+ .parent()
1726
+ .unwrap_or_else(|| Path::new("/tmp"))
1727
+ .join(".shipzone-build")
1728
+ };
1729
+ let _ = fs::remove_dir_all(&runtime_root);
1730
+ let secrets_dir = runtime_root.join("secrets");
1731
+ let docker_config_dir = runtime_root.join("docker-config");
1732
+ fs::create_dir_all(&secrets_dir).map_err(|e| format!("create build secrets dir: {e}"))?;
1733
+ fs::create_dir_all(&docker_config_dir)
1734
+ .map_err(|e| format!("create docker config dir: {e}"))?;
1735
+ let _ = fs::set_permissions(&runtime_root, fs::Permissions::from_mode(0o700));
1736
+ let _ = fs::set_permissions(&secrets_dir, fs::Permissions::from_mode(0o700));
1737
+ let _ = fs::set_permissions(&docker_config_dir, fs::Permissions::from_mode(0o700));
1738
+
1739
+ let cleanup = || {
1740
+ let _ = fs::remove_dir_all(&runtime_root);
1741
+ };
1742
+
1743
+ let result = (|| -> Result<ImageBuildResponse, String> {
1744
+ // 1. Source policy file enforcing exact SHA-256 digest pinning.
1745
+ let policy_path = runtime_root.join("source-policy.json");
1746
+ fs::write(&policy_path, buildkit_source_policy_json())
1747
+ .map_err(|e| format!("write source policy: {e}"))?;
1748
+
1749
+ // 2. Scoped Docker config.json holding ONLY the attempt's lease grants.
1750
+ let mut auths = serde_json::Map::new();
1751
+ for grant in &spec.grants {
1752
+ let encoded = base64_encode(format!("{}:{}", grant.username, grant.secret).as_bytes());
1753
+ auths.insert(grant.registry.clone(), serde_json::json!({ "auth": encoded }));
1754
+ }
1755
+ fs::write(
1756
+ docker_config_dir.join("config.json"),
1757
+ serde_json::json!({ "auths": auths }).to_string(),
1758
+ )
1759
+ .map_err(|e| format!("write docker config: {e}"))?;
1760
+
1761
+ // 3. Build secrets (+ optional `npmrc` secret) written mode 0400 in private tmpfs.
1762
+ let mut secret_args: Vec<String> = Vec::new();
1763
+ for (id, value) in &spec.secrets {
1764
+ if id.is_empty() || id.contains('/') || id.contains(',') || id.contains('\0') {
1765
+ return Err(format!("invalid build secret id: {id}"));
1766
+ }
1767
+ let secret_path = secrets_dir.join(id);
1768
+ let mut file = OpenOptions::new()
1769
+ .write(true)
1770
+ .create(true)
1771
+ .truncate(true)
1772
+ .mode(0o400)
1773
+ .open(&secret_path)
1774
+ .map_err(|e| format!("create secret file {id}: {e}"))?;
1775
+ file.write_all(value.as_bytes())
1776
+ .map_err(|e| format!("write secret file {id}: {e}"))?;
1777
+ secret_args.push(format!("id={id},src={}", secret_path.display()));
1778
+ }
1779
+ if let Some(ref npmrc) = spec.npmrc_content {
1780
+ let npmrc_path = secrets_dir.join("npmrc");
1781
+ let mut file = OpenOptions::new()
1782
+ .write(true)
1783
+ .create(true)
1784
+ .truncate(true)
1785
+ .mode(0o400)
1786
+ .open(&npmrc_path)
1787
+ .map_err(|e| format!("create npmrc secret file: {e}"))?;
1788
+ file.write_all(npmrc.as_bytes())
1789
+ .map_err(|e| format!("write npmrc secret file: {e}"))?;
1790
+ secret_args.push(format!("id=npmrc,src={}", npmrc_path.display()));
1791
+ }
1792
+
1793
+ // 4. Assemble buildctl arguments matching ci-spec OCI Image Build Profile.
1794
+ let context_dir = ctx.workspace_dir.join(&spec.context);
1795
+ let dockerfile_rel = Path::new(&spec.dockerfile);
1796
+ let dockerfile_dir = dockerfile_rel
1797
+ .parent()
1798
+ .map(|p| ctx.workspace_dir.join(p))
1799
+ .unwrap_or_else(|| ctx.workspace_dir.clone());
1800
+ let dockerfile_name = dockerfile_rel
1801
+ .file_name()
1802
+ .and_then(|n| n.to_str())
1803
+ .ok_or_else(|| "invalid dockerfile path".to_owned())?;
1804
+ let metadata_path = runtime_root.join("metadata.json");
1805
+
1806
+ let buildctl = spec
1807
+ .buildctl_path
1808
+ .unwrap_or_else(|| "/usr/bin/buildctl".to_owned());
1809
+ let mut args: Vec<String> = vec![
1810
+ buildctl.clone(),
1811
+ "build".into(),
1812
+ "--frontend".into(),
1813
+ "dockerfile.v0".into(),
1814
+ "--local".into(),
1815
+ format!("context={}", context_dir.display()),
1816
+ "--local".into(),
1817
+ format!("dockerfile={}", dockerfile_dir.display()),
1818
+ "--opt".into(),
1819
+ format!("filename={dockerfile_name}"),
1820
+ "--opt".into(),
1821
+ format!("platform={}", spec.platform),
1822
+ "--opt".into(),
1823
+ format!("source-policy-file={}", policy_path.display()),
1824
+ "--opt".into(),
1825
+ "attest:provenance=false".into(),
1826
+ "--opt".into(),
1827
+ "attest:sbom=false".into(),
1828
+ "--output".into(),
1829
+ format!(
1830
+ "type=image,name={}/{},push=true,push-by-digest=true,oci-mediatypes=true",
1831
+ spec.push_registry, spec.push_repository
1832
+ ),
1833
+ "--metadata-file".into(),
1834
+ metadata_path.display().to_string(),
1835
+ ];
1836
+ if let Some(ref target) = spec.target {
1837
+ args.push("--opt".into());
1838
+ args.push(format!("target={target}"));
1839
+ }
1840
+ for (k, v) in &spec.build_args {
1841
+ args.push("--opt".into());
1842
+ args.push(format!("build-arg:{k}={v}"));
1843
+ }
1844
+ for (k, v) in &spec.labels {
1845
+ args.push("--opt".into());
1846
+ args.push(format!("label:{k}={v}"));
1847
+ }
1848
+ for base in &spec.base_images {
1849
+ args.push("--opt".into());
1850
+ args.push(format!("context:{}=docker-image://{}", base.name, base.image));
1851
+ }
1852
+ for secret in &secret_args {
1853
+ args.push("--secret".into());
1854
+ args.push(secret.clone());
1855
+ }
1856
+ if let Some(ref import_dir) = spec.import_cache_dir {
1857
+ args.push("--import-cache".into());
1858
+ args.push(format!("type=local,src={import_dir}"));
1859
+ }
1860
+ if let Some(ref export_dir) = spec.export_cache_dir {
1861
+ args.push("--export-cache".into());
1862
+ args.push(format!("type=local,dest={export_dir},mode=max"));
1863
+ }
1864
+
1865
+ // 5. Spawn buildctl, streaming stdout/stderr over vsock and watching timeout/cancel.
1866
+ let (stdout_r, stdout_w) = make_pipe()?;
1867
+ let (stderr_r, stderr_w) = make_pipe()?;
1868
+ set_nonblocking(stdout_r.as_raw_fd());
1869
+ set_nonblocking(stderr_r.as_raw_fd());
1870
+
1871
+ let argv: Vec<CString> = args
1872
+ .iter()
1873
+ .map(|a| CString::new(a.as_bytes()).map_err(|_| "buildctl arg contains NUL".to_owned()))
1874
+ .collect::<Result<_, _>>()?;
1875
+ let env_pairs = [
1876
+ format!("DOCKER_CONFIG={}", docker_config_dir.display()),
1877
+ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".to_owned(),
1878
+ ];
1879
+ let envp: Vec<CString> = env_pairs
1880
+ .iter()
1881
+ .map(|e| CString::new(e.as_bytes()).unwrap())
1882
+ .collect();
1883
+
1884
+ let pid = unsafe { libc::fork() };
1885
+ if pid < 0 {
1886
+ return Err(format!("fork buildctl failed: {}", io::Error::last_os_error()));
1887
+ }
1888
+ if pid == 0 {
1889
+ unsafe {
1890
+ libc::dup2(stdout_w.as_raw_fd(), libc::STDOUT_FILENO);
1891
+ libc::dup2(stderr_w.as_raw_fd(), libc::STDERR_FILENO);
1892
+ }
1893
+ drop(stdout_r);
1894
+ drop(stdout_w);
1895
+ drop(stderr_r);
1896
+ drop(stderr_w);
1897
+ let mut argv_ptrs: Vec<*const libc::c_char> = argv.iter().map(|s| s.as_ptr()).collect();
1898
+ argv_ptrs.push(std::ptr::null());
1899
+ let mut envp_ptrs: Vec<*const libc::c_char> = envp.iter().map(|s| s.as_ptr()).collect();
1900
+ envp_ptrs.push(std::ptr::null());
1901
+ unsafe {
1902
+ libc::execve(argv[0].as_ptr(), argv_ptrs.as_ptr(), envp_ptrs.as_ptr());
1903
+ libc::_exit(127);
1904
+ }
1905
+ }
1906
+ drop(stdout_w);
1907
+ drop(stderr_w);
1908
+
1909
+ let deadline = Instant::now() + Duration::from_millis(spec.timeout_ms.max(1));
1910
+ let mut stdout_open = true;
1911
+ let mut stderr_open = true;
1912
+ let mut timed_out = false;
1913
+ let mut canceled = false;
1914
+ let mut killed = false;
1915
+ let mut exit_status: Option<libc::c_int> = None;
1916
+ let mut buf = [0u8; STREAM_CHUNK_BYTES];
1917
+
1918
+ while stdout_open || stderr_open || exit_status.is_none() {
1919
+ if !killed && Instant::now() >= deadline {
1920
+ timed_out = true;
1921
+ killed = true;
1922
+ unsafe {
1923
+ libc::kill(pid, libc::SIGKILL);
1924
+ }
1925
+ }
1926
+ let mut pollfds: Vec<libc::pollfd> = Vec::with_capacity(3);
1927
+ if stdout_open {
1928
+ pollfds.push(libc::pollfd {
1929
+ fd: stdout_r.as_raw_fd(),
1930
+ events: libc::POLLIN,
1931
+ revents: 0,
1932
+ });
1933
+ }
1934
+ if stderr_open {
1935
+ pollfds.push(libc::pollfd {
1936
+ fd: stderr_r.as_raw_fd(),
1937
+ events: libc::POLLIN,
1938
+ revents: 0,
1939
+ });
1940
+ }
1941
+ if !killed {
1942
+ pollfds.push(libc::pollfd {
1943
+ fd: stream.as_raw_fd(),
1944
+ events: libc::POLLIN,
1945
+ revents: 0,
1946
+ });
1947
+ }
1948
+ if !pollfds.is_empty() {
1949
+ unsafe {
1950
+ libc::poll(
1951
+ pollfds.as_mut_ptr(),
1952
+ pollfds.len() as libc::nfds_t,
1953
+ MAXIMUM_STEP_OUTPUT_POLL_MS,
1954
+ );
1955
+ }
1956
+ }
1957
+ for pfd in &pollfds {
1958
+ if pfd.revents == 0 {
1959
+ continue;
1960
+ }
1961
+ if pfd.fd == stdout_r.as_raw_fd() {
1962
+ loop {
1963
+ let n = unsafe {
1964
+ libc::read(stdout_r.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len())
1965
+ };
1966
+ if n > 0 {
1967
+ let _ = write_frame(stream, FRAME_STDOUT, &buf[..n as usize]);
1968
+ } else if n == 0 {
1969
+ stdout_open = false;
1970
+ break;
1971
+ } else if io::Error::last_os_error().kind() == io::ErrorKind::WouldBlock {
1972
+ break;
1973
+ } else {
1974
+ stdout_open = false;
1975
+ break;
1976
+ }
1977
+ }
1978
+ } else if pfd.fd == stderr_r.as_raw_fd() {
1979
+ loop {
1980
+ let n = unsafe {
1981
+ libc::read(stderr_r.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len())
1982
+ };
1983
+ if n > 0 {
1984
+ let _ = write_frame(stream, FRAME_STDERR, &buf[..n as usize]);
1985
+ } else if n == 0 {
1986
+ stderr_open = false;
1987
+ break;
1988
+ } else if io::Error::last_os_error().kind() == io::ErrorKind::WouldBlock {
1989
+ break;
1990
+ } else {
1991
+ stderr_open = false;
1992
+ break;
1993
+ }
1994
+ }
1995
+ } else if pfd.fd == stream.as_raw_fd() {
1996
+ match read_frame(stream) {
1997
+ Ok(Some((FRAME_CANCEL, _))) | Ok(None) | Err(_) => {
1998
+ canceled = true;
1999
+ killed = true;
2000
+ unsafe {
2001
+ libc::kill(pid, libc::SIGKILL);
2002
+ }
2003
+ }
2004
+ Ok(Some(_)) => {}
2005
+ }
2006
+ }
2007
+ }
2008
+ if exit_status.is_none() {
2009
+ let mut st: libc::c_int = 0;
2010
+ let waited = unsafe { libc::waitpid(pid, &mut st, libc::WNOHANG) };
2011
+ if waited == pid {
2012
+ exit_status = Some(st);
2013
+ }
2014
+ }
2015
+ }
2016
+
2017
+ let exit_code = match exit_status {
2018
+ Some(st) if libc::WIFEXITED(st) => Some(libc::WEXITSTATUS(st)),
2019
+ _ => None,
2020
+ };
2021
+
2022
+ let mut manifest_digest = None;
2023
+ let mut media_type = None;
2024
+ let mut size_bytes = None;
2025
+ if exit_code == Some(0)
2026
+ && !timed_out
2027
+ && !canceled
2028
+ && let Ok(meta_bytes) = fs::read(&metadata_path)
2029
+ && let Ok(meta) = serde_json::from_slice::<serde_json::Value>(&meta_bytes)
2030
+ {
2031
+ manifest_digest = meta
2032
+ .get("containerimage.digest")
2033
+ .and_then(|v| v.as_str())
2034
+ .map(str::to_owned);
2035
+ if let Some(desc) = meta.get("containerimage.descriptor") {
2036
+ if manifest_digest.is_none() {
2037
+ manifest_digest = desc.get("digest").and_then(|v| v.as_str()).map(str::to_owned);
2038
+ }
2039
+ media_type = desc
2040
+ .get("mediaType")
2041
+ .and_then(|v| v.as_str())
2042
+ .map(str::to_owned);
2043
+ size_bytes = desc.get("size").and_then(|v| v.as_u64());
2044
+ }
2045
+ }
2046
+
2047
+ let cache_exported = exit_code == Some(0)
2048
+ && !timed_out
2049
+ && !canceled
2050
+ && spec
2051
+ .export_cache_dir
2052
+ .as_ref()
2053
+ .is_some_and(|dir| Path::new(dir).exists());
2054
+
2055
+ Ok(ImageBuildResponse {
2056
+ ok: true,
2057
+ exit_code,
2058
+ timed_out,
2059
+ canceled,
2060
+ manifest_digest,
2061
+ media_type,
2062
+ size_bytes,
2063
+ cache_exported,
2064
+ })
2065
+ })();
2066
+
2067
+ cleanup();
2068
+ result
2069
+ }
2070
+
2071
+ /// Entrypoint when booted as Firecracker guest PID 1 (`/init` inside initrd).
2072
+ pub fn run_pid1() -> Result<(), Error> {
2073
+ mount_fs("proc", "/proc", "proc", libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, None);
2074
+ mount_fs("sysfs", "/sys", "sysfs", libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, None);
2075
+ mount_fs("devtmpfs", "/dev", "devtmpfs", libc::MS_NOSUID, None);
2076
+ mount_fs("cgroup2", "/sys/fs/cgroup", "cgroup2", libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, None);
2077
+ mount_fs("tmpfs", "/run", "tmpfs", libc::MS_NOSUID | libc::MS_NODEV, Some("size=16m"));
2078
+
2079
+ // Mount the read-only OCI rootfs block device (/dev/vda) at /oci-rootfs.
2080
+ let _ = fs::create_dir_all("/oci-rootfs");
2081
+ let src = CString::new("/dev/vda").unwrap();
2082
+ let dst = CString::new("/oci-rootfs").unwrap();
2083
+ let ext4 = CString::new("ext4").unwrap();
2084
+ let ext2 = CString::new("ext2").unwrap();
2085
+ let noload = CString::new("noload").unwrap();
2086
+ let mounted = unsafe {
2087
+ libc::mount(
2088
+ src.as_ptr(),
2089
+ dst.as_ptr(),
2090
+ ext4.as_ptr(),
2091
+ libc::MS_RDONLY | libc::MS_NODEV,
2092
+ noload.as_ptr().cast(),
2093
+ ) == 0
2094
+ || libc::mount(
2095
+ src.as_ptr(),
2096
+ dst.as_ptr(),
2097
+ ext2.as_ptr(),
2098
+ libc::MS_RDONLY | libc::MS_NODEV,
2099
+ std::ptr::null(),
2100
+ ) == 0
2101
+ };
2102
+ if !mounted {
2103
+ eprintln!(
2104
+ "runnerguest: failed to mount /dev/vda: {}",
2105
+ io::Error::last_os_error()
2106
+ );
2107
+ }
2108
+
2109
+ let listener = listen_vsock(VSOCK_PORT)?;
2110
+ let mut ctx = GuestContext {
2111
+ pid1_mode: true,
2112
+ oci_rootfs: PathBuf::from("/oci-rootfs"),
2113
+ vm_rootfs: PathBuf::from("/vm-rootfs"),
2114
+ workspace_dir: PathBuf::from("/workspace"),
2115
+ npmrc_dir: None,
2116
+ step_counter: 0,
2117
+ };
2118
+
2119
+ loop {
2120
+ let client_fd = unsafe {
2121
+ libc::accept4(
2122
+ listener.as_raw_fd(),
2123
+ std::ptr::null_mut(),
2124
+ std::ptr::null_mut(),
2125
+ libc::SOCK_CLOEXEC,
2126
+ )
2127
+ };
2128
+ if client_fd < 0 {
2129
+ if io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
2130
+ continue;
2131
+ }
2132
+ std::thread::sleep(Duration::from_millis(20));
2133
+ continue;
2134
+ }
2135
+ let mut client = unsafe { File::from_raw_fd(client_fd) };
2136
+ if let Ok(true) = handle_connection(&mut client, &mut ctx) {
2137
+ break;
2138
+ }
2139
+ }
2140
+
2141
+ unsafe {
2142
+ libc::sync();
2143
+ libc::reboot(libc::RB_POWER_OFF);
2144
+ }
2145
+ Ok(())
2146
+ }
2147
+
2148
+ /// Serves the exact same guest framed RPC protocol over a Unix domain socket for unprivileged
2149
+ /// unit & integration tests.
2150
+ pub fn serve_unix_socket(
2151
+ socket_path: &Path,
2152
+ workspace_dir: &Path,
2153
+ ) -> Result<(), Error> {
2154
+ if !socket_path.is_absolute() || !workspace_dir.is_absolute() {
2155
+ return Err(Error::new("guest-init socket and workspace paths must be absolute"));
2156
+ }
2157
+ let _ = fs::remove_file(socket_path);
2158
+ fs::create_dir_all(workspace_dir)
2159
+ .map_err(|_| Error::new("unable to create guest workspace directory"))?;
2160
+ let listener = UnixListener::bind(socket_path)
2161
+ .map_err(|_| Error::new("unable to bind guest-init unix socket"))?;
2162
+ let mut ctx = GuestContext {
2163
+ pid1_mode: false,
2164
+ oci_rootfs: PathBuf::from("/"),
2165
+ vm_rootfs: PathBuf::from("/"),
2166
+ workspace_dir: workspace_dir.to_path_buf(),
2167
+ npmrc_dir: None,
2168
+ step_counter: 0,
2169
+ };
2170
+ println!("listening");
2171
+ let _ = io::stdout().flush();
2172
+
2173
+ for incoming in listener.incoming() {
2174
+ let Ok(mut stream) = incoming else {
2175
+ break;
2176
+ };
2177
+ if let Ok(true) = handle_connection(&mut stream, &mut ctx) {
2178
+ break;
2179
+ }
2180
+ }
2181
+ let _ = fs::remove_file(socket_path);
2182
+ Ok(())
2183
+ }
2184
+
2185
+ /// Returns true when the current process was booted as `/init` (or PID 1 inside a microVM guest).
2186
+ pub fn invoked_as_pid1() -> bool {
2187
+ if std::process::id() == 1 {
2188
+ return true;
2189
+ }
2190
+ std::env::args_os()
2191
+ .next()
2192
+ .is_some_and(|arg| arg.as_bytes() == b"/init")
2193
+ }
2194
+
2195
+ #[allow(dead_code)]
2196
+ fn _cstr_unused(_: &CStr) {}
2197
+
2198
+ #[cfg(test)]
2199
+ mod tests {
2200
+ use super::*;
2201
+ use std::os::unix::net::UnixStream;
2202
+
2203
+ #[test]
2204
+ fn guest_rpc_imports_runs_step_and_exports_over_unix_socket() {
2205
+ let dir = std::env::temp_dir().join(format!(
2206
+ "runnerworkspace-guest-test-{}",
2207
+ std::process::id()
2208
+ ));
2209
+ let _ = fs::remove_dir_all(&dir);
2210
+ fs::create_dir_all(&dir).unwrap();
2211
+ let sock = dir.join("guest.sock");
2212
+ let ws = dir.join("workspace");
2213
+
2214
+ let sock_srv = sock.clone();
2215
+ let ws_srv = ws.clone();
2216
+ let handle = std::thread::spawn(move || serve_unix_socket(&sock_srv, &ws_srv).unwrap());
2217
+
2218
+ let mut client = loop {
2219
+ if let Ok(s) = UnixStream::connect(&sock) {
2220
+ break s;
2221
+ }
2222
+ std::thread::sleep(Duration::from_millis(10));
2223
+ };
2224
+
2225
+ // 1. hello
2226
+ write_frame(&mut client, FRAME_JSON_REQ, br#"{"op":"hello"}"#).unwrap();
2227
+ let (kind, payload) = read_frame(&mut client).unwrap().unwrap();
2228
+ assert_eq!(kind, FRAME_JSON_RES);
2229
+ let hello: serde_json::Value = serde_json::from_slice(&payload).unwrap();
2230
+ assert_eq!(hello["ok"], true);
2231
+
2232
+ // 2. prepare_workspace
2233
+ write_frame(
2234
+ &mut client,
2235
+ FRAME_JSON_REQ,
2236
+ br#"{"op":"prepare_workspace","workspaceSizeBytes":1048576,"maximumWorkspaceEntries":100,"uid":1000,"gid":1000}"#,
2237
+ )
2238
+ .unwrap();
2239
+ let (_, payload) = read_frame(&mut client).unwrap().unwrap();
2240
+ assert_eq!(serde_json::from_slice::<serde_json::Value>(&payload).unwrap()["ok"], true);
2241
+
2242
+ // 3. import_tar
2243
+ let mut tar = Vec::new();
2244
+ write_tar_entry(
2245
+ &mut tar,
2246
+ &TarEntry {
2247
+ path: "hello.txt".into(),
2248
+ mode: 0o644,
2249
+ uid: 0,
2250
+ gid: 0,
2251
+ mtime: 0,
2252
+ kind: TarEntryKind::File(b"from-host\n".to_vec()),
2253
+ },
2254
+ )
2255
+ .unwrap();
2256
+ write_tar_trailer(&mut tar).unwrap();
2257
+ write_frame(
2258
+ &mut client,
2259
+ FRAME_JSON_REQ,
2260
+ br#"{"op":"import_tar","maximumBytes":1048576,"maximumEntries":100,"uid":1000,"gid":1000}"#,
2261
+ )
2262
+ .unwrap();
2263
+ write_frame(&mut client, FRAME_DATA, &tar).unwrap();
2264
+ write_frame(&mut client, FRAME_DATA_EOF, &[]).unwrap();
2265
+ let (_, payload) = read_frame(&mut client).unwrap().unwrap();
2266
+ let imp: serde_json::Value = serde_json::from_slice(&payload).unwrap();
2267
+ assert_eq!(imp["ok"], true);
2268
+ assert_eq!(imp["bytes"], 10);
2269
+
2270
+ // 4. run_step
2271
+ let step_req = serde_json::json!({
2272
+ "op": "run_step",
2273
+ "command": ["/bin/sh", "-c", "cat hello.txt && echo built > out.txt"],
2274
+ "env": { "PATH": "/usr/bin:/bin" },
2275
+ "workingDirectory": "/workspace",
2276
+ "uid": 1000,
2277
+ "gid": 1000,
2278
+ "timeoutMs": 5000,
2279
+ "memoryBytes": 134217728,
2280
+ "cpus": 1,
2281
+ "pids": 64,
2282
+ "sharedMemoryBytes": 16777216,
2283
+ "temporarySizeBytes": 16777216,
2284
+ "maximumWorkspaceBytes": 1048576,
2285
+ "maximumWorkspaceEntries": 100
2286
+ });
2287
+ write_frame(&mut client, FRAME_JSON_REQ, &serde_json::to_vec(&step_req).unwrap()).unwrap();
2288
+ let mut stdout = Vec::new();
2289
+ let step_res = loop {
2290
+ let (k, p) = read_frame(&mut client).unwrap().unwrap();
2291
+ match k {
2292
+ FRAME_STDOUT => stdout.extend_from_slice(&p),
2293
+ FRAME_STDERR => {}
2294
+ FRAME_JSON_RES => break serde_json::from_slice::<serde_json::Value>(&p).unwrap(),
2295
+ other => panic!("unexpected frame {other}"),
2296
+ }
2297
+ };
2298
+ assert_eq!(stdout, b"from-host\n");
2299
+ assert_eq!(step_res["ok"], true);
2300
+ assert_eq!(step_res["exitCode"], 0);
2301
+
2302
+ // 5. export_tar
2303
+ write_frame(
2304
+ &mut client,
2305
+ FRAME_JSON_REQ,
2306
+ br#"{"op":"export_tar","selections":["out.txt"],"maximumBytes":1048576,"maximumEntries":10}"#,
2307
+ )
2308
+ .unwrap();
2309
+ let exported = read_data_stream(&mut client, 1048576).unwrap();
2310
+ let (_, payload) = read_frame(&mut client).unwrap().unwrap();
2311
+ let exp_res: serde_json::Value = serde_json::from_slice(&payload).unwrap();
2312
+ assert_eq!(exp_res["ok"], true);
2313
+ assert_eq!(exp_res["bytes"], 6);
2314
+ let entries = read_tar_entries(&mut io::Cursor::new(exported), 1048576, 10).unwrap();
2315
+ assert_eq!(entries.len(), 1);
2316
+ assert_eq!(entries[0].path, "out.txt");
2317
+ assert_eq!(entries[0].kind, TarEntryKind::File(b"built\n".to_vec()));
2318
+
2319
+ // 6. shutdown
2320
+ write_frame(&mut client, FRAME_JSON_REQ, br#"{"op":"shutdown"}"#).unwrap();
2321
+ let (_, payload) = read_frame(&mut client).unwrap().unwrap();
2322
+ assert_eq!(serde_json::from_slice::<serde_json::Value>(&payload).unwrap()["ok"], true);
2323
+
2324
+ handle.join().unwrap();
2325
+ let _ = fs::remove_dir_all(&dir);
2326
+ }
2327
+
2328
+ #[test]
2329
+ fn guest_rpc_executes_image_build_with_source_policy_and_cleans_secrets() {
2330
+ let dir = std::env::temp_dir().join(format!(
2331
+ "runnerworkspace-build-test-{}",
2332
+ std::process::id()
2333
+ ));
2334
+ let _ = fs::remove_dir_all(&dir);
2335
+ fs::create_dir_all(&dir).unwrap();
2336
+ let sock = dir.join("guest.sock");
2337
+ let ws = dir.join("workspace");
2338
+ fs::create_dir_all(&ws).unwrap();
2339
+ fs::write(ws.join("Dockerfile"), "FROM scratch\n").unwrap();
2340
+
2341
+ let stub_buildctl = dir.join("stub-buildctl.sh");
2342
+ let args_log = dir.join("buildctl-args.txt");
2343
+ let script = format!(
2344
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" > {}\nMETA=\"\"\nwhile [ $# -gt 0 ]; do\n if [ \"$1\" = \"--metadata-file\" ]; then META=\"$2\"; shift 2; continue; fi\n shift\ndone\nprintf '{{\"containerimage.digest\":\"sha256:{}\",\"containerimage.descriptor\":{{\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"digest\":\"sha256:{}\",\"size\":1234}}}}' > \"$META\"\necho 'buildkit-ok'\n",
2345
+ args_log.display(),
2346
+ "a".repeat(64),
2347
+ "a".repeat(64),
2348
+ );
2349
+ fs::write(&stub_buildctl, script).unwrap();
2350
+ fs::set_permissions(&stub_buildctl, fs::Permissions::from_mode(0o755)).unwrap();
2351
+
2352
+ let sock_srv = sock.clone();
2353
+ let ws_srv = ws.clone();
2354
+ let handle = std::thread::spawn(move || serve_unix_socket(&sock_srv, &ws_srv).unwrap());
2355
+
2356
+ let mut client = loop {
2357
+ if let Ok(s) = UnixStream::connect(&sock) {
2358
+ break s;
2359
+ }
2360
+ std::thread::sleep(Duration::from_millis(10));
2361
+ };
2362
+
2363
+ let req = serde_json::json!({
2364
+ "op": "run_image_build",
2365
+ "context": ".",
2366
+ "dockerfile": "Dockerfile",
2367
+ "platform": "linux/amd64",
2368
+ "buildArgs": { "NODE_ENV": "production" },
2369
+ "secrets": { "my_secret": "super-secret-build-value" },
2370
+ "labels": { "org.opencontainers.image.revision": "abc123" },
2371
+ "baseImages": [{ "name": "base", "image": format!("registry.example/base@sha256:{}", "b".repeat(64)) }],
2372
+ "npmrcContent": "@scope:registry=https://npm.example/\n//npm.example/:_authToken=token012345678901234567890123456789\n",
2373
+ "pushRegistry": "registry.example",
2374
+ "pushRepository": "org/app",
2375
+ "grants": [{ "registry": "registry.example", "username": "grant-user", "secret": "grant-secret-0123456789" }],
2376
+ "timeoutMs": 5000,
2377
+ "buildctlPath": stub_buildctl.to_str().unwrap()
2378
+ });
2379
+ write_frame(&mut client, FRAME_JSON_REQ, &serde_json::to_vec(&req).unwrap()).unwrap();
2380
+ let mut out = Vec::new();
2381
+ let res = loop {
2382
+ let (k, p) = read_frame(&mut client).unwrap().unwrap();
2383
+ match k {
2384
+ FRAME_STDOUT => out.extend_from_slice(&p),
2385
+ FRAME_STDERR => {}
2386
+ FRAME_JSON_RES => break serde_json::from_slice::<serde_json::Value>(&p).unwrap(),
2387
+ other => panic!("unexpected frame {other}"),
2388
+ }
2389
+ };
2390
+ assert_eq!(res["ok"], true);
2391
+ assert_eq!(res["exitCode"], 0);
2392
+ assert_eq!(res["manifestDigest"], format!("sha256:{}", "a".repeat(64)));
2393
+ assert_eq!(res["mediaType"], "application/vnd.oci.image.manifest.v1+json");
2394
+ assert_eq!(res["sizeBytes"], 1234);
2395
+ assert_eq!(String::from_utf8_lossy(&out).trim(), "buildkit-ok");
2396
+
2397
+ let recorded_args = fs::read_to_string(&args_log).unwrap();
2398
+ assert!(recorded_args.contains("attest:provenance=false"));
2399
+ assert!(recorded_args.contains("attest:sbom=false"));
2400
+ assert!(recorded_args.contains("push-by-digest=true"));
2401
+ assert!(recorded_args.contains("id=npmrc,src="));
2402
+ assert!(recorded_args.contains("id=my_secret,src="));
2403
+ // Secrets directory must be wiped after buildctl exits.
2404
+ assert!(!dir.join(".shipzone-build").exists());
2405
+
2406
+ write_frame(&mut client, FRAME_JSON_REQ, br#"{"op":"shutdown"}"#).unwrap();
2407
+ let _ = read_frame(&mut client).unwrap();
2408
+ handle.join().unwrap();
2409
+ let _ = fs::remove_dir_all(&dir);
2410
+ }
2411
+ }