diff --git a/CLAUDE.md b/CLAUDE.md index 2f2805bfb0..afa2d63103 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,7 +17,7 @@ Flutter app for managing servers, in a Rust workspace monorepo. Feature notes li - `flutter test --timeout 30s` (`make test-one TEST=...`), `cargo test --workspace`. - Kotlin: from `android/`, `./gradlew :app:testDebugUnitTest -x :app:compileFlutterBuildDebug`. - `test/unit/` is split by **feature** (`ssh/`, `terminal/`, `file/`, `server/`, `virt/`, `monitor/`, …); `store/` is storage infrastructure, `app/` what belongs to no feature. Helpers: `test/helpers/`. -- Opt-in e2e, skipped when unset: `SBM_E2E_SSH_HOST` in `.env` + `cargo test -p sbm_parser --test ssh_e2e -- --ignored` (libvirt: `-p sbm_virt`); RDP: `SBM_E2E_RDP_{HOST,PORT,USER,PASSWORD}` + `cargo test -p sbm_ffi --lib rdp_e2e -- --ignored` (an alpine `xrdp xorgxrdp` container serves); `flutter test test/e2e/app_mcp_real_test.dart` (the app's MCP server over real SSH, through `$SSH_AUTH_SOCK`'s agent); `flutter test test/e2e/virt_real_test.dart` (variables in its header; dartssh2 has no ssh-agent, so use `SBM_E2E_SSH_IDENTITY` or `SBM_E2E_SSH_KEY_PASSPHRASE`). +- Opt-in e2e, skipped when unset: `SBM_E2E_SSH_HOST` in `.env` + `cargo test -p sbm_parser --test ssh_e2e -- --ignored` (libvirt: `-p sbm_virt`); a unit's log read as accounts with and without journal access: `scripts/service-log-e2e.sh` (a privileged systemd container); RDP: `SBM_E2E_RDP_{HOST,PORT,USER,PASSWORD}` + `cargo test -p sbm_ffi --lib rdp_e2e -- --ignored` (an alpine `xrdp xorgxrdp` container serves); `flutter test test/e2e/app_mcp_real_test.dart` (the app's MCP server over real SSH, through `$SSH_AUTH_SOCK`'s agent); `flutter test test/e2e/virt_real_test.dart` (variables in its header; dartssh2 has no ssh-agent, so use `SBM_E2E_SSH_IDENTITY` or `SBM_E2E_SSH_KEY_PASSPHRASE`). - Backups and chats end to end, each starting what it needs on loopback: `scripts/monitor-backup-e2e.sh` (the agent's, rclone + nginx WebDAV, Go's age), `scripts/app-backup-e2e.sh` (the app's sync to WebDAV, the `age` CLI), `scripts/agent-chat-encryption-e2e.sh OLD NEW` (Agent mode's chats encrypted in place, an older agent binary then this one). A test that sets up `TestWidgetsFlutterBinding` and makes real HTTP requests clears `HttpOverrides.global`: the binding answers every request 400. - Widget tests whose tree writes a store: `openTestDb()` in `setUp`, `SqliteDb.close` in `tearDown`, the store's `forTest()` — many widgets persist on their own, and a real file write in fake-async hangs. - **UI text in a test comes from the localization**, never a copied string: the instance the code reads (`l10n`, `libL10n`), else `AppLocalizationsEn()` / `LibLocalizationsEn()` / `LlmLocalizationsEn()`; panel: `get(LL).key()`. A message embedded in a longer text: `startOf` (`test/helpers/l10n.dart`). Server output and fixture data stay literal. diff --git a/crates/sbm_mcp/src/machine/services.rs b/crates/sbm_mcp/src/machine/services.rs index 003b5b14fc..1b77ee92c2 100644 --- a/crates/sbm_mcp/src/machine/services.rs +++ b/crates/sbm_mcp/src/machine/services.rs @@ -429,8 +429,8 @@ async fn fill_log(m: &dyn Machine, response: &mut ServiceListResponse, manager: let output = command_output(raw); match sbm_parser::service::parse_recent_log(manager, &output) { Some(log) => response.log = Some(log), - // `logread` absent is a machine with no log to read, which is the - // same answer as OpenRC's and not an empty log. + // `logread` absent, or a `journalctl` that could not run, is a + // machine with no log to read: OpenRC's answer, not an empty log. None => { response.available = false; response.reason_kind = Some(ServiceReason::NoLog); diff --git a/crates/sbm_parser/src/service.rs b/crates/sbm_parser/src/service.rs index 7d9a79ea69..2dec6a646d 100644 --- a/crates/sbm_parser/src/service.rs +++ b/crates/sbm_parser/src/service.rs @@ -1436,12 +1436,18 @@ pub fn parse_listing( } /// A unit's last lines, from what [`ServiceManagerType::recent_log_command`] -/// printed. `None` where the machine keeps no log to ask for by unit: -/// OpenRC, and a procd machine without `logread` — which is not the same -/// answer as a unit that has written nothing. +/// printed. `None` where the machine keeps no log to ask for by unit: OpenRC, +/// a procd machine without `logread`, and a `journalctl` that failed without +/// printing anything (no journald, not booted with systemd, no user bus) — +/// none of which is the same answer as a unit that has written nothing. pub fn parse_recent_log(manager: ServiceManagerType, output: &CommandOutput) -> Option { match manager { - ServiceManagerType::Systemd => Some(parse_journal(&output.stdout, &output.stderr)), + ServiceManagerType::Systemd => { + // Opening no journal file at all for lack of permission also exits + // non-zero with an empty stdout; that one is still an answer. + let log = parse_journal(&output.stdout, &output.stderr); + (output.succeeded || !log.lines.is_empty() || log.unreadable).then_some(log) + } ServiceManagerType::Procd if !output.succeeded && output.stdout.trim().is_empty() => None, ServiceManagerType::Procd => Some(ServiceLog { lines: parse_logread(&output.stdout), unreadable: false }), ServiceManagerType::Openrc => None, diff --git a/crates/sbm_parser/tests/service_compat.rs b/crates/sbm_parser/tests/service_compat.rs index a4b3e0b90d..a857c0dc1c 100644 --- a/crates/sbm_parser/tests/service_compat.rs +++ b/crates/sbm_parser/tests/service_compat.rs @@ -626,3 +626,42 @@ fn the_timestamp_and_memory_parsers_refuse_what_they_cannot_read() { } assert_eq!(parse_memory(" 950272 "), Some(950_272)); } + +#[test] +fn a_journal_read_that_failed_is_not_an_empty_log() { + // journalctl exits non-zero with an empty stdout where it cannot run at + // all: that machine has no log to read by unit, not an empty one. + let failed = CommandOutput::failed("System has not been booted with systemd"); + assert_eq!(parse_recent_log(ServiceManagerType::Systemd, &failed), None); + + // Not one journal file opened for lack of permission also exits non-zero; + // that is the unreadable hint, not a missing log. + let denied = CommandOutput::failed("No journal files were opened due to insufficient permissions."); + let log = parse_recent_log(ServiceManagerType::Systemd, &denied).expect("denied is an answer"); + assert!(log.lines.is_empty()); + assert!(log.unreadable); + + // What was printed before a failure is still a log. + let partial = CommandOutput::new("2026-12-01T10:00:00+00:00 host unit[1]: line\n", "some late error", false); + let log = parse_recent_log(ServiceManagerType::Systemd, &partial).expect("partial log parses"); + assert_eq!(log.lines.len(), 1); + + // Some files readable: exit zero, entries hidden, the hint on stderr. + let hidden = CommandOutput::new( + "-- No entries --\n", + "Hint: You are currently not seeing messages from other users and the system.", + true, + ); + let log = parse_recent_log(ServiceManagerType::Systemd, &hidden).expect("empty is a log"); + assert!(log.lines.is_empty()); + assert!(log.unreadable); + + // A unit that has written nothing. + let empty = CommandOutput::new("-- No entries --\n", "", true); + let log = parse_recent_log(ServiceManagerType::Systemd, &empty).expect("empty is a log"); + assert!(log.lines.is_empty()); + assert!(!log.unreadable); + + let procd_failed = CommandOutput::failed("-ash: logread: not found"); + assert_eq!(parse_recent_log(ServiceManagerType::Procd, &procd_failed), None); +} diff --git a/crates/sbm_parser/tests/ssh_e2e.rs b/crates/sbm_parser/tests/ssh_e2e.rs index 3f8902f3b2..bfcb43e7ff 100644 --- a/crates/sbm_parser/tests/ssh_e2e.rs +++ b/crates/sbm_parser/tests/ssh_e2e.rs @@ -13,6 +13,9 @@ //! - `SBM_E2E_SSH_HOST`: a Unix remote (Linux or BSD/macOS) //! - `SBM_E2E_SSH_HOST_WINDOWS`: a Windows remote (OpenSSH server; both //! cmd.exe and PowerShell default shells are supported) +//! - `SBM_E2E_SSH_HOST_JOURNAL`: a disposable systemd machine laid out by +//! `scripts/service-log-e2e.sh`, which sets it +//! - `SBM_E2E_SSH_CONFIG`: an `ssh_config` to read instead of `~/.ssh/config` //! //! Run with `cargo test -p sbm_parser --test ssh_e2e -- --ignored`. //! @@ -46,6 +49,10 @@ fn windows_host() -> Option { env_host("SBM_E2E_SSH_HOST_WINDOWS") } +fn journal_host() -> Option { + env_host("SBM_E2E_SSH_HOST_JOURNAL") +} + /// Put back whatever the account had in the custom-command directory before /// the test replaced it. Called on the failure path too — a test that leaves /// someone's commands in a `.e2e` directory has done real damage. @@ -95,7 +102,11 @@ const SSH_TIMEOUT: Duration = Duration::from_secs(120); /// blocks on the rest of the input. It has not bitten here only because the /// commands given input print nothing. fn run_ssh(host: &str, arg: &str, stdin: Option<&str>) -> Result { - let mut child = Command::new("ssh") + let mut ssh = Command::new("ssh"); + if let Some(config) = env_host("SBM_E2E_SSH_CONFIG") { + ssh.args(["-F", &config]); + } + let mut child = ssh .args(SSH_OPTS) .args([host, arg]) .stdin(if stdin.is_some() { @@ -699,6 +710,58 @@ fn ssh_e2e_unix_service_listing() { } } +/// A unit's recent log on a real systemd machine, read as accounts that can, +/// partly can and cannot read the journal, the way the app reads it. +/// +/// The machine is `scripts/service-log-e2e.sh`'s: `e2e-logger.service` has +/// logged, `ownlog` has a journal file of its own, `nojournal` has none and is +/// in neither `adm` nor `systemd-journal`. +#[test] +#[ignore = "requires SBM_E2E_SSH_HOST_JOURNAL (scripts/service-log-e2e.sh)"] +fn ssh_e2e_unix_service_log() { + use service::{ServiceManagerType::Systemd, ServiceScope, ServiceState, ServiceUnit, ServiceUnitType}; + let host = journal_host().expect("SBM_E2E_SSH_HOST_JOURNAL must be set"); + let unit = |name: &str| ServiceUnit::new(name, ServiceUnitType::Service, ServiceScope::System, ServiceState::Running); + let read = |user: &str, unit: &ServiceUnit, shell: &str| { + let command = Systemd.recent_log_command(unit, 5).expect("systemd reads by unit"); + let quoted = format!("{shell} -c '{}'", command.replace('\'', r"'\''")); + let out = run_ssh(&format!("{user}@{host}"), "ed, None).expect("ssh"); + let output = CommandOutput { + stdout: String::from_utf8_lossy(&out.stdout).into_owned(), + stderr: String::from_utf8_lossy(&out.stderr).into_owned(), + succeeded: out.status.success(), + }; + (service::parse_recent_log(Systemd, &output), output) + }; + let logger = unit("e2e-logger"); + + let (log, output) = read("root", &logger, "sh"); + let log = log.unwrap_or_else(|| panic!("root reads the log: {output:?}")); + assert!(log.lines.iter().any(|l| l.text.ends_with("hello from e2e")), "{log:?}"); + assert!(!log.unreadable); + + let (log, output) = read("root", &unit("never-ran"), "sh"); + let log = log.unwrap_or_else(|| panic!("a unit that never ran has a log: {output:?}")); + assert!(log.lines.is_empty() && !log.unreadable, "{log:?}"); + + // Not one journal file opened: journalctl fails, and that is the hint. + let (log, output) = read("nojournal", &logger, "sh"); + assert!(!output.succeeded, "{output:?}"); + let log = log.unwrap_or_else(|| panic!("no permission is an answer: {output:?}")); + assert!(log.lines.is_empty() && log.unreadable, "{log:?}"); + + // Its own file opened, the system's not: journalctl succeeds, same hint. + let (log, output) = read("ownlog", &logger, "sh"); + assert!(output.succeeded, "{output:?}"); + let log = log.unwrap_or_else(|| panic!("hidden entries are an answer: {output:?}")); + assert!(log.lines.is_empty() && log.unreadable, "{log:?}"); + + // A systemd machine whose journalctl is gone has no log to read by unit. + let (log, output) = read("root", &logger, "env PATH=/var/empty /bin/sh"); + assert!(!output.succeeded, "{output:?}"); + assert_eq!(log, None, "{output:?}"); +} + /// The benchmark's install and poll on a real machine, as the app runs them /// (each command is its own `sh -c`, handed to the login shell), under a /// throwaway `HOME` so the account's own copy is not touched. Nothing is diff --git a/scripts/service-log-e2e.sh b/scripts/service-log-e2e.sh new file mode 100755 index 0000000000..279e41725c --- /dev/null +++ b/scripts/service-log-e2e.sh @@ -0,0 +1,77 @@ +#!/bin/sh +# A unit's recent log on a real systemd machine, as the app reads it: +# +# 1. a throwaway Debian container booted with systemd, a persistent journal +# and sshd, on loopback with a key made here; +# 2. `e2e-logger.service` logs; `ownlog` gets a journal file of its own; +# `nojournal` has none and is in neither `adm` nor `systemd-journal`; +# 3. `ssh_e2e_unix_service_log` reads the log over SSH as each of them. +# +# scripts/service-log-e2e.sh +# +# Needs docker (privileged containers) and ssh. +set -eu + +ROOT=$(cd "$(dirname "$0")/.." && pwd) +WORK=$(mktemp -d "${TMPDIR:-/tmp}/sbm-service-log-e2e.XXXXXX") +IMAGE=sbm-service-log-e2e +NAME=sbm-service-log-e2e-$$ +PORT=${SBM_E2E_JOURNAL_PORT:-2229} + +cleanup() { + docker rm -f "$NAME" >/dev/null 2>&1 || true + rm -rf "$WORK" +} +trap cleanup EXIT INT TERM + +echo "== image" +docker build -q -t "$IMAGE" - >/dev/null <<'EOF' +FROM debian:trixie-slim +RUN apt-get update \ + && apt-get install -y --no-install-recommends systemd systemd-sysv dbus openssh-server \ + && rm -rf /var/lib/apt/lists/* \ + && mkdir -p /var/log/journal \ + && useradd -m -s /bin/sh nojournal && useradd -m -s /bin/sh ownlog +CMD ["/sbin/init"] +EOF + +echo "== machine" +ssh-keygen -q -t ed25519 -N '' -f "$WORK/key" +docker run -d --name "$NAME" --privileged --cgroupns=host \ + -v /sys/fs/cgroup:/sys/fs/cgroup:rw --tmpfs /run --tmpfs /run/lock \ + -p "127.0.0.1:$PORT:22" "$IMAGE" >/dev/null +i=0 +until state=$(docker exec "$NAME" systemctl is-system-running 2>/dev/null) || [ "$state" = degraded ]; do + i=$((i + 1)); [ "$i" -lt 60 ] || { echo "systemd did not come up: $state" >&2; exit 1; } + sleep 0.5 +done +docker exec -i "$NAME" sh -eu -c ' + key=$(cat) + for user in root nojournal ownlog; do + home=$(getent passwd "$user" | cut -d: -f6) + mkdir -p "$home/.ssh" + printf "%s\n" "$key" > "$home/.ssh/authorized_keys" + chown -R "$user:" "$home/.ssh"; chmod 700 "$home/.ssh"; chmod 600 "$home/.ssh/authorized_keys" + done + systemctl enable --now ssh >/dev/null 2>&1 + systemd-run -q --unit=e2e-logger sh -c "echo hello from e2e; exec sleep infinity" + su ownlog -c "echo own | systemd-cat -t ownlog" + journalctl --flush + ls /var/log/journal/*/user-$(id -u ownlog).journal >/dev/null +' < "$WORK/key.pub" + +cat > "$WORK/ssh_config" <