@ship.zone/runner 3.0.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 (79) hide show
  1. package/.smartconfig.json +19 -1
  2. package/changelog.md +43 -0
  3. package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
  4. package/dist_rust/runnerworkspace_linux_amd64_musl.tsrust-build.json +4 -4
  5. package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
  6. package/dist_rust/runnerworkspace_linux_arm64_musl.tsrust-build.json +4 -4
  7. package/dist_ts/00_commitinfo_data.js +3 -3
  8. package/dist_ts/api-client.d.ts +2 -1
  9. package/dist_ts/api-client.js +10 -2
  10. package/dist_ts/artifact-manager.js +1 -1
  11. package/dist_ts/attempt-state.js +1 -1
  12. package/dist_ts/cache-manager.js +1 -1
  13. package/dist_ts/cli-entry.js +17 -3
  14. package/dist_ts/cli.js +39 -11
  15. package/dist_ts/config.js +70 -20
  16. package/dist_ts/egress-proxy.d.ts +99 -0
  17. package/dist_ts/egress-proxy.js +607 -0
  18. package/dist_ts/errors.js +1 -1
  19. package/dist_ts/filesystem.js +1 -1
  20. package/dist_ts/index.d.ts +5 -1
  21. package/dist_ts/index.js +6 -2
  22. package/dist_ts/interfaces.d.ts +93 -22
  23. package/dist_ts/interfaces.js +1 -1
  24. package/dist_ts/log-sender.js +1 -1
  25. package/dist_ts/microvm-executor.d.ts +90 -0
  26. package/dist_ts/microvm-executor.js +1045 -0
  27. package/dist_ts/node-version.d.ts +11 -0
  28. package/dist_ts/node-version.js +43 -0
  29. package/dist_ts/npm-grants.d.ts +9 -0
  30. package/dist_ts/npm-grants.js +44 -0
  31. package/dist_ts/oci-registry.d.ts +73 -0
  32. package/dist_ts/oci-registry.js +508 -0
  33. package/dist_ts/plugins.d.ts +6 -2
  34. package/dist_ts/plugins.js +7 -3
  35. package/dist_ts/protocol-validator.d.ts +3 -3
  36. package/dist_ts/protocol-validator.js +26 -21
  37. package/dist_ts/redactor.js +1 -1
  38. package/dist_ts/registration-state.js +1 -1
  39. package/dist_ts/runner.d.ts +6 -5
  40. package/dist_ts/runner.js +48 -18
  41. package/dist_ts/source-workspace.js +1 -1
  42. package/dist_ts/spec-version.js +1 -1
  43. package/dist_ts/staging-scavenger.js +1 -1
  44. package/dist_ts/state-owner.js +4 -2
  45. package/dist_ts/transfer-archive.js +1 -1
  46. package/dist_ts/validation.js +1 -1
  47. package/dist_ts/vsock-protocol.d.ts +130 -0
  48. package/dist_ts/vsock-protocol.js +336 -0
  49. package/dist_ts/wire-schema.js +1 -1
  50. package/package.json +9 -6
  51. package/readme.md +72 -61
  52. package/rust/Cargo.lock +1 -0
  53. package/rust/Cargo.toml +2 -1
  54. package/rust/src/cpio.rs +147 -0
  55. package/rust/src/extfs.rs +747 -0
  56. package/rust/src/guest.rs +2411 -0
  57. package/rust/src/lib.rs +41 -0
  58. package/rust/src/main.rs +6 -1
  59. package/rust/src/oci_tar.rs +842 -0
  60. package/ts/00_commitinfo_data.ts +2 -2
  61. package/ts/api-client.ts +19 -1
  62. package/ts/cli-entry.ts +15 -2
  63. package/ts/cli.ts +33 -11
  64. package/ts/config.ts +96 -23
  65. package/ts/egress-proxy.ts +649 -0
  66. package/ts/index.ts +5 -1
  67. package/ts/interfaces.ts +103 -21
  68. package/ts/microvm-executor.ts +1265 -0
  69. package/ts/node-version.ts +49 -0
  70. package/ts/npm-grants.ts +49 -0
  71. package/ts/oci-registry.ts +649 -0
  72. package/ts/plugins.ts +6 -2
  73. package/ts/protocol-validator.ts +29 -25
  74. package/ts/runner.ts +51 -17
  75. package/ts/state-owner.ts +8 -1
  76. package/ts/vsock-protocol.ts +437 -0
  77. package/dist_ts/oci-executor.d.ts +0 -155
  78. package/dist_ts/oci-executor.js +0 -2238
  79. package/ts/oci-executor.ts +0 -2989
package/readme.md CHANGED
@@ -1,9 +1,18 @@
1
1
  # @ship.zone/runner
2
2
 
3
- `@ship.zone/runner` is the outbound-only OCI execution agent for ship.zone CI/CD. It implements the
4
- runner protocol of `@ship.zone/ci-spec` (2.0.0) for the `oci` execution profile, validates leases
5
- and compiled jobs against the published schemas, and runs one fenced attempt at a time on a local
6
- Docker or Podman engine.
3
+ `@ship.zone/runner` is the outbound-only Firecracker microVM execution agent for ship.zone CI/CD.
4
+ It implements the runner protocol of `@ship.zone/ci-spec` (2.0.0) with `microvm` isolation for
5
+ `oci`, `vm`, and dedicated-builder `oci-image` execution profiles, validates leases and compiled
6
+ jobs against the published schemas, and runs one fenced attempt at a time inside a dedicated
7
+ Firecracker microVM managed via `@push.rocks/smartvm`.
8
+
9
+ No host Docker or Podman daemon is required or supported. Jobs still choose any digest-pinned
10
+ Linux Docker/OCI image; the runner pulls and verifies the image layers directly via OCI
11
+ Distribution v2, builds a deterministic read-only ext2 rootfs image, and boots a fresh Firecracker
12
+ microVM with that image attached read-only (`/dev/vda`) and the static Rust `runnerworkspace` guest
13
+ agent as PID 1 (`/init`). Dedicated builder runners (`--profile builder`) execute `oci-image`
14
+ builds via BuildKit (`buildctl`) inside a dedicated Firecracker microVM and record the produced
15
+ image digest with the coordinator.
7
16
 
8
17
  The control plane owns workflow compilation, scheduling, authorization, secrets policy, and
9
18
  canonical run state. This package owns runner registration, lease handling, isolated execution,
@@ -19,30 +28,31 @@ Requests directly.
19
28
 
20
29
  ## Security Model
21
30
 
22
- - Only local Unix-socket Docker and Podman endpoints are accepted. Remote contexts and connections
23
- are rejected before capabilities are advertised.
24
- - Job images must be Linux images pinned by an exact SHA-256 digest. The image OS, architecture, and
25
- digest are checked before lease acceptance.
26
- - Every compiled step runs in a fresh container as a numeric non-root user with a read-only root,
27
- all capabilities dropped, `no-new-privileges`, private IPC, and CPU, memory, PID, shared-memory
28
- (`/dev/shm`), time, and writable-storage limits. The job's `resources` are these ceilings; omitted
29
- values take the runner defaults, and every value is bounded by the maximum the runner advertises.
30
- - The only network mode is `none`: every step container runs in a new network namespace whose only
31
- interface is its own loopback, so nothing leaves the sandbox and loopback ports never collide with
32
- another attempt. The runner exposes no service on that loopback. `egress` allowlists are not
33
- enforced by this runner, are never advertised, and cannot be configured.
34
- - Job containers receive no host paths, runtime sockets, devices, host namespaces, or arbitrary OCI
35
- arguments. Their only persistent writable mount is `/workspace`.
36
- - The shared workspace is an attempt-specific `nodev,nosuid` tmpfs with hard byte and entry
37
- ceilings. Imported executable files may run directly from it. A trusted static Rust helper imports
38
- source/cache staging, measures the workspace around every step, and exports only declared
39
- artifact/cache paths.
40
- - Helper containers use the exact job image only as an inert root filesystem. They override the
41
- entrypoint with the packaged static helper, have no network, and receive only the narrowly scoped
42
- `CHOWN` and `DAC_OVERRIDE` capabilities required for private staging ownership. Job containers do
43
- not receive those capabilities.
44
- - Step containers receive exactly the compiled step environment plus job secrets. Secret values are
45
- passed through the runtime environment rather than OCI command arguments.
31
+ - Every attempt runs inside its own jailed Firecracker microVM (`/dev/kvm`) managed via
32
+ `@push.rocks/smartvm` (`smartvm-helper`). No host Docker or Podman daemon is used or accepted.
33
+ - Job images must be Linux images pinned by an exact SHA-256 digest (or resolved from a
34
+ coordinator-supplied candidate binding). The runner pulls and verifies every manifest, config, and
35
+ layer digest directly via OCI Distribution v2, matching pull grants strictly by literal registry
36
+ and repository with redirect refusal and attempt-private caching for grant-backed images.
37
+ - In `oci` profile, every compiled step runs inside the microVM pivoted into the read-only OCI
38
+ rootfs (`/dev/vda`) as a numeric non-root user with all capabilities dropped, `no-new-privileges`,
39
+ private namespaces, and bounded vCPU, memory, PID, shared-memory (`/dev/shm`), time, and
40
+ writable-storage limits. In `vm` profile, steps run inside the microVM over an ephemeral writable
41
+ overlayfs above the read-only OCI rootfs and are torn down between steps via cgroup v2 kill.
42
+ - Dedicated builder runners (`--profile builder`) advertise only `oci-image` (never `oci` or `vm`),
43
+ run BuildKit inside a fresh Firecracker microVM with source-policy digest pinning, scoped `0400`
44
+ secrets and push credentials, attestations disabled, and digest-only push before calling
45
+ `PUT /jobs/{jobId}/attempts/{attemptId}/image`.
46
+ - By default the network mode is `none` (Firecracker microVM with no external connectivity). When
47
+ `--allow-egress` is enabled, the runner advertises `['none', 'egress']` and enforces `egress`
48
+ allowlists on the host via `EgressProxy` (DNS `A`/`AAAA`-only allowlist, private/link-local/
49
+ non-global/IPv4-mapped and custom CIDR blocking, TTL bindings, TLS SNI on 443, HTTP `Host` on 80).
50
+ - MicroVMs receive no host paths, runtime sockets, devices, or host namespaces. Their only
51
+ persistent writable workspace is `/workspace`, imported/exported by the static Rust
52
+ `runnerworkspace` guest PID 1 agent over vsock.
53
+ - `.npmrc` credentials from `npmGrants` are mounted read-only inside the guest and exposed via
54
+ `NPM_CONFIG_USERCONFIG`; every secret value and npm grant token is added to the attempt's
55
+ redaction set.
46
56
  - The attempt's redaction set holds every secret value, every npm grant token, and each line of a
47
57
  value containing a line terminator (CR LF, LF, or CR), leaving out members shorter than 8 UTF-8
48
58
  bytes; a short line of a multi-line value stays unmasked when printed on its own. Every member is
@@ -55,13 +65,12 @@ Requests directly.
55
65
 
56
66
  ## Requirements
57
67
 
58
- - Linux on x64 or arm64
68
+ - Linux on x64 or arm64 with `/dev/kvm`
69
+ - `smartvm-helper` (`@push.rocks/smartvm`) with Firecracker v1.17+ and a pinned Linux `vmlinux` kernel
59
70
  - For the npm package: Node.js 26.1 or later; the staging capacity check reads the filesystem
60
71
  fragment size, `statfs` `frsize`, which Node.js provides from 26.1 on. The executables embed
61
72
  Node.js 26.11.1.
62
73
  - pnpm 12
63
- - Docker or Podman on Linux
64
- - A rootless runtime by default
65
74
  - Rust and configured cross-compilers when building the packaged helpers from source
66
75
 
67
76
  ## Install
@@ -164,9 +173,16 @@ Create a private runner configuration:
164
173
  ```sh
165
174
  ship-zone-runner init \
166
175
  --control-plane https://foss.global \
167
- --runtime-path /usr/bin/docker
176
+ --kernel-path /var/lib/ship-zone-runner/vmlinux
168
177
  ```
169
178
 
179
+ Optional flags for `init`:
180
+
181
+ - `--profile workload|builder`: `workload` (default) advertises `['oci', 'vm']`; `builder`
182
+ advertises only `['oci-image']` and requires `--builder-rootfs-path <path>`.
183
+ - `--allow-egress`: enable host-enforced `egress` allowlist proxy and advertise `['none', 'egress']`.
184
+ - `--egress-blocked-cidr <cidr>` (repeatable): block additional destination CIDRs in `egress` mode.
185
+
170
186
  Register with a one-time bootstrap token, then start the daemon:
171
187
 
172
188
  ```sh
@@ -174,8 +190,8 @@ SHIP_RUNNER_BOOTSTRAP_TOKEN='<one-time token>' ship-zone-runner register
174
190
  ship-zone-runner run
175
191
  ```
176
192
 
177
- The runner uses `/dev/shm` for fail-closed host tmpfs verification before registration and must be
178
- trusted with unrestricted subprocess execution for the configured OCI runtime.
193
+ The runner uses `/dev/shm` for fail-closed host tmpfs verification before registration and talks to
194
+ `smartvm-helper` (`@push.rocks/smartvm`) to boot per-attempt Firecracker microVMs.
179
195
 
180
196
  Replace `run` with `once` to claim at most one job or `config` to print the effective configuration
181
197
  with credentials masked. Within this repository, `pnpm build` followed by
@@ -191,10 +207,10 @@ credential becomes active.
191
207
 
192
208
  The default policy includes:
193
209
 
194
- - rootless Docker at `/usr/bin/docker`;
195
- - labels for Linux, the current architecture, and OCI;
196
- - network `none` only;
197
- - job user `65532:65532`;
210
+ - Firecracker microVM isolation via `@push.rocks/smartvm` (`workload` profile: `oci` and `vm`);
211
+ - labels for Linux, the current architecture, and microVM;
212
+ - network `none` only (add `--allow-egress` to enable host-enforced `egress`);
213
+ - job user `65532:65532` (for `oci` steps);
198
214
  - a 4 GiB maximum logical workspace and 100,000 entries;
199
215
  - bounded source, artifact, cache, log, environment, and staging limits;
200
216
  - a 1 GiB free-space and 10,000-inode staging reserve.
@@ -272,14 +288,15 @@ every coordinator of major version 2. A leased job is accepted only when its `sp
272
288
  major version and is not newer than the implemented version; any other job is abandoned as
273
289
  `runner_error`.
274
290
 
275
- The runner advertises the `oci` profile, `container` isolation, the native `linux/<arch>` platform
276
- of its verified OCI engine, the `none` network mode, its transfer limits, `resources` maxima for
277
- memory, CPUs, PIDs, and shared memory, an empty `leaseFeatures` list because it uses no image pull
278
- grants, candidate bindings, or npm read grants, and `maximumTimeoutMs`, its configured
279
- `oci.maximumTimeoutMs`. It refuses, by abandoning the lease as `runner_error` before acceptance,
280
- every lease it cannot execute as specified: the `vm` and `oci-image` profiles, `microvm` isolation,
281
- `egress` networks, candidate images with `bindings`, image `grants`, jobs with `npmRead` and their
282
- `npmGrants`, and jobs whose `timeoutMs` exceeds `oci.maximumTimeoutMs`.
291
+ The runner advertises `microvm` isolation, its native `linux/<arch>` platform, `executionProfiles`
292
+ of `['oci', 'vm']` for a `workload` runner or `['oci-image']` for a dedicated `builder` runner,
293
+ `networks` of `['none']` (or `['none', 'egress']` when `--allow-egress` is enabled), its transfer
294
+ limits, `resources` maxima for memory, CPUs, PIDs, and shared memory,
295
+ `leaseFeatures: ['image-pull-grants', 'candidate-bindings', 'npm-read-grants']`, and
296
+ `maximumTimeoutMs`, its configured `oci.maximumTimeoutMs`. It refuses, by abandoning the lease as
297
+ `runner_error` before acceptance, any lease outside its advertised capabilities (for example
298
+ `container` isolation, non-Linux platforms, mismatched execution profile, or `timeoutMs` exceeding
299
+ `oci.maximumTimeoutMs`).
283
300
 
284
301
  The reserved step environment names are `SHIPZONE_CI_MATRIX_JSON` and `SHIPZONE_CI_INPUTS_JSON`,
285
302
  each carrying canonical RFC 8785 JSON. A job whose step environment defines any other
@@ -305,6 +322,7 @@ published OpenAPI component before it is sent, and every response before it is u
305
322
  | Source | `GET sources/{sha256}` | Immutable attempt-bound digest |
306
323
  | Artifact | `PUT jobs/{jobId}/attempts/{attemptId}/artifacts/{name}` | `transferRequestId` and metadata |
307
324
  | Cache | `GET/PUT jobs/{jobId}/attempts/{attemptId}/caches/{name}` | Fenced declaration and transfer ID |
325
+ | Record image | `PUT jobs/{jobId}/attempts/{attemptId}/image` | Fenced produced OCI image digest |
308
326
 
309
327
  Transient retry statuses are 429, 502, 503, and 504. Exact retries reuse the same request ID and
310
328
  canonical body. Request, response, archive, extracted-data, entry, and stream sizes are bounded.
@@ -322,7 +340,8 @@ import {
322
340
  ArtifactManager,
323
341
  CacheManager,
324
342
  defaultRunnerConfig,
325
- OciExecutor,
343
+ EgressProxy,
344
+ MicroVmExecutor,
326
345
  RunnerApiClient,
327
346
  ShipRunner,
328
347
  SourceWorkspaceManager,
@@ -334,11 +353,11 @@ verification, discovery, lifecycle, fencing, cleanup, and credential-persistence
334
353
  own the state directory first:
335
354
 
336
355
  ```ts
337
- import { OciExecutor, RunnerStateOwner, ShipRunner } from '@ship.zone/runner';
356
+ import { MicroVmExecutor, RunnerStateOwner, ShipRunner } from '@ship.zone/runner';
338
357
 
339
358
  const stateOwner = await RunnerStateOwner.acquire({ stateDirectory: config.stateDirectory });
340
359
  try {
341
- const executor = new OciExecutor(config, stateOwner);
360
+ const executor = new MicroVmExecutor(config, stateOwner);
342
361
  // new ShipRunner(config, { stateOwner, executor, ... }).run(...)
343
362
  } finally {
344
363
  await stateOwner.release();
@@ -354,18 +373,10 @@ pnpm test
354
373
  pnpm pack --dry-run
355
374
  ```
356
375
 
357
- `pnpm test` builds first: the tests take real state ownership with the host helper in `dist_rust/`.
358
- The real Docker integration is opt-in and requires a locally available digest-pinned Linux image:
359
-
360
- ```sh
361
- SHIP_RUNNER_OCI_TEST=1 \
362
- SHIP_RUNNER_OCI_IMAGE='alpine@sha256:<digest>' \
363
- pnpm exec tstest test/test.oci-executor.node.ts --verbose
364
- ```
365
-
366
- It verifies direct execution of an imported workspace file, shared multi-step state, helper
367
- ownership, selected export, hardlink rejection, inode exhaustion, and container/volume cleanup
368
- against the real runtime.
376
+ `pnpm test` builds first: the tests take real state ownership with the host helper in `dist_rust/`,
377
+ run the TypeScript unit/E2E suites (`test/test.*.node.ts`, including Firecracker microVM, OCI
378
+ registry, egress allowlist proxy, and dedicated `oci-image` builder tests), and run `cargo test`
379
+ for the static Rust `runnerworkspace` helper and guest PID 1 agent.
369
380
 
370
381
  ## License and Legal Information
371
382
 
package/rust/Cargo.lock CHANGED
@@ -88,6 +88,7 @@ dependencies = [
88
88
  name = "runnerworkspace"
89
89
  version = "0.1.0"
90
90
  dependencies = [
91
+ "libc",
91
92
  "nix",
92
93
  "serde",
93
94
  "serde_json",
package/rust/Cargo.toml CHANGED
@@ -6,9 +6,10 @@ license = "MIT"
6
6
  publish = false
7
7
 
8
8
  [dependencies]
9
+ libc = "0.2.189"
9
10
  nix = { version = "0.30.1", default-features = false, features = ["fs", "process", "signal", "user"] }
10
11
  serde = { version = "1.0.229", features = ["derive"] }
11
- serde_json = "1.0.149"
12
+ serde_json = { version = "1.0.149" }
12
13
 
13
14
  [target.'cfg(not(target_env = "msvc"))'.dependencies]
14
15
  tikv-jemallocator = { version = "0.7.0", features = ["background_threads"] }
@@ -0,0 +1,147 @@
1
+ use crate::Error;
2
+ use std::fs::{self, OpenOptions};
3
+ use std::io::{self, Write};
4
+ use std::os::unix::fs::OpenOptionsExt;
5
+ use std::path::Path;
6
+
7
+ const NEWC_MAGIC: &[u8; 6] = b"070701";
8
+ const MAXIMUM_INITRD_BINARY_BYTES: u64 = 64 * 1024 * 1024;
9
+
10
+ fn align4(len: usize) -> usize {
11
+ (4 - (len % 4)) % 4
12
+ }
13
+
14
+ fn write_newc_entry<W: Write>(
15
+ writer: &mut W,
16
+ ino: u32,
17
+ mode: u32,
18
+ nlink: u32,
19
+ name: &str,
20
+ data: &[u8],
21
+ ) -> io::Result<()> {
22
+ let name_bytes = name.as_bytes();
23
+ let namesize = name_bytes.len() + 1;
24
+ let filesize = data.len();
25
+ let header = format!(
26
+ "{}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}",
27
+ std::str::from_utf8(NEWC_MAGIC).unwrap_or("070701"),
28
+ ino,
29
+ mode,
30
+ 0u32, // uid
31
+ 0u32, // gid
32
+ nlink,
33
+ 0u32, // mtime (deterministic)
34
+ filesize as u32,
35
+ 0u32, // devmajor
36
+ 0u32, // devminor
37
+ 0u32, // rdevmajor
38
+ 0u32, // rdevminor
39
+ namesize as u32,
40
+ 0u32, // check
41
+ );
42
+ writer.write_all(header.as_bytes())?;
43
+ writer.write_all(name_bytes)?;
44
+ writer.write_all(&[0u8])?;
45
+ let header_pad = align4(110 + namesize);
46
+ if header_pad > 0 {
47
+ writer.write_all(&[0u8; 4][..header_pad])?;
48
+ }
49
+ if !data.is_empty() {
50
+ writer.write_all(data)?;
51
+ let data_pad = align4(filesize);
52
+ if data_pad > 0 {
53
+ writer.write_all(&[0u8; 4][..data_pad])?;
54
+ }
55
+ }
56
+ Ok(())
57
+ }
58
+
59
+ /// Builds a deterministic Linux `newc` CPIO initramfs containing `/init` (the static guest binary)
60
+ /// and the minimal mountpoint directories required during Firecracker guest boot.
61
+ pub fn build_initrd(binary_path: &Path, output_path: &Path) -> Result<u64, Error> {
62
+ if !binary_path.is_absolute() || !output_path.is_absolute() {
63
+ return Err(Error::new("initrd paths must be absolute"));
64
+ }
65
+ let metadata = fs::symlink_metadata(binary_path)
66
+ .map_err(|_| Error::new("unable to inspect guest binary for initrd"))?;
67
+ if !metadata.file_type().is_file() {
68
+ return Err(Error::new("guest binary must be a regular file"));
69
+ }
70
+ if metadata.len() == 0 || metadata.len() > MAXIMUM_INITRD_BINARY_BYTES {
71
+ return Err(Error::new("guest binary size is out of bounds"));
72
+ }
73
+ let binary_bytes =
74
+ fs::read(binary_path).map_err(|_| Error::new("unable to read guest binary for initrd"))?;
75
+
76
+ let mut buffer = Vec::with_capacity(binary_bytes.len() + 4096);
77
+ let dirs = [
78
+ "dev",
79
+ "proc",
80
+ "sys",
81
+ "tmp",
82
+ "workspace",
83
+ "oci-rootfs",
84
+ "run",
85
+ "mnt",
86
+ ];
87
+ let mut ino: u32 = 1;
88
+ for dir in dirs {
89
+ write_newc_entry(&mut buffer, ino, 0o040755, 2, dir, &[])
90
+ .map_err(|_| Error::new("unable to write initrd directory entry"))?;
91
+ ino += 1;
92
+ }
93
+ write_newc_entry(&mut buffer, ino, 0o100755, 1, "init", &binary_bytes)
94
+ .map_err(|_| Error::new("unable to write initrd /init entry"))?;
95
+ write_newc_entry(&mut buffer, 0, 0, 1, "TRAILER!!!", &[])
96
+ .map_err(|_| Error::new("unable to write initrd trailer"))?;
97
+
98
+ // Pad to 512-byte boundary for clean initrd loading.
99
+ let rem = buffer.len() % 512;
100
+ if rem != 0 {
101
+ buffer.resize(buffer.len() + (512 - rem), 0);
102
+ }
103
+
104
+ let mut out = OpenOptions::new()
105
+ .write(true)
106
+ .create(true)
107
+ .truncate(true)
108
+ .mode(0o600)
109
+ .open(output_path)
110
+ .map_err(|_| Error::new("unable to create initrd output file"))?;
111
+ out.write_all(&buffer)
112
+ .map_err(|_| Error::new("unable to write initrd output file"))?;
113
+ out.sync_all()
114
+ .map_err(|_| Error::new("unable to sync initrd output file"))?;
115
+ Ok(buffer.len() as u64)
116
+ }
117
+
118
+ #[cfg(test)]
119
+ mod tests {
120
+ use super::*;
121
+
122
+ #[test]
123
+ fn builds_deterministic_newc_initrd() {
124
+ let dir = std::env::temp_dir().join(format!(
125
+ "runnerworkspace-cpio-test-{}",
126
+ std::process::id()
127
+ ));
128
+ let _ = fs::remove_dir_all(&dir);
129
+ fs::create_dir_all(&dir).unwrap();
130
+ let bin = dir.join("fake-init");
131
+ let out1 = dir.join("initrd1.cpio");
132
+ let out2 = dir.join("initrd2.cpio");
133
+ fs::write(&bin, b"#!/bin/sh\necho hi\n").unwrap();
134
+
135
+ let size1 = build_initrd(&bin, &out1).unwrap();
136
+ let size2 = build_initrd(&bin, &out2).unwrap();
137
+ assert_eq!(size1, size2);
138
+ let bytes1 = fs::read(&out1).unwrap();
139
+ let bytes2 = fs::read(&out2).unwrap();
140
+ assert_eq!(bytes1, bytes2);
141
+ assert!(bytes1.starts_with(b"070701"));
142
+ assert!(bytes1.windows(10).any(|w| w == b"TRAILER!!!"));
143
+ assert_eq!(bytes1.len() % 512, 0);
144
+
145
+ let _ = fs::remove_dir_all(&dir);
146
+ }
147
+ }