Skip to main content

winx_code_agent/
logging.rs

1use std::fs::{self, File, OpenOptions};
2use std::io::{self, Write};
3use std::path::{Path, PathBuf};
4
5#[cfg(unix)]
6use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _, PermissionsExt as _};
7use time::OffsetDateTime;
8use tracing_appender::non_blocking::{NonBlocking, NonBlockingBuilder, WorkerGuard};
9use tracing_subscriber::filter::filter_fn;
10use tracing_subscriber::layer::SubscriberExt as _;
11use tracing_subscriber::util::SubscriberInitExt as _;
12use tracing_subscriber::Layer as _;
13
14use crate::errors::{Result, WinxError};
15
16/// Keeps the non-blocking usage-log worker alive for the lifetime of the process.
17pub struct LoggingGuard {
18    _usage: Option<WorkerGuard>,
19}
20
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22enum UsageRotation {
23    Never,
24    Hourly,
25    Daily,
26}
27
28impl UsageRotation {
29    fn parse(value: Option<&str>) -> Result<Self> {
30        match value.unwrap_or("daily").trim().to_ascii_lowercase().as_str() {
31            "never" => Ok(Self::Never),
32            "hourly" => Ok(Self::Hourly),
33            "daily" | "" => Ok(Self::Daily),
34            other => Err(WinxError::ConfigurationError(format!(
35                "invalid WINX_USAGE_LOG_ROTATION={other:?}; expected `never`, `hourly`, or `daily`"
36            ))),
37        }
38    }
39
40    fn period(self, now: OffsetDateTime) -> Option<String> {
41        let month = u8::from(now.month());
42        match self {
43            Self::Never => None,
44            Self::Daily => Some(format!("{:04}-{month:02}-{:02}", now.year(), now.day())),
45            Self::Hourly => {
46                Some(format!("{:04}-{month:02}-{:02}-{:02}", now.year(), now.day(), now.hour()))
47            }
48        }
49    }
50
51    fn max_files(self, keep_days: usize) -> Option<usize> {
52        if keep_days == 0 || self == Self::Never {
53            return None;
54        }
55        let files_per_day = if self == Self::Hourly { 24 } else { 1 };
56        // Retain one extra file so rotation never dips below the requested
57        // completed-history window while the active file is counted.
58        Some(keep_days.saturating_mul(files_per_day).saturating_add(1))
59    }
60
61    fn valid_period(self, suffix: &str) -> bool {
62        let expected_len = match self {
63            Self::Never => return false,
64            Self::Daily => 10,
65            Self::Hourly => 13,
66        };
67        suffix.len() == expected_len
68            && suffix.bytes().enumerate().all(|(index, byte)| {
69                let dash = index == 4 || index == 7 || (self == Self::Hourly && index == 10);
70                if dash {
71                    byte == b'-'
72                } else {
73                    byte.is_ascii_digit()
74                }
75            })
76    }
77}
78
79/// Minimal secure rolling writer used by the non-blocking tracing worker.
80/// Every file is opened with `O_NOFOLLOW` and mode `0600` on Unix, including
81/// files created after daily/hourly rotation. This avoids relying on the process
82/// umask and closes the short world-readable window a post-open chmod would have.
83struct SecureUsageWriter {
84    base_path: PathBuf,
85    rotation: UsageRotation,
86    keep_days: usize,
87    active_period: Option<String>,
88    active_path: PathBuf,
89    file: File,
90}
91
92impl SecureUsageWriter {
93    fn new(base_path: PathBuf, rotation: UsageRotation, keep_days: usize) -> io::Result<Self> {
94        let parent = log_parent(&base_path);
95        create_log_directory(parent)?;
96        validate_log_file_name(&base_path)?;
97
98        let active_period = rotation.period(OffsetDateTime::now_utc());
99        let active_path = rotated_path(&base_path, active_period.as_deref())?;
100        let file = open_secure_log_file(&active_path)?;
101        let writer = Self { base_path, rotation, keep_days, active_period, active_path, file };
102        writer.prune_old_logs()?;
103        Ok(writer)
104    }
105
106    fn rotate_if_needed(&mut self) -> io::Result<()> {
107        let period = self.rotation.period(OffsetDateTime::now_utc());
108        if period == self.active_period {
109            return Ok(());
110        }
111
112        let path = rotated_path(&self.base_path, period.as_deref())?;
113        let file = open_secure_log_file(&path)?;
114        self.file = file;
115        self.active_path = path;
116        self.active_period = period;
117        self.prune_old_logs()
118    }
119
120    fn prune_old_logs(&self) -> io::Result<()> {
121        let Some(max_files) = self.rotation.max_files(self.keep_days) else {
122            return Ok(());
123        };
124        let parent = log_parent(&self.base_path);
125        let base_name = validate_log_file_name(&self.base_path)?;
126        let prefix = format!("{base_name}.");
127        let mut candidates = Vec::new();
128
129        for entry in fs::read_dir(parent)? {
130            let entry = entry?;
131            let file_type = entry.file_type()?;
132            if !file_type.is_file() || file_type.is_symlink() {
133                continue;
134            }
135            let Some(name) = entry.file_name().to_str().map(ToString::to_string) else {
136                continue;
137            };
138            let Some(period) = name.strip_prefix(&prefix) else {
139                continue;
140            };
141            if self.rotation.valid_period(period) {
142                candidates.push((name, entry.path()));
143            }
144        }
145
146        candidates.sort_by(|left, right| left.0.cmp(&right.0));
147        let remove_count = candidates.len().saturating_sub(max_files);
148        for (_, path) in candidates.into_iter().take(remove_count) {
149            fs::remove_file(path)?;
150        }
151        Ok(())
152    }
153}
154
155impl Write for SecureUsageWriter {
156    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
157        self.rotate_if_needed()?;
158        self.file.write(buffer)
159    }
160
161    fn flush(&mut self) -> io::Result<()> {
162        self.file.flush()
163    }
164}
165
166/// Install the stderr subscriber plus an optional JSONL usage-event sink.
167///
168/// `WINX_USAGE_LOG` enables a non-blocking file writer filtered to the
169/// `winx::usage` target. The sink never receives command text or file contents.
170/// Call this only after the optional Landlock domain has been applied so the
171/// writer thread inherits the same filesystem restrictions as every other child.
172pub fn initialize(verbose: bool, debug: bool) -> Result<LoggingGuard> {
173    let level = if debug {
174        tracing::Level::DEBUG
175    } else if verbose {
176        tracing::Level::INFO
177    } else {
178        tracing::Level::WARN
179    };
180    let filter = tracing_subscriber::EnvFilter::from_default_env().add_directive(level.into());
181    let filter = match "winx::usage=info".parse() {
182        Ok(directive) => filter.add_directive(directive),
183        Err(_) => filter,
184    };
185    let stderr_json = crate::config::env_text("WINX_LOG_FORMAT")
186        .is_some_and(|format| format.eq_ignore_ascii_case("json"));
187    let usage = usage_log_writer()?;
188
189    let guard = match (stderr_json, usage) {
190        (true, Some((writer, guard))) => {
191            tracing_subscriber::registry()
192                .with(
193                    tracing_subscriber::fmt::layer()
194                        .json()
195                        .with_ansi(false)
196                        .with_writer(std::io::stderr)
197                        .with_filter(filter),
198                )
199                .with(usage_json_layer(writer))
200                .init();
201            Some(guard)
202        }
203        (false, Some((writer, guard))) => {
204            tracing_subscriber::registry()
205                .with(
206                    tracing_subscriber::fmt::layer()
207                        .with_ansi(true)
208                        .with_writer(std::io::stderr)
209                        .with_filter(filter),
210                )
211                .with(usage_json_layer(writer))
212                .init();
213            Some(guard)
214        }
215        (true, None) => {
216            tracing_subscriber::registry()
217                .with(
218                    tracing_subscriber::fmt::layer()
219                        .json()
220                        .with_ansi(false)
221                        .with_writer(std::io::stderr)
222                        .with_filter(filter),
223                )
224                .init();
225            None
226        }
227        (false, None) => {
228            tracing_subscriber::registry()
229                .with(
230                    tracing_subscriber::fmt::layer()
231                        .with_ansi(true)
232                        .with_writer(std::io::stderr)
233                        .with_filter(filter),
234                )
235                .init();
236            None
237        }
238    };
239    Ok(LoggingGuard { _usage: guard })
240}
241
242fn usage_json_layer<S>(writer: NonBlocking) -> impl tracing_subscriber::Layer<S>
243where
244    S: tracing::Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>,
245{
246    tracing_subscriber::fmt::layer()
247        .json()
248        .with_ansi(false)
249        .with_current_span(false)
250        .with_span_list(false)
251        .with_writer(writer)
252        .with_filter(filter_fn(|metadata| metadata.target() == "winx::usage"))
253}
254
255fn usage_log_writer() -> Result<Option<(NonBlocking, WorkerGuard)>> {
256    let Some(path) = crate::config::env_text("WINX_USAGE_LOG").map(PathBuf::from) else {
257        return Ok(None);
258    };
259    let rotation =
260        UsageRotation::parse(crate::config::env_text("WINX_USAGE_LOG_ROTATION").as_deref())?;
261    let keep_days = parse_keep_days()?;
262    let writer = SecureUsageWriter::new(path.clone(), rotation, keep_days).map_err(|error| {
263        WinxError::ConfigurationError(format!(
264            "cannot open WINX_USAGE_LOG {} securely: {error}",
265            path.display()
266        ))
267    })?;
268    Ok(Some(NonBlockingBuilder::default().thread_name("winx-usage-log").finish(writer)))
269}
270
271fn log_parent(path: &Path) -> &Path {
272    path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or(Path::new("."))
273}
274
275fn validate_log_file_name(path: &Path) -> io::Result<&str> {
276    path.file_name().and_then(|name| name.to_str()).ok_or_else(|| {
277        io::Error::new(
278            io::ErrorKind::InvalidInput,
279            format!("usage log path must name a UTF-8 file: {}", path.display()),
280        )
281    })
282}
283
284fn rotated_path(base_path: &Path, period: Option<&str>) -> io::Result<PathBuf> {
285    let Some(period) = period else {
286        return Ok(base_path.to_path_buf());
287    };
288    let name = validate_log_file_name(base_path)?;
289    Ok(base_path.with_file_name(format!("{name}.{period}")))
290}
291
292fn create_log_directory(path: &Path) -> io::Result<()> {
293    #[cfg(unix)]
294    {
295        let mut builder = fs::DirBuilder::new();
296        builder.recursive(true).mode(0o700).create(path)
297    }
298    #[cfg(not(unix))]
299    {
300        fs::create_dir_all(path)
301    }
302}
303
304fn open_secure_log_file(path: &Path) -> io::Result<File> {
305    #[cfg(unix)]
306    {
307        let file = OpenOptions::new()
308            .append(true)
309            .create(true)
310            .mode(0o600)
311            .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
312            .open(path)?;
313        let metadata = file.metadata()?;
314        if !metadata.is_file() {
315            return Err(io::Error::new(
316                io::ErrorKind::InvalidInput,
317                format!("usage log is not a regular file: {}", path.display()),
318            ));
319        }
320        let mut permissions = metadata.permissions();
321        if permissions.mode() & 0o777 != 0o600 {
322            permissions.set_mode(0o600);
323            file.set_permissions(permissions)?;
324        }
325        Ok(file)
326    }
327    #[cfg(not(unix))]
328    {
329        let file = OpenOptions::new().append(true).create(true).open(path)?;
330        if !file.metadata()?.is_file() {
331            return Err(io::Error::new(
332                io::ErrorKind::InvalidInput,
333                format!("usage log is not a regular file: {}", path.display()),
334            ));
335        }
336        Ok(file)
337    }
338}
339
340fn parse_keep_days() -> Result<usize> {
341    let Some(raw) = crate::config::env_text("WINX_USAGE_LOG_KEEP_DAYS") else {
342        return Ok(7);
343    };
344    let days = raw.parse::<usize>().map_err(|error| {
345        WinxError::ConfigurationError(format!("invalid WINX_USAGE_LOG_KEEP_DAYS={raw:?}: {error}"))
346    })?;
347    if days > 3_650 {
348        return Err(WinxError::ConfigurationError(
349            "WINX_USAGE_LOG_KEEP_DAYS must be between 0 and 3650".to_string(),
350        ));
351    }
352    Ok(days)
353}
354
355#[cfg(test)]
356mod tests {
357    #![allow(clippy::unwrap_used)]
358
359    use super::{SecureUsageWriter, UsageRotation};
360    use std::io::Write as _;
361
362    #[test]
363    fn usage_rotation_retention_is_bounded_and_explicit() {
364        assert!(matches!(UsageRotation::parse(None), Ok(UsageRotation::Daily)));
365        assert_eq!(UsageRotation::Daily.max_files(7), Some(8));
366        assert_eq!(UsageRotation::Hourly.max_files(2), Some(49));
367        assert_eq!(UsageRotation::Never.max_files(7), None);
368        assert_eq!(UsageRotation::Daily.max_files(0), None);
369    }
370
371    #[cfg(unix)]
372    #[test]
373    fn usage_files_are_private_for_initial_and_rotated_names() {
374        use std::os::unix::fs::PermissionsExt as _;
375
376        for rotation in [UsageRotation::Never, UsageRotation::Daily, UsageRotation::Hourly] {
377            let root = tempfile::tempdir().unwrap();
378            let nested = root.path().join("private/state");
379            let base = nested.join("usage.jsonl");
380            let mut writer = SecureUsageWriter::new(base, rotation, 1).unwrap();
381            writer.write_all(b"{}\n").unwrap();
382            writer.flush().unwrap();
383
384            let mode = writer.active_path.metadata().unwrap().permissions().mode() & 0o777;
385            assert_eq!(mode, 0o600, "{}", writer.active_path.display());
386            let directory_mode = nested.metadata().unwrap().permissions().mode() & 0o777;
387            assert_eq!(directory_mode, 0o700, "{}", nested.display());
388
389            if rotation != UsageRotation::Never {
390                let rotated_path = writer.active_path.clone();
391                std::fs::remove_file(&rotated_path).unwrap();
392                writer.active_period = Some("1970-01-01-00".to_string());
393                writer.write_all(b"rotated\n").unwrap();
394                writer.flush().unwrap();
395                let rotated_mode = rotated_path.metadata().unwrap().permissions().mode() & 0o777;
396                assert_eq!(rotated_mode, 0o600, "{}", rotated_path.display());
397            }
398        }
399    }
400
401    #[cfg(unix)]
402    #[test]
403    fn existing_usage_file_is_tightened_and_symlink_is_rejected() {
404        use std::os::unix::fs::{symlink, PermissionsExt as _};
405
406        let root = tempfile::tempdir().unwrap();
407        let existing = root.path().join("existing.jsonl");
408        std::fs::write(&existing, b"old\n").unwrap();
409        std::fs::set_permissions(&existing, std::fs::Permissions::from_mode(0o644)).unwrap();
410        let writer = SecureUsageWriter::new(existing.clone(), UsageRotation::Never, 0).unwrap();
411        let mode = writer.active_path.metadata().unwrap().permissions().mode() & 0o777;
412        assert_eq!(mode, 0o600);
413        drop(writer);
414
415        let target = root.path().join("target.jsonl");
416        std::fs::write(&target, b"target\n").unwrap();
417        let link = root.path().join("link.jsonl");
418        symlink(&target, &link).unwrap();
419        assert!(SecureUsageWriter::new(link, UsageRotation::Never, 0).is_err());
420    }
421}