Box the CommandFailure payload so ExecError shrinks 128 -> 96 bytes and Result<T, ExecError> passes result_large_err without per-site boxing. Preserve the display text, redacted stdout/stderr capture, and the stderr tail used for update failures; update the constructor and every match site. Add regression tests for the error text, captured output, and the 96-byte size bound. Resolve the remaining Clippy warnings without blanket allows: a type alias for the snap-entry tuple in actions.rs, a CommandRecord params struct for Logger::command in log.rs, and DiskPhase variant renames in gui_bridge.rs. cargo clippy --workspace --all-targets -- -D warnings is clean; cargo test --workspace passes (692 tests).
315 lines
9.4 KiB
Rust
315 lines
9.4 KiB
Rust
//! Installer logging with mandatory secret redaction.
|
|
//!
|
|
//! Every log line is passed through the shared `Redactor`, so a caller cannot
|
|
//! accidentally write a registered secret. Command output is captured and
|
|
//! logged through the same path.
|
|
|
|
use std::fs::{File, OpenOptions};
|
|
use std::io::Write;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Mutex;
|
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
|
|
|
use phoebus_core::Redactor;
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Level {
|
|
Debug,
|
|
Info,
|
|
Warn,
|
|
Error,
|
|
}
|
|
|
|
impl Level {
|
|
fn as_str(self) -> &'static str {
|
|
match self {
|
|
Level::Debug => "DEBUG",
|
|
Level::Info => "INFO",
|
|
Level::Warn => "WARN",
|
|
Level::Error => "ERROR",
|
|
}
|
|
}
|
|
}
|
|
|
|
use std::sync::Arc;
|
|
|
|
pub type LogListener = Arc<dyn Fn(&str) + Send + Sync>;
|
|
|
|
/// Parameters for [`Logger::command`], grouped so the call stays within the
|
|
/// argument-count lint while keeping every field explicit at the call site.
|
|
pub struct CommandRecord<'a> {
|
|
pub stage: &'a str,
|
|
pub operation: &'a str,
|
|
pub program: &'a str,
|
|
pub args: &'a [String],
|
|
pub status: i32,
|
|
pub duration: Duration,
|
|
pub stdin_hidden: bool,
|
|
}
|
|
|
|
struct LoggerInner {
|
|
path: PathBuf,
|
|
file: Mutex<Option<File>>,
|
|
echo: bool,
|
|
redactor: Redactor,
|
|
listeners: Mutex<Vec<LogListener>>,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Logger {
|
|
inner: Arc<LoggerInner>,
|
|
}
|
|
|
|
impl Logger {
|
|
/// Open (or create) the log file. Falls back to an in-memory logger when
|
|
/// the path cannot be opened, so logging never aborts the installer.
|
|
pub fn open(path: impl Into<PathBuf>, redactor: Redactor, echo: bool) -> Self {
|
|
let path = path.into();
|
|
if let Some(parent) = path.parent() {
|
|
let _ = std::fs::create_dir_all(parent);
|
|
}
|
|
let file = OpenOptions::new()
|
|
.create(true)
|
|
.append(true)
|
|
.open(&path)
|
|
.ok();
|
|
Self {
|
|
inner: Arc::new(LoggerInner {
|
|
path,
|
|
file: Mutex::new(file),
|
|
echo,
|
|
redactor,
|
|
listeners: Mutex::new(Vec::new()),
|
|
}),
|
|
}
|
|
}
|
|
|
|
pub fn path(&self) -> &Path {
|
|
&self.inner.path
|
|
}
|
|
|
|
pub fn redactor(&self) -> &Redactor {
|
|
&self.inner.redactor
|
|
}
|
|
|
|
pub fn register_secret(&self, secret: &phoebus_core::SecretString) {
|
|
self.inner.redactor.register(secret);
|
|
}
|
|
|
|
pub fn add_listener(&self, listener: LogListener) {
|
|
if let Ok(mut listeners) = self.inner.listeners.lock() {
|
|
listeners.push(listener);
|
|
}
|
|
}
|
|
|
|
pub fn clear_listeners(&self) {
|
|
if let Ok(mut listeners) = self.inner.listeners.lock() {
|
|
listeners.clear();
|
|
}
|
|
}
|
|
|
|
fn write_line(&self, level: Level, message: &str) {
|
|
let message = self.inner.redactor.redact(message);
|
|
let line = format!("{} [{}] {}\n", timestamp(), level.as_str(), message);
|
|
if let Ok(mut guard) = self.inner.file.lock() {
|
|
if let Some(file) = guard.as_mut() {
|
|
let _ = file.write_all(line.as_bytes());
|
|
let _ = file.flush();
|
|
}
|
|
}
|
|
if self.inner.echo {
|
|
let _ = std::io::stderr().write_all(line.as_bytes());
|
|
}
|
|
if let Ok(listeners) = self.inner.listeners.lock() {
|
|
for listener in listeners.iter() {
|
|
listener(&line);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn debug(&self, message: impl AsRef<str>) {
|
|
self.write_line(Level::Debug, message.as_ref());
|
|
}
|
|
pub fn info(&self, message: impl AsRef<str>) {
|
|
self.write_line(Level::Info, message.as_ref());
|
|
}
|
|
pub fn warn(&self, message: impl AsRef<str>) {
|
|
self.write_line(Level::Warn, message.as_ref());
|
|
}
|
|
pub fn error(&self, message: impl AsRef<str>) {
|
|
self.write_line(Level::Error, message.as_ref());
|
|
}
|
|
pub fn section(&self, name: &str) {
|
|
self.write_line(Level::Info, &format!("--- {name} ---"));
|
|
}
|
|
|
|
/// Log the start of a command before running it.
|
|
pub fn command_start(
|
|
&self,
|
|
stage: &str,
|
|
operation: &str,
|
|
program: &str,
|
|
args: &[String],
|
|
stdin_hidden: bool,
|
|
) {
|
|
let mut line = format!("[{stage}] {operation} :: {program}");
|
|
for arg in args {
|
|
line.push(' ');
|
|
line.push_str(&shell_quote(arg));
|
|
}
|
|
if stdin_hidden {
|
|
line.push_str(" (stdin hidden)");
|
|
}
|
|
self.write_line(Level::Info, &line);
|
|
}
|
|
|
|
/// Log a command with its exit status and duration (all redacted).
|
|
pub fn command(&self, record: CommandRecord<'_>) {
|
|
let mut line = format!(
|
|
"[{}] {} :: {}",
|
|
record.stage, record.operation, record.program
|
|
);
|
|
for arg in record.args {
|
|
line.push(' ');
|
|
line.push_str(&shell_quote(arg));
|
|
}
|
|
if record.stdin_hidden {
|
|
line.push_str(" (stdin hidden)");
|
|
}
|
|
line.push_str(&format!(
|
|
" :: exit {} in {:.3}s",
|
|
record.status,
|
|
record.duration.as_secs_f64()
|
|
));
|
|
self.write_line(Level::Info, &line);
|
|
}
|
|
|
|
/// Append streaming command output to the log in real time, redacted.
|
|
pub fn stream_output(&self, text: &str) {
|
|
if text.is_empty() {
|
|
return;
|
|
}
|
|
let redacted = self.inner.redactor.redact(text);
|
|
if let Ok(mut guard) = self.inner.file.lock() {
|
|
if let Some(file) = guard.as_mut() {
|
|
let _ = file.write_all(redacted.as_bytes());
|
|
if !redacted.ends_with('\n') {
|
|
let _ = file.write_all(b"\n");
|
|
}
|
|
let _ = file.flush();
|
|
}
|
|
}
|
|
if self.inner.echo {
|
|
let _ = std::io::stderr().write_all(redacted.as_bytes());
|
|
}
|
|
if let Ok(listeners) = self.inner.listeners.lock() {
|
|
for listener in listeners.iter() {
|
|
listener(&redacted);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Append raw command output (stdout/stderr) to the log, redacted.
|
|
pub fn output(&self, bytes: &[u8]) {
|
|
if bytes.is_empty() {
|
|
return;
|
|
}
|
|
let text = String::from_utf8_lossy(bytes);
|
|
self.stream_output(&text);
|
|
}
|
|
|
|
pub fn dry_run(&self, stage: &str, operation: &str, program: &str, args: &[String]) {
|
|
let mut line = format!("[{stage}] [dry-run] {operation} :: {program}");
|
|
for arg in args {
|
|
line.push(' ');
|
|
line.push_str(&shell_quote(arg));
|
|
}
|
|
self.write_line(Level::Info, &line);
|
|
}
|
|
}
|
|
|
|
fn shell_quote(arg: &str) -> String {
|
|
if arg
|
|
.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || "-_./:=,@+".contains(c))
|
|
{
|
|
arg.to_string()
|
|
} else {
|
|
format!("'{}'", arg.replace('\'', "'\\''"))
|
|
}
|
|
}
|
|
|
|
/// Minimal UTC timestamp without pulling in a date crate.
|
|
fn timestamp() -> String {
|
|
let now = SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.unwrap_or_default();
|
|
let secs = now.as_secs() as i64;
|
|
let millis = now.subsec_millis();
|
|
let days = secs.div_euclid(86_400);
|
|
let rem = secs.rem_euclid(86_400);
|
|
let (y, m, d) = civil_from_days(days);
|
|
let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
|
|
format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}.{millis:03}Z")
|
|
}
|
|
|
|
/// Howard Hinnant's civil-from-days algorithm.
|
|
fn civil_from_days(z: i64) -> (i64, u32, u32) {
|
|
let z = z + 719_468;
|
|
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
|
|
let doe = z - era * 146_097;
|
|
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
|
let y = yoe + era * 400;
|
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
|
let mp = (5 * doy + 2) / 153;
|
|
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
|
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
|
(if m <= 2 { y + 1 } else { y }, m, d)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use phoebus_core::SecretString;
|
|
|
|
#[test]
|
|
fn secrets_are_redacted_in_log_file() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let path = dir.path().join("install.log");
|
|
let redactor = Redactor::new();
|
|
let secret = SecretString::new("hunter2");
|
|
redactor.register(&secret);
|
|
let logger = Logger::open(&path, redactor, false);
|
|
logger.info("passphrase is hunter2 here");
|
|
let text = std::fs::read_to_string(&path).unwrap();
|
|
assert!(text.contains("<redacted>"));
|
|
assert!(!text.contains("hunter2"));
|
|
}
|
|
|
|
#[test]
|
|
fn command_logging_includes_stage_and_status() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let path = dir.path().join("install.log");
|
|
let logger = Logger::open(&path, Redactor::new(), false);
|
|
logger.command(CommandRecord {
|
|
stage: "storage_prepare",
|
|
operation: "create GPT",
|
|
program: "sgdisk",
|
|
args: &["--zap-all".into(), "/dev/vda".into()],
|
|
status: 0,
|
|
duration: Duration::from_millis(12),
|
|
stdin_hidden: false,
|
|
});
|
|
let text = std::fs::read_to_string(&path).unwrap();
|
|
assert!(text.contains("[storage_prepare] create GPT :: sgdisk"));
|
|
assert!(text.contains("/dev/vda"));
|
|
assert!(text.contains("exit 0"));
|
|
}
|
|
|
|
#[test]
|
|
fn timestamp_has_expected_shape() {
|
|
let ts = timestamp();
|
|
assert_eq!(ts.len(), 24);
|
|
assert!(ts.ends_with('Z'));
|
|
}
|
|
}
|