hyperhive/hivectl/src/client.rs
atlas f108c72f25 hivectl: say which of the three socket failures actually happened
`hivectl open forge` on a host where the daemon is fine and the socket is
fine printed "could not reach the hive-c0re daemon for URLs — is hive-c0re
running?". It was running. The operator was not in `hive-admin` in that
shell, and the connect got EACCES.

The message was a guess, not a diagnosis, because `query_hive_urls`
returned `Option` and threw the cause away with `.ok()`. Three different
failures — not in the group, no socket at all, nobody listening — all
arrived as the same sentence, and only one of the three is fixed by
looking at the daemon.

Classify the connect error in `client::request`, which every
daemon-assisted verb goes through, and keep the io error as the anyhow
cause so the output reads fix-first. EACCES names `hive-admin`,
`services.hyperhive.adminUsers`, and — the part that actually bites — the
re-login, since secondary group membership is only applied at login, so a
shell opened before the grant still cannot connect. ENOENT and
ECONNREFUSED point at the units instead.

Then stop discarding it: `query_hive_urls` returns `Result<Option<_>>`,
`open` and `require_hive_domain` propagate, and `daemon_request` drops its
own "connect to daemon socket" context, which only buried the actionable
line under a vaguer one. `wg init`'s domain lookup stays best-effort by
an explicit `.ok().flatten()` rather than by accident.

Same footgun `agent_exists` was already fixed for: a permission error
collapsed into a value that reads as a different, wrong story.
2026-07-26 17:35:44 +02:00

126 lines
5 KiB
Rust

//! Host admin socket client: one request/response round trip over
//! `/run/hyperhive/host.sock`.
//!
//! Connect failures are classified into an actionable message before they
//! reach the operator (see [`connect_hint`]) — the three ways this fails
//! (not in `hive-admin`, no socket, nobody listening) need three different
//! fixes, and the raw `Permission denied (os error 13)` names none of them.
use std::io::ErrorKind;
use std::path::Path;
use anyhow::{Result, bail};
use hive_host_sock::{HostRequest, HostResponse};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::UnixStream;
/// Turn a socket-connect `io::ErrorKind` into a message that names the fix.
///
/// The interesting one is `PermissionDenied`: the socket is `0660
/// root:hive-admin` behind a `0751` runtime dir, so a non-member gets EACCES
/// on connect — and so does a *member* whose shell predates the group being
/// granted, because secondary group membership is only applied at login. That
/// second case is the one that reads as "the daemon is down" and isn't.
fn connect_hint(kind: ErrorKind, socket: &Path) -> String {
let path = socket.display();
match kind {
ErrorKind::PermissionDenied => format!(
"permission denied opening the host admin socket {path} — reaching it requires \
membership in the `hive-admin` group. Add your user to \
`services.hyperhive.adminUsers`, then log out and back in: secondary group \
membership is applied at login, so a shell opened before the change still \
cannot connect. `id -nG` shows what the running shell actually has; \
`newgrp hive-admin` picks the group up without a full re-login"
),
ErrorKind::NotFound => format!(
"no socket at {path} — hive-c0re is not running, or it binds somewhere else \
(`--socket`). Check `systemctl status hive-c0re.socket hive-c0re.service`"
),
ErrorKind::ConnectionRefused => format!(
"nothing is listening on {path} — the socket exists but the daemon behind it \
is down. Check `systemctl status hive-c0re.service` and \
`journalctl -u hive-c0re`"
),
_ => format!("could not connect to the hive-c0re host admin socket {path}"),
}
}
pub async fn request(socket: &Path, req: HostRequest) -> Result<HostResponse> {
let stream = match UnixStream::connect(socket).await {
Ok(stream) => stream,
// Keep the io error as the cause and put the actionable line on top,
// so `Error: <hint>` / `Caused by: <errno>` reads fix-first.
Err(e) => {
let hint = connect_hint(e.kind(), socket);
return Err(anyhow::Error::new(e).context(hint));
}
};
let (read, mut write) = stream.into_split();
let mut payload = serde_json::to_string(&req)?;
payload.push('\n');
write.write_all(payload.as_bytes()).await?;
write.flush().await?;
let mut reader = BufReader::new(read);
let mut line = String::new();
reader.read_line(&mut line).await?;
if line.is_empty() {
bail!("server closed connection without responding");
}
let resp: HostResponse = serde_json::from_str(line.trim())?;
Ok(resp)
}
#[cfg(test)]
mod tests {
use super::{ErrorKind, Path, connect_hint};
fn hint(kind: ErrorKind) -> String {
connect_hint(kind, Path::new("/run/hyperhive/host.sock"))
}
/// EACCES is an operator-side fix, and the non-obvious half is the
/// re-login — so both the group and the login requirement must appear,
/// and it must not send the operator off checking a daemon that is fine.
#[test]
fn permission_denied_names_the_group_and_the_relogin() {
let h = hint(ErrorKind::PermissionDenied);
assert!(h.contains("hive-admin"), "{h}");
assert!(h.contains("adminUsers"), "{h}");
assert!(h.contains("log out"), "{h}");
assert!(
!h.contains("not running"),
"EACCES must not blame the daemon: {h}"
);
}
/// The inverse: a missing socket is a daemon-side problem, so it must not
/// send the operator chasing group membership.
#[test]
fn missing_socket_blames_the_daemon_not_the_operator() {
let h = hint(ErrorKind::NotFound);
assert!(h.contains("not running"), "{h}");
assert!(!h.contains("hive-admin"), "{h}");
}
#[test]
fn refused_socket_points_at_the_service_not_the_group() {
let h = hint(ErrorKind::ConnectionRefused);
assert!(h.contains("nothing is listening"), "{h}");
assert!(!h.contains("hive-admin"), "{h}");
}
#[test]
fn every_hint_names_the_socket_path() {
for kind in [
ErrorKind::PermissionDenied,
ErrorKind::NotFound,
ErrorKind::ConnectionRefused,
ErrorKind::BrokenPipe,
] {
let h = hint(kind);
assert!(h.contains("/run/hyperhive/host.sock"), "{kind:?}: {h}");
}
}
}