Skip to content
Merged
13 changes: 13 additions & 0 deletions crates/minimald/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,19 @@ pub struct ChannelConfig {
pub(crate) pty: Option<RequestedPty>,
}

/// The fix to run for a host that refuses the unprivileged user namespace
/// every session sandbox needs. One source for the daemon's startup warning
/// and the spawn-failed attach error, so both name the same remediation:
/// the daemon's own remedy for the restriction, the text the create gate's
/// refusal carries too.
#[cfg(target_os = "linux")]
#[must_use]
pub fn userns_restriction_fix(restriction: sandbox2::UsernsRestriction) -> String {
restriction.remedy(sandbox2::RemedyTarget::Daemon {
bin: &server::this_daemon_path(),
})
}

#[cfg(test)]
mod integration_naming_convention {
//! Guards the integration-test auto-discovery contract (root variant). The
Expand Down
4 changes: 1 addition & 3 deletions crates/minimald/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1107,9 +1107,7 @@ async fn async_main() -> Result<(), MainError> {
} else if let Some(restriction) = sandbox2::user_namespaces_restriction() {
tracing::warn!(
reason = %restriction,
fix = restriction.remedy(sandbox2::RemedyTarget::Daemon {
bin: &minimald::server::this_daemon_path(),
}),
fix = minimald::userns_restriction_fix(restriction),
docs = "https://docs.minimal.dev/reference/linux-host-setup",
"sessions will fail to start: this host refuses the unprivileged user \
namespace every session sandbox needs"
Expand Down
54 changes: 51 additions & 3 deletions crates/minimald/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,52 @@ mod helpers;

pub(crate) use helpers::*;

/// Why this host refuses the unprivileged user namespace every session
/// sandbox needs, with the fix to run — `None` when nothing is visible.
///
/// Probed at failure time rather than reused from the daemon's startup
/// probe: the sysctls it reads take effect live (the host-setup doc's
/// `sysctl -w` fix needs no daemon restart), so a startup verdict could
/// name a restriction already lifted, or miss one set since. The probe is a
/// handful of `/proc` reads on a path that has already failed.
#[cfg(target_os = "linux")]
fn userns_spawn_hint() -> Option<String> {
sandbox2::user_namespaces_restriction()
.map(|r| format!("{r} — fix: {}", crate::userns_restriction_fix(r)))
}

/// Off Linux no user namespace is involved, so there is nothing to name.
#[cfg(not(target_os = "linux"))]
fn userns_spawn_hint() -> Option<String> {
None
}

/// The error a failed host attach surfaces: the bare symptom, plus the
/// userns diagnosis and fix when there is one (see [`userns_spawn_hint`]).
/// A host that dies in the launch-to-attach window on a userns-restricted
/// host (stock Ubuntu 24.04+) otherwise leaves the client with a symptom
/// that names neither the restriction nor the fix.
fn spawn_failed_error(userns_spawn_hint: Option<&str>) -> std::io::Error {
with_userns_hint(
std::io::Error::other("session host exited before its channel could attach"),
userns_spawn_hint,
)
}

/// `err` with the userns diagnosis and fix appended when there is one,
/// keeping its kind. A launch that fails outright on a userns-restricted
/// host (an own-ip session wiring the netns of a child that already died on
/// its `uid_map` write) otherwise reaches the client with the same
/// cause-less symptom as a host that dies before its attach. The probe
/// sees the host, not this error, so the hint is labelled the likely cause
/// and the error's own message stays first.
fn with_userns_hint(err: std::io::Error, userns_spawn_hint: Option<&str>) -> std::io::Error {
match userns_spawn_hint {
Some(hint) => std::io::Error::new(err.kind(), format!("{err} — likely cause: {hint}")),
None => err,
}
}

/// An error that occurred when attaching to a running session/its-shell.
#[derive(Debug)]
pub enum AttachError {
Expand Down Expand Up @@ -4358,7 +4404,9 @@ impl Session {
}
None => (None, spawn.await),
};
let (host, task, host_ip_enforcement) = spawned.map_err(AttachError::SpawnFailed)?;
let (host, task, host_ip_enforcement) = spawned.map_err(|e| {
AttachError::SpawnFailed(with_userns_hint(e, userns_spawn_hint().as_deref()))
})?;
Comment thread
norrietaylor marked this conversation as resolved.
Resolved
// The confirmation was a read, not a reservation: the VM host daemon
// may have withdrawn the row at its grace's end between that read
// and this launch (NET-138). Read it again now the new host is up,
Expand Down Expand Up @@ -4702,8 +4750,8 @@ impl Session {
Ok(()) => Ok(()),
// The host's loop ended before the attach could be delivered.
Err(session_host::HostAttachError::Closed(..)) => {
return Err(AttachError::SpawnFailed(std::io::Error::other(
"session host exited before its channel could attach",
return Err(AttachError::SpawnFailed(spawn_failed_error(
userns_spawn_hint().as_deref(),
)));
}
// The host is alive but its mailbox stayed full past the attach
Expand Down
45 changes: 45 additions & 0 deletions crates/minimald/src/session/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,51 @@ fn inherited_session_env_prefix_not_substring() {
);
}

/// A spawn failure with no probe diagnosis keeps the bare symptom — the
/// exact message the pre-hint daemon surfaced, so an unrestricted host (or
/// an off-Linux one, where no probe runs) sees no change.
#[test]
fn spawn_failed_error_without_a_hint_keeps_the_bare_symptom() {
assert_eq!(
super::spawn_failed_error(None).to_string(),
"session host exited before its channel could attach"
);
}

/// A spawn failure with a probe diagnosis names it: the symptom stays (the
/// host did exit before attaching) and the restriction + fix the startup
/// probe logged follow it, so the error a client sees on a userns-
/// restricted host explains itself.
#[test]
fn spawn_failed_error_with_a_hint_names_the_restriction_and_fix() {
let hint = "kernel.apparmor_restrict_unprivileged_userns=1 and this \
process is unconfined — fix: install minimald's AppArmor \
profile (one-time, needs root)";
let msg = super::spawn_failed_error(Some(hint)).to_string();
assert!(
msg.starts_with("session host exited before its channel could attach — "),
"the symptom must stay the error's lead: {msg}"
);
assert!(msg.contains(hint), "the diagnosis must travel whole: {msg}");
}

/// A launch failure keeps its own message and kind, and gains the
/// diagnosis only when the probe found one.
#[test]
fn with_userns_hint_appends_the_diagnosis_and_keeps_the_kind() {
let base = || std::io::Error::new(std::io::ErrorKind::PermissionDenied, "uid_map write");
let bare = super::with_userns_hint(base(), None);
assert_eq!(bare.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(bare.to_string(), "uid_map write");

let hinted = super::with_userns_hint(base(), Some("restricted — fix: x"));
assert_eq!(hinted.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(
hinted.to_string(),
"uid_map write — likely cause: restricted — fix: x"
);
}

/// Reads the session record for `id`, or `None` once it has been deleted.
async fn record_exists(client: &mut TestClient, id: SessionId) -> bool {
client
Expand Down
Loading