microsandbox-rb 0.17.4 → 0.18.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.
@@ -8,7 +8,7 @@ description = "Ruby SDK native extension for microsandbox — secure, fast micro
8
8
  # returns this via env!("CARGO_PKG_VERSION") and version_spec.rb asserts equality.
9
9
  # The core-crate dependencies below stay on their own tag, which is
10
10
  # Microsandbox::RUNTIME_VERSION and moves independently of this version.
11
- version = "0.17.4"
11
+ version = "0.18.0"
12
12
  authors = ["Super Rad Company <development@superrad.company>"]
13
13
  repository = "https://github.com/superradcompany/microsandbox"
14
14
  license = "Apache-2.0"
@@ -45,25 +45,27 @@ libc = "0.2"
45
45
  # sibling checkout, use the `paths` override in `.cargo/config.toml` (see
46
46
  # `.cargo/config.toml.example`).
47
47
  #
48
- # Features are listed explicitly (default-features = false) so the SDK crate's
49
- # own "prebuilt" feature stays OFF: that feature makes its build.rs download
50
- # the msb + libkrunfw *host runtime* into ~/.microsandbox at compile time. This
51
- # gem is SDK-only — the host runtime comes from the companion
52
- # `microsandbox-rb-binaries` gem (see binaries/) or, as the lowest tier, the
53
- # first-use download into ~/.microsandbox (`setup::install`, which is not
54
- # gated on "prebuilt"). "net"/"ssh"/"keyring" are the features the official
55
- # SDKs ship with.
56
- microsandbox = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.6.18", default-features = false, features = ["keyring", "net", "ssh"] }
57
- microsandbox-network = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.6.18" }
58
- # The *guest* agent (`agentd`, PID 1 inside every microVM) is embedded into the
59
- # extension by microsandbox-filesystem's build.rs, which without its "prebuilt"
60
- # feature demands a locally built `build/agentd` (workspace-only, `just
61
- # build-deps`). Enable that one sub-feature directly — via microsandbox-runtime,
62
- # whose "prebuilt" is exactly `microsandbox-filesystem/prebuilt` — so the
63
- # prebuilt agentd for the target arch is fetched (same behaviour as before)
64
- # while the SDK-level msb download above stays off. Feature unification means
65
- # this adds no new crates; keep it on the same tag as the deps above.
66
- microsandbox-runtime = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.6.18", default-features = false, features = ["prebuilt"] }
48
+ # Features are listed explicitly (default-features = false). Two SDK features
49
+ # must stay OFF: "download-binaries" (its build.rs downloads the msb + libkrunfw
50
+ # *host runtime* into ~/.microsandbox at compile time) and "embed-binaries"
51
+ # (`include_bytes!` of the whole runtime tarball). This gem is SDK-only — the
52
+ # host runtime comes from the companion `microsandbox-rb-binaries` gem (see
53
+ # binaries/) or, as the lowest tier, the first-use download into
54
+ # ~/.microsandbox (`setup::install_runtime`, which is not gated on either
55
+ # feature). The *guest* agent (`agentd`) ships inside `msb` itself (the msb
56
+ # release build embeds it), so the SDK embeds nothing. "cloud"/"keyring"/
57
+ # "local"/"net"/"ssh" are the features the official SDKs ship with.
58
+ #
59
+ # `microsandbox-network` is a direct dependency only for its builder/config
60
+ # types; `default-features = false` keeps its packet-processing engine out of
61
+ # this extension (the SDK depends on it the same way).
62
+ microsandbox = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.7.14", default-features = false, features = ["cloud", "keyring", "local", "net", "ssh"] }
63
+ microsandbox-network = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.7.14", default-features = false }
64
+ # `microsandbox-utils` is a direct dependency only for `msb_binary_filename` /
65
+ # `libkrunfw_filename`, which the SDK does not re-export: the runtime-home
66
+ # self-check (`Native.runtime_home_pair`) must name exactly the files the
67
+ # resolver's `runtime_in_home` expects. Already in the dependency graph.
68
+ microsandbox-utils = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.7.14" }
67
69
 
68
70
  # Async core bridged to Ruby's synchronous API via a blocking tokio runtime.
69
71
  tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] }
@@ -4,11 +4,11 @@ require "mkmf"
4
4
  require "rb_sys/mkmf"
5
5
  require "shellwords"
6
6
 
7
- # Preflight: the embedded microsandbox core is edition 2024 and pulls smoltcp,
8
- # which sets a Minimum Supported Rust Version of 1.91. An older rustc (commonly
9
- # Homebrew's, which shadows a newer rustup on PATH and ignores this gem's
10
- # rust-toolchain.toml) fails deep in the build with a cryptic "rustc X is not
11
- # supported by smoltcp" error. Detect it up front and explain the fix instead.
7
+ # Preflight: the embedded microsandbox core is edition 2024 and (since runtime
8
+ # v0.7) pulls sea-orm 2 / sqlx 0.9, which set a Minimum Supported Rust Version
9
+ # of 1.94. An older rustc (commonly Homebrew's, which shadows a newer rustup on
10
+ # PATH and ignores this gem's rust-toolchain.toml) fails deep in the build with
11
+ # a cryptic "rustc X is not supported by <crate>" error. Detect it up front and explain the fix instead.
12
12
  #
13
13
  # Probe the *same* rustc the build will invoke. create_rust_makefile drives the
14
14
  # build through `cargo`, and cargo resolves its compiler exactly as: the `RUSTC`
@@ -22,7 +22,7 @@ require "shellwords"
22
22
  # neither false-passes (the trap of checking the cargo sibling, which stays a
23
23
  # valid rustup shim while the build silently uses the stale PATH rustc) nor
24
24
  # false-aborts (when `RUSTC` points at a newer compiler than the PATH `rustc`).
25
- MSRV = Gem::Version.new("1.91")
25
+ MSRV = Gem::Version.new("1.94")
26
26
 
27
27
  def build_rustc
28
28
  rustc = ENV["RUSTC"].to_s.strip
@@ -67,6 +67,7 @@ end
67
67
  #
68
68
  # Cargo features for the embedded microsandbox runtime (e.g. "ssh") are enabled
69
69
  # directly on the dependency in ext/microsandbox/Cargo.toml, mirroring the official
70
- # Python/Node SDKs. The crate's "prebuilt" default feature provisions the msb
71
- # runtime + libkrunfw into ~/.microsandbox at build time.
70
+ # Python/Node SDKs, with default features off: the build provisions nothing. The
71
+ # host runtime (msb + libkrunfw, which embeds the guest agent) comes from the
72
+ # microsandbox-rb-binaries gem or the first-use install into the runtime home.
72
73
  create_rust_makefile("microsandbox/microsandbox_rb")
@@ -77,7 +77,7 @@ fn build_backend(
77
77
  profile: Option<String>,
78
78
  ) -> Result<Arc<dyn Backend>, MicrosandboxError> {
79
79
  match kind.trim().to_ascii_lowercase().as_str() {
80
- "local" => Ok(Arc::new(microsandbox::LocalBackend::lazy())),
80
+ "local" => Ok(Arc::new(microsandbox::LocalBackend::lazy()?)),
81
81
  "cloud" => {
82
82
  let cloud = match profile {
83
83
  Some(profile) => microsandbox::CloudBackend::from_profile(&profile),
@@ -408,15 +408,28 @@ fn pop_default_backend(token: u32) -> Result<(), Error> {
408
408
  Ok(())
409
409
  }
410
410
 
411
- /// The active default backend kind: `"local"` or `"cloud"`. First call lazily
412
- /// resolves the env/profile/config ladder. Synchronous (an `RwLock` read).
413
- fn default_backend_kind() -> Result<String, Error> {
411
+ /// The active default backend's description, mapped to a Ruby error when the
412
+ /// ambient selection is misconfigured. Since runtime v0.7.x a backend that
413
+ /// failed to resolve reports `BackendKind::Cloud` from `kind()` (upstream's
414
+ /// "safe intent marker"), so `kind()` alone would misreport a configuration
415
+ /// error as a cloud backend; `info()` returns the error instead.
416
+ fn active_backend_info() -> Result<microsandbox::BackendInfo, Error> {
414
417
  ensure_this_process_backend()?;
415
- Ok(match microsandbox::default_backend().kind() {
418
+ microsandbox::default_backend_info().map_err(error::to_ruby)
419
+ }
420
+
421
+ fn kind_str(kind: microsandbox::BackendKind) -> &'static str {
422
+ match kind {
416
423
  microsandbox::BackendKind::Local => "local",
417
424
  microsandbox::BackendKind::Cloud => "cloud",
418
425
  }
419
- .to_string())
426
+ }
427
+
428
+ /// The active default backend kind: `"local"` or `"cloud"`. First call lazily
429
+ /// resolves the env/profile/config ladder; a misconfigured selection raises
430
+ /// (see `active_backend_info`). Synchronous (an `RwLock` read).
431
+ fn default_backend_kind() -> Result<String, Error> {
432
+ Ok(kind_str(active_backend_info()?.kind).to_string())
420
433
  }
421
434
 
422
435
  /// Secret-safe description of the active default backend (v0.6.9):
@@ -425,16 +438,9 @@ fn default_backend_kind() -> Result<String, Error> {
425
438
  /// included. Like `default_backend_kind`, the first call freezes ambient
426
439
  /// env/profile resolution for the process.
427
440
  fn default_backend_info() -> Result<magnus::RHash, Error> {
428
- ensure_this_process_backend()?;
429
- let info = microsandbox::default_backend_info();
441
+ let info = active_backend_info()?;
430
442
  let hash = crate::runtime::ruby().hash_new();
431
- let _ = hash.aset(
432
- "kind",
433
- match info.kind {
434
- microsandbox::BackendKind::Local => "local",
435
- microsandbox::BackendKind::Cloud => "cloud",
436
- },
437
- );
443
+ let _ = hash.aset("kind", kind_str(info.kind));
438
444
  let _ = hash.aset("api_url", info.api_url);
439
445
  let _ = hash.aset("source", info.source.as_str());
440
446
  let _ = hash.aset("profile", info.profile);
@@ -16,7 +16,10 @@ use crate::runtime::ruby;
16
16
  fn class_name(err: &MicrosandboxError) -> &'static str {
17
17
  use MicrosandboxError::*;
18
18
  match err {
19
- InvalidConfig(_) => "InvalidConfigError",
19
+ // v0.7: a restore whose captured mounts/disks have no destination
20
+ // binding (the message names them and the remedy). Every other SDK
21
+ // reports it as an invalid configuration.
22
+ InvalidConfig(_) | MissingRestoreBindings { .. } => "InvalidConfigError",
20
23
  SandboxNotFound(_) => "SandboxNotFoundError",
21
24
  SandboxAlreadyExists(_) => "SandboxAlreadyExistsError",
22
25
  SandboxStillRunning(_) => "SandboxStillRunningError",
@@ -78,6 +81,23 @@ fn class_name(err: &MicrosandboxError) -> &'static str {
78
81
  // ENTRYPOINT+CMD provide no executable command. Mirrors the Python
79
82
  // SDK's `NoDefaultCommandError`.
80
83
  NoDefaultCommand => "NoDefaultCommandError",
84
+ // v0.7: host runtime resolution. `RuntimeNotInstalled` = no runtime
85
+ // pair anywhere; `RuntimeIncomplete` = the selected pair is partial or
86
+ // an explicit `MSB_PATH`/`runtime_path` has no matching libkrunfw.
87
+ // Mirrors the Python SDK.
88
+ RuntimeNotInstalled(_) => "RuntimeNotInstalledError",
89
+ RuntimeIncomplete(_) => "RuntimeIncompleteError",
90
+ // v0.7: a graceful stop did not complete within its budget (no kill was
91
+ // requested). `SandboxStopTimedOut` has no raise site at v0.7.14; the
92
+ // class is reserved so callers can rescue it already.
93
+ StopTimeout { .. } => "StopTimeoutError",
94
+ SandboxStopTimedOut { .. } => "SandboxStopTimedOutError",
95
+ // v0.7: a full checkpoint was captured but the source failed to
96
+ // recover; built with structured attributes by `to_ruby` below.
97
+ SnapshotSourceRecovery(_) => "SnapshotSourceRecoveryError",
98
+ // v0.7 (cloud only): a modification was saved but is not in effect, or
99
+ // its outcome is unknown. `cause` never holds a secret value.
100
+ ModificationNotConfirmed { .. } => "ModificationNotConfirmedError",
81
101
  _ => "Error",
82
102
  }
83
103
  }
@@ -108,6 +128,13 @@ pub fn to_ruby(err: MicrosandboxError) -> Error {
108
128
  return unsupported_error(&ruby, &ruby_api_name(*op), &ruby_hint(reason));
109
129
  }
110
130
 
131
+ // `SnapshotSourceRecovery` keeps its structured recovery locator (where the
132
+ // checkpoint and any published artifact are) as attributes, so callers never
133
+ // parse the message. Mirrors the Python SDK's keyword attributes.
134
+ if let MicrosandboxError::SnapshotSourceRecovery(recovery) = &err {
135
+ return source_recovery_error(&ruby, &message, recovery);
136
+ }
137
+
111
138
  match exception_class(&ruby, class_name(&err)) {
112
139
  Some(class) => Error::new(class, message),
113
140
  None => Error::new(ruby.exception_runtime_error(), message),
@@ -122,6 +149,37 @@ pub fn local_only(name: &str) -> Error {
122
149
  unsupported_error(&ruby(), name, "use a local backend")
123
150
  }
124
151
 
152
+ /// Build a `Microsandbox::SnapshotSourceRecoveryError` whose attributes come
153
+ /// from the core's serialized recovery record (`source_sandbox`,
154
+ /// `checkpoint_id`, `checkpoint_root`, `checkpoint_path`, `artifact`, `detail`,
155
+ /// `publication_error`). Falls back to a message-only error, which still names
156
+ /// the locator, if the record cannot be attached.
157
+ fn source_recovery_error(
158
+ ruby: &Ruby,
159
+ message: &str,
160
+ recovery: &microsandbox::SnapshotSourceRecoveryError,
161
+ ) -> Error {
162
+ let Some(class) = exception_class(ruby, "SnapshotSourceRecoveryError") else {
163
+ return Error::new(ruby.exception_runtime_error(), message.to_string());
164
+ };
165
+ let Ok(details) = serde_json::to_value(recovery) else {
166
+ return Error::new(class, message.to_string());
167
+ };
168
+ match class
169
+ .as_value()
170
+ .funcall::<_, _, magnus::Exception>("new", (message,))
171
+ {
172
+ Ok(exc) => {
173
+ let _ = exc.funcall::<_, _, magnus::Value>(
174
+ "__apply_recovery",
175
+ (crate::conv::json_to_ruby(&details),),
176
+ );
177
+ exc.into()
178
+ }
179
+ Err(_) => Error::new(class, message.to_string()),
180
+ }
181
+ }
182
+
125
183
  /// Build a `Microsandbox::UnsupportedError` carrying the rendered message and
126
184
  /// the structured `@operation` / `@hint` attributes.
127
185
  fn unsupported_error(ruby: &Ruby, operation: &str, hint: &str) -> Error {
@@ -1,12 +1,14 @@
1
1
  //! Pin caller-supplied host paths when a sandbox is created (GHSA-mcw9-9rf6-p4rm).
2
2
  //!
3
- //! The pinned core stores a relative host path exactly as written and resolves
4
- //! it against the working directory of whichever process later starts the
5
- //! sandbox, so restarting from another directory mounts a different host
6
- //! directory than the one the caller meant. Upstream fixed that in v0.7.6 by
7
- //! resolving host paths once, at the local-backend boundary, before the
8
- //! configuration is persisted. This module applies the same resolution in the
9
- //! binding so it also holds on the runtime this gem pins.
3
+ //! Runtimes before v0.7.6 stored a relative host path exactly as written and
4
+ //! resolved it against the working directory of whichever process later
5
+ //! started the sandbox, so restarting from another directory mounted a
6
+ //! different host directory than the one the caller meant. Upstream fixed that
7
+ //! in v0.7.6 by resolving host paths once, at the local-backend boundary,
8
+ //! before the configuration is persisted. The binding added the same
9
+ //! resolution in 0.17.1 and keeps it: it is idempotent with upstream's (an
10
+ //! anchored path is absolute, which upstream leaves alone), so the contract
11
+ //! does not depend on which layer does it.
10
12
  //!
11
13
  //! Rules, matching upstream's `resolve_host_paths`:
12
14
  //!
@@ -18,6 +20,9 @@
18
20
  //! - Only create-time input is resolved. A sandbox that was already persisted
19
21
  //! with a relative path keeps it; nothing here rewrites saved state.
20
22
  //!
23
+ //! The same anchoring applies to `Sandbox.restore`'s snapshot path and
24
+ //! `snapshot_base:` (upstream resolves those at the same boundary).
25
+ //!
21
26
  //! A vsock `host_socket` is deliberately not routed through here: the core
22
27
  //! refuses a relative one outright ("vsock host path must be absolute") before
23
28
  //! anything is persisted, so there is no stored relative path to pin.
@@ -46,7 +51,10 @@ pub struct HostPaths {
46
51
  }
47
52
 
48
53
  impl HostPaths {
49
- /// Capture which backend the create call is about to dispatch to.
54
+ /// Capture which backend the create call is about to dispatch to. A
55
+ /// misconfigured selection reports `Cloud` from `kind()` (runtime v0.7.x),
56
+ /// so paths pass through untouched — and the create itself then fails with
57
+ /// that configuration error before anything is persisted.
50
58
  pub fn for_default_backend() -> Result<Self, Error> {
51
59
  crate::backend::ensure_this_process_backend()?;
52
60
  Ok(Self {
@@ -69,6 +77,27 @@ impl HostPaths {
69
77
  })
70
78
  }
71
79
 
80
+ /// Pin a `Sandbox.restore` snapshot selector (or `snapshot_base:`) when it
81
+ /// names a path rather than an id, a `group:member` or a digest. Mirrors
82
+ /// v0.7.14's `resolve_snapshot_reference` for an auto reference: a value
83
+ /// that contains `/` or starts with `.` or `~` (the core's
84
+ /// `looks_like_path`), or that names an existing file (a bare archive
85
+ /// name in the current directory), is a path. (The core does not expand
86
+ /// `~`; like any other relative path it is anchored as written.)
87
+ pub fn pin_snapshot(self, raw: String) -> Result<String, Error> {
88
+ let path_like = raw.contains('/')
89
+ || raw.starts_with('.')
90
+ || raw.starts_with('~')
91
+ || std::path::Path::new(&raw).is_file();
92
+ if !path_like {
93
+ return Ok(raw);
94
+ }
95
+ Ok(self
96
+ .pin(raw, "snapshot path")?
97
+ .to_string_lossy()
98
+ .into_owned())
99
+ }
100
+
72
101
  /// Classify `image:` text the way the core does and pin it when it names a
73
102
  /// relative local path (a directory rootfs or a disk image).
74
103
  pub fn pin_image(self, text: String) -> Result<Image, Error> {
@@ -86,24 +115,4 @@ impl HostPaths {
86
115
  Ok(Image::Text(text))
87
116
  }
88
117
  }
89
-
90
- /// Pin a `from_snapshot:` value when it is a path rather than a snapshot
91
- /// name or digest. Uses the core's own name-vs-path split: a value that
92
- /// contains `/` or starts with `.` or `~` is a path. (The core does not
93
- /// expand `~`; like any other relative path it is anchored as written.)
94
- pub fn pin_snapshot(self, raw: String) -> Result<String, Error> {
95
- let path_like = raw.contains('/') || raw.starts_with('.') || raw.starts_with('~');
96
- if !self.local || !path_like {
97
- return Ok(raw);
98
- }
99
- self.pin(raw, "snapshot path")?
100
- .into_os_string()
101
- .into_string()
102
- .map_err(|path| {
103
- error::to_ruby(MicrosandboxError::InvalidConfig(format!(
104
- "cannot resolve snapshot path {}: the current directory is not valid UTF-8",
105
- PathBuf::from(path).display()
106
- )))
107
- })
108
- }
109
118
  }