Skip to main content

aios_collector/
fanotify_monitor.rs

1//! Fanotify monitor interface for privileged filesystem access events.
2//!
3//! The public API is intentionally usable on every development platform. Real
4//! fanotify attachment is only available to a privileged Linux daemon; when the
5//! current process cannot attach, the monitor reports that status and returns an
6//! empty event stream instead of pretending to collect file activity.
7
8use std::path::{Path, PathBuf};
9
10use aios_spec::{FsAccessEvent, FsAccessType, RawEvent};
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct FanotifyConfig {
14    pub roots: Vec<PathBuf>,
15    pub max_events_per_poll: usize,
16}
17
18impl Default for FanotifyConfig {
19    fn default() -> Self {
20        Self {
21            roots: vec![PathBuf::from("/")],
22            max_events_per_poll: 256,
23        }
24    }
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum FanotifyStatus {
29    Uninitialized,
30    UnsupportedPlatform,
31    PermissionRequired,
32    Ready,
33}
34
35pub struct FanotifyMonitor {
36    config: FanotifyConfig,
37    status: FanotifyStatus,
38}
39
40impl FanotifyMonitor {
41    pub fn new(config: FanotifyConfig) -> Self {
42        Self {
43            config,
44            status: FanotifyStatus::Uninitialized,
45        }
46    }
47
48    pub fn status(&self) -> FanotifyStatus {
49        self.status
50    }
51
52    pub fn roots(&self) -> &[PathBuf] {
53        &self.config.roots
54    }
55
56    pub fn try_init(&mut self) -> FanotifyStatus {
57        self.status = detect_status();
58        self.status
59    }
60
61    pub fn poll(&self) -> Vec<RawEvent> {
62        if self.status != FanotifyStatus::Ready {
63            return Vec::new();
64        }
65
66        // A real implementation should read from the fanotify fd, cap the
67        // batch at `max_events_per_poll`, and convert each record with
68        // `event_from_observation` below. Keeping this empty until an fd-backed
69        // implementation exists preserves deterministic local tests.
70        Vec::new()
71    }
72
73    pub fn event_from_observation(
74        timestamp_ms: i64,
75        pid: u32,
76        uid: u32,
77        file_path: impl AsRef<Path>,
78        access_type: FsAccessType,
79        bytes_transferred: Option<u64>,
80    ) -> RawEvent {
81        RawEvent::FileSystemAccess(FsAccessEvent {
82            timestamp_ms,
83            pid,
84            uid,
85            file_path: file_path.as_ref().to_string_lossy().into_owned(),
86            access_type,
87            bytes_transferred,
88        })
89    }
90}
91
92impl Default for FanotifyMonitor {
93    fn default() -> Self {
94        Self::new(FanotifyConfig::default())
95    }
96}
97
98fn detect_status() -> FanotifyStatus {
99    if !cfg!(target_os = "linux") {
100        return FanotifyStatus::UnsupportedPlatform;
101    }
102
103    // On Linux, fanotify requires a privileged daemon and a real fd-backed
104    // implementation. Until that implementation is linked in, expose the
105    // deployment requirement explicitly.
106    FanotifyStatus::PermissionRequired
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112
113    #[test]
114    fn unsupported_or_unprivileged_monitor_returns_no_events() {
115        let mut monitor = FanotifyMonitor::default();
116        let status = monitor.try_init();
117
118        assert!(matches!(
119            status,
120            FanotifyStatus::UnsupportedPlatform | FanotifyStatus::PermissionRequired
121        ));
122        assert!(monitor.poll().is_empty());
123    }
124
125    #[test]
126    fn observation_conversion_preserves_raw_path_until_airgap() {
127        let raw = FanotifyMonitor::event_from_observation(
128            42,
129            100,
130            200,
131            "/tmp/private/report.docx",
132            FsAccessType::OpenRead,
133            Some(4096),
134        );
135
136        match raw {
137            RawEvent::FileSystemAccess(event) => {
138                assert_eq!(event.timestamp_ms, 42);
139                assert_eq!(event.pid, 100);
140                assert_eq!(event.uid, 200);
141                assert_eq!(event.file_path, "/tmp/private/report.docx");
142                assert!(matches!(event.access_type, FsAccessType::OpenRead));
143                assert_eq!(event.bytes_transferred, Some(4096));
144            },
145            other => panic!("expected FileSystemAccess, got {other:?}"),
146        }
147    }
148}