agentmux_srv_core/backend/viewer/
audit.rs1use std::sync::atomic::{AtomicUsize, Ordering};
21use std::sync::OnceLock;
22use std::time::Instant;
23
24use crate::backend::mps::StreamPos;
25use crate::backend::storage::viewer_devices::{DeviceKind, ViewerDevice};
26
27const MAX_NAME: usize = 64;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Proof {
33 Code,
35 Token,
37 Signed,
39}
40
41impl Proof {
42 fn as_str(self) -> &'static str {
43 match self {
44 Proof::Code => "the pairing code shown on this computer",
45 Proof::Token => "its viewer token",
46 Proof::Signed => "signed by its paired key",
47 }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct ViewerActor {
54 pub device_id: String,
55 pub name: String,
56 pub kind: DeviceKind,
57 pub user: Option<String>,
59}
60
61fn tidy(text: &str) -> String {
63 let kept: String = text.chars().filter(|c| !c.is_control()).collect();
64 kept.trim().chars().take(MAX_NAME).collect::<String>().trim_end().to_string()
65}
66
67fn clean(text: &str) -> String {
69 let kept = tidy(text).replace(':', "-");
70 if kept.is_empty() { "unnamed".to_string() } else { kept }
71}
72
73impl ViewerActor {
74 pub fn of(device: &ViewerDevice, user: Option<&str>) -> Self {
77 let user = user.filter(|_| device.kind == DeviceKind::Computer).map(tidy).filter(|u| !u.is_empty());
78 Self { device_id: device.device_id.clone(), name: device.device_name.clone(), kind: device.kind, user }
79 }
80
81 pub fn label(&self) -> String {
83 match (&self.user, self.kind) {
84 (Some(user), _) => format!("{}@{}", clean(user).replace('@', "-"), clean(&self.name)),
85 (None, kind) => format!("{} ({})", clean(&self.name), kind.as_str()),
86 }
87 }
88
89 fn reason(&self, proof: Proof, detail: Option<&str>) -> String {
90 let mut reason = format!("paired {} {}; {}", self.kind.as_str(), self.device_id, proof.as_str());
91 if self.user.is_some() {
92 reason.push_str("; the person's name is claimed by the paired computer");
93 }
94 if let Some(detail) = detail.filter(|d| !d.is_empty()) {
95 reason.push_str("; ");
96 reason.push_str(detail);
97 }
98 reason
99 }
100}
101
102pub fn record(actor: &ViewerActor, act: &str, agent: &str, proof: Proof, detail: Option<&str>, refused: Option<&str>) {
105 let reason = actor.reason(proof, detail);
106 crate::backend::reactive::get_global_handler().log_fleet_action_audit(
107 Some(&actor.label()),
108 agent,
109 "",
110 &format!("viewer.{act}"),
111 refused.is_none(),
112 refused,
113 "",
114 Some(&reason),
115 );
116}
117
118pub fn wrong_pairing_code(name: &str, kind: DeviceKind) {
121 let label = format!("{} ({})", clean(name), kind.as_str());
122 let reason = "an unpaired device answered the pairing code shown on this computer with a wrong one; its name and kind are its own words";
123 crate::backend::reactive::get_global_handler().log_fleet_action_audit(
124 Some(&label),
125 "",
126 "",
127 "viewer.pair",
128 false,
129 Some("a wrong pairing code"),
130 "",
131 Some(reason),
132 );
133}
134
135pub fn feed_opened(actor: ViewerActor, agent: &str, proof: Proof, lease: super::FeedLease) -> super::FeedLease {
137 record(&actor, "feed-open", agent, proof, None, None);
138 let agent = agent.to_string();
139 lease.on_close(move || record(&actor, "feed-close", &agent, proof, None, None))
140}
141
142struct Landing {
144 block_id: String,
145 device: String,
147 message_id: String,
148 actor: ViewerActor,
149 agent: String,
150 at: Instant,
151}
152
153static LANDING: OnceLock<parking_lot::Mutex<Vec<Landing>>> = OnceLock::new();
154static WAITING: AtomicUsize = AtomicUsize::new(0);
156
157fn landing() -> &'static parking_lot::Mutex<Vec<Landing>> {
158 LANDING.get_or_init(|| parking_lot::Mutex::new(Vec::new()))
159}
160
161pub(super) fn expect_landing(block_id: &str, device: &str, message_id: &str, actor: ViewerActor, agent: &str) {
164 let mut list = landing().lock();
165 let now = Instant::now();
166 list.retain(|l| now.duration_since(l.at) < super::origin::KEEP);
167 let landing = Landing {
168 block_id: block_id.to_string(),
169 device: device.to_string(),
170 message_id: message_id.to_string(),
171 actor,
172 agent: agent.to_string(),
173 at: now,
174 };
175 list.push(landing);
176 WAITING.store(list.len(), Ordering::Release);
177}
178
179fn position(pos: &[StreamPos], n: u64) -> Option<String> {
181 let p = pos.iter().find(|p| p.stream.starts_with("g:")).or_else(|| pos.first())?;
182 Some(format!("line {}:{} of {}", p.gen, p.line + n, p.stream))
183}
184
185fn sent_by(line: &[u8]) -> Option<(String, String)> {
187 find(line, b"\"via\":\"viewer\"")?;
189 let record: serde_json::Value = serde_json::from_slice(line).ok()?;
190 let amx = record.get("amx")?;
191 (amx.get("via")?.as_str()? == "viewer").then_some(())?;
192 Some((amx.get("device")?.as_str()?.to_string(), amx.get("message_id")?.as_str()?.to_string()))
193}
194
195pub fn note_landed(block_id: &str, records: &[u8], pos: &[StreamPos], stored: bool) {
201 if WAITING.load(Ordering::Acquire) == 0 {
202 return;
203 }
204 let mut landed = Vec::new();
205 {
206 let mut list = landing().lock();
207 for (n, line) in records.split(|b| *b == b'\n').enumerate() {
208 let Some((device, message_id)) = sent_by(line) else { continue };
209 let Some(at) = list.iter().position(|l| l.block_id == block_id && l.device == device && l.message_id == message_id) else {
210 continue;
211 };
212 let l = list.remove(at);
213 landed.push((l.actor, l.agent, position(pos, n as u64)));
214 }
215 WAITING.store(list.len(), Ordering::Release);
216 }
217 for (actor, agent, at) in landed {
218 match at {
219 Some(at) => record(&actor, "send", &agent, Proof::Signed, Some(&at), None),
220 None if stored => record(&actor, "send", &agent, Proof::Signed, Some("its line's position is not known"), None),
221 None => record(&actor, "send", &agent, Proof::Signed, None, Some("delivered, but its line was not stored")),
222 }
223 }
224}
225
226fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
227 haystack.windows(needle.len()).position(|w| w == needle)
228}
229
230#[cfg(test)]
231#[path = "audit_tests.rs"]
232mod tests;