1use crate::state::{RuntimeState, ServerState, StateError, loopback};
2use serde::{Deserialize, Serialize};
3use sha2::{Digest, Sha256};
4
5fn invalid(message: &str) -> StateError {
6 StateError {
7 kind: "invalid",
8 message: message.into(),
9 }
10}
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct ProcessIdentity {
14 pub pid: u32,
15 pub process: String,
16 pub executable: String,
17 pub started: String,
18}
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(deny_unknown_fields)]
21pub struct Listener {
22 pub identity: ProcessIdentity,
23 pub address: String,
24 pub port: u16,
25}
26fn addresses_match(actual: &str, expected: &str) -> bool {
27 let actual = actual.trim_matches(['[', ']']).to_ascii_lowercase();
28 let expected = expected.trim_matches(['[', ']']).to_ascii_lowercase();
29 if expected == "localhost" {
30 ["127.0.0.1", "::1", "localhost"].contains(&actual.as_str())
31 } else {
32 actual == expected
33 }
34}
35pub fn choose_listener(
36 listeners: &[Listener],
37 port: u16,
38 host: &str,
39) -> Result<Listener, StateError> {
40 let mut matches = listeners
41 .iter()
42 .filter(|entry| entry.port == port && addresses_match(&entry.address, host));
43 let found = matches
44 .next()
45 .ok_or_else(|| invalid("listener identity unavailable"))?;
46 if matches.next().is_some() {
47 return Err(invalid("listener identity ambiguous"));
48 }
49 Ok(found.clone())
50}
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct LiveIdentity {
53 pub hash: String,
54 pub expected: ProcessIdentity,
55}
56fn hash(value: &impl Serialize) -> Result<String, StateError> {
57 let value = serde_json::to_value(value).map_err(|_| invalid("cannot serialize identity"))?;
58 let bytes = serde_json::to_vec(&value).map_err(|_| invalid("cannot encode identity"))?;
59 if bytes.len() > 1048576 {
60 return Err(invalid("identity exceeds limit"));
61 }
62 Ok(format!("{:x}", Sha256::digest(bytes)))
63}
64pub fn capture(
65 active: &ServerState,
66 observed: &Listener,
67 approved_executable: bool,
68) -> Result<LiveIdentity, StateError> {
69 active.validate()?;
70 let url = loopback(&active.endpoint)?;
71 let host = url.host_str().ok_or_else(|| invalid("missing host"))?;
72 let identity = &observed.identity;
73 if observed.port != active.port
74 || !addresses_match(&observed.address, host)
75 || !approved_executable
76 || identity.pid == 0
77 || identity.executable.is_empty()
78 || identity.started.is_empty()
79 || identity.process.is_empty()
80 || active.pid.is_some_and(|pid| pid != identity.pid)
81 || active
82 .process_executable
83 .as_ref()
84 .is_some_and(|value| value != &identity.executable)
85 || active
86 .process_started_at
87 .as_ref()
88 .is_some_and(|value| value != &identity.started)
89 {
90 return Err(invalid(
91 "observed listener does not match approved runtime identity",
92 ));
93 }
94 let value = serde_json::json!({"backend":active.backend,"host":host,"port":active.port,"pid":identity.pid,"ownedByUs":active.owned_by_us,"executable":identity.executable,"startedAt":identity.started});
95 Ok(LiveIdentity {
96 hash: hash(&value)?,
97 expected: identity.clone(),
98 })
99}
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum Operation {
103 Down,
104 Detach,
105 ReplaceServer,
106}
107#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
108#[serde(rename_all = "camelCase")]
109pub struct Confirmation {
110 operation: Operation,
111 canonical_target_ids: Vec<String>,
112 backend: Option<String>,
113 endpoint: Option<String>,
114 owned_by_us: Option<bool>,
115 process_identity_hash: Option<String>,
116 state_revision_hash: String,
117}
118impl Confirmation {
119 pub fn prepare(
120 operation: Operation,
121 state: &RuntimeState,
122 target: Option<&str>,
123 live: Option<&LiveIdentity>,
124 ) -> Result<Self, StateError> {
125 state.validate()?;
126 let active = state.active.as_ref();
127 if active.is_some() != live.is_some() {
128 return Err(invalid(
129 "active confirmation requires live process identity",
130 ));
131 }
132 match operation {
133 Operation::Down if active.is_some_and(|entry| !entry.owned_by_us) => {
134 return Err(invalid("down requires owned runtime"));
135 }
136 Operation::Detach if !active.is_some_and(|entry| !entry.owned_by_us) => {
137 return Err(invalid("detach requires attached runtime"));
138 }
139 Operation::ReplaceServer if target.is_none() => {
140 return Err(invalid("replacement target required"));
141 }
142 Operation::Down | Operation::Detach if target.is_some() => {
143 return Err(invalid("unexpected target"));
144 }
145 _ => (),
146 }
147 let mut targets = active
148 .map(|entry| vec![entry.model_id.clone()])
149 .unwrap_or_default();
150 if let Some(target) = target {
151 targets.push(target.into());
152 }
153 for target in &targets {
154 if target.is_empty()
155 || target.len() > 8192
156 || !target.as_bytes()[0].is_ascii_alphanumeric()
157 || target.split('/').any(|part| part == "..")
158 || !target
159 .bytes()
160 .all(|byte| byte.is_ascii_alphanumeric() || b"._:/-".contains(&byte))
161 {
162 return Err(invalid("unsafe confirmation target"));
163 }
164 }
165 Ok(Self {
166 operation,
167 canonical_target_ids: targets,
168 backend: active.map(|entry| entry.backend.clone()),
169 endpoint: active.map(|entry| entry.endpoint.clone()),
170 owned_by_us: active.map(|entry| entry.owned_by_us),
171 process_identity_hash: live.map(|identity| identity.hash.clone()),
172 state_revision_hash: hash(state)?,
173 })
174 }
175 pub fn verify(&self, current: &Self) -> Result<(), StateError> {
176 if self == current {
177 Ok(())
178 } else {
179 Err(StateError {
180 kind: "drift",
181 message: "confirmation target changed; rebuild review".into(),
182 })
183 }
184 }
185}
186
187pub fn parse_lsof_listener(raw: &str, port: u16, host: &str) -> Result<u32, StateError> {
188 if raw.len() > 65536 {
189 return Err(invalid("listener output exceeds limit"));
190 }
191 let mut pid = None;
192 let mut matches = Vec::new();
193 for line in raw.lines() {
194 if let Some(value) = line.strip_prefix('p') {
195 pid = value
196 .parse::<u32>()
197 .ok()
198 .filter(|pid| *pid > 0 && *pid <= i32::MAX as u32);
199 }
200 if let Some(value) = line.strip_prefix('n') {
201 let Some((address, observed_port)) = value.rsplit_once(':') else {
202 return Err(invalid("invalid listener address"));
203 };
204 if observed_port.parse::<u16>().ok() == Some(port) && addresses_match(address, host) {
205 matches.push(pid.ok_or_else(|| invalid("missing listener PID"))?);
206 }
207 }
208 }
209 if matches.len() != 1 {
210 return Err(invalid("listener absent or ambiguous"));
211 }
212 Ok(matches[0])
213}
214pub fn parse_start_time(raw: &str) -> Result<String, StateError> {
215 if raw.len() > 4096 {
216 return Err(invalid("process start output exceeds limit"));
217 }
218 let rows: Vec<_> = raw.lines().filter(|line| !line.trim().is_empty()).collect();
219 if rows.len() != 1 {
220 return Err(invalid("process start absent or ambiguous"));
221 }
222 let parts: Vec<_> = rows[0].split_whitespace().collect();
223 if parts.len() != 5 || !["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].contains(&parts[0]) {
224 return Err(invalid("invalid process start"));
225 }
226 let month = [
227 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
228 ]
229 .iter()
230 .position(|month| *month == parts[1])
231 .ok_or_else(|| invalid("invalid start month"))?
232 + 1;
233 let day = parts[2]
234 .parse::<u8>()
235 .map_err(|_| invalid("invalid start day"))?;
236 let time: Vec<_> = parts[3].split(':').collect();
237 if !(1..=31).contains(&day)
238 || parts[4].len() != 4
239 || !parts[4].bytes().all(|byte| byte.is_ascii_digit())
240 || time.len() != 3
241 || time.iter().enumerate().any(|(index, part)| {
242 part.len() != 2
243 || part
244 .parse::<u8>()
245 .map_or(true, |value| value > if index == 0 { 23 } else { 59 })
246 })
247 {
248 return Err(invalid("invalid process start"));
249 }
250 Ok(format!("{}-{month:02}-{day:02} {}", parts[4], parts[3]))
251}
252pub fn parse_windows_listener(raw: &str, port: u16, host: &str) -> Result<Listener, StateError> {
253 #[derive(Deserialize)]
254 #[serde(deny_unknown_fields)]
255 struct Row {
256 pid: u32,
257 process: String,
258 executable: String,
259 started: String,
260 address: String,
261 port: u16,
262 }
263 if raw.len() > 65536 {
264 return Err(invalid("listener output exceeds limit"));
265 }
266 let rows: Vec<Row> =
267 serde_json::from_str(raw).map_err(|_| invalid("invalid Windows listener output"))?;
268 let listeners: Vec<_> = rows
269 .into_iter()
270 .map(|row| Listener {
271 identity: ProcessIdentity {
272 pid: row.pid,
273 process: row.process,
274 executable: row.executable,
275 started: row.started,
276 },
277 address: row.address,
278 port: row.port,
279 })
280 .collect();
281 let listener = choose_listener(&listeners, port, host)?;
282 validate_process(&listener.identity)?;
283 Ok(listener)
284}
285fn validate_process(identity: &ProcessIdentity) -> Result<(), StateError> {
286 if identity.pid == 0
287 || identity.pid > i32::MAX as u32
288 || identity.process.is_empty()
289 || identity.executable.is_empty()
290 || identity.started.is_empty()
291 {
292 return Err(invalid("incomplete process identity"));
293 }
294 Ok(())
295}
296#[async_trait::async_trait]
297pub trait ProcessProbe: Send + Sync {
298 async fn listener(&self, port: u16, host: &str) -> Result<Listener, StateError>;
299 async fn process(&self, pid: u32) -> Result<ProcessIdentity, StateError>;
300 async fn command_line(&self, _pid: u32) -> Result<Vec<String>, StateError> {
302 Err(invalid("process command line unavailable"))
303 }
304}
305pub struct NativeProcessProbe;
306async fn output(binary: &str, args: &[&str]) -> Result<String, StateError> {
307 crate::hardware::command_output(binary, args)
308 .await
309 .map_err(|_| invalid("process identity probe failed"))
310}
311#[async_trait::async_trait]
312impl ProcessProbe for NativeProcessProbe {
313 async fn command_line(&self, pid: u32) -> Result<Vec<String>, StateError> {
314 tokio::task::spawn_blocking(move || {
315 let mut system = sysinfo::System::new();
316 let pid = sysinfo::Pid::from_u32(pid);
317 system.refresh_processes_specifics(
318 sysinfo::ProcessesToUpdate::Some(&[pid]),
319 true,
320 sysinfo::ProcessRefreshKind::nothing().with_cmd(sysinfo::UpdateKind::Always),
321 );
322 let process = system
323 .process(pid)
324 .ok_or_else(|| invalid("process command line unavailable"))?;
325 let args = process.cmd();
326 if args.is_empty()
327 || args.len() > 1024
328 || args.iter().map(|arg| arg.len()).sum::<usize>() > 65536
329 {
330 return Err(invalid("invalid process command line"));
331 }
332 args.iter()
333 .map(|arg| {
334 arg.to_str()
335 .map(str::to_owned)
336 .ok_or_else(|| invalid("non-UTF-8 process command line"))
337 })
338 .collect()
339 })
340 .await
341 .map_err(|_| invalid("process command line probe failed"))?
342 }
343
344 async fn listener(&self, port: u16, host: &str) -> Result<Listener, StateError> {
345 loopback(&format!(
346 "http://{}:{port}",
347 if host.contains(':') && !host.starts_with('[') {
348 format!("[{host}]")
349 } else {
350 host.into()
351 }
352 ))?;
353 #[cfg(windows)]
354 {
355 let script = format!(
356 "$ErrorActionPreference='Stop'; $rows=@(Get-NetTCPConnection -State Listen -LocalPort {port} | ForEach-Object {{ $proc=Get-CimInstance Win32_Process -Filter ('ProcessId='+$_.OwningProcess); [pscustomobject]@{{pid=$_.OwningProcess;process=$proc.Name;executable=$proc.ExecutablePath;started=$proc.CreationDate.ToString('yyyy-MM-dd HH:mm:ss');address=$_.LocalAddress;port=$_.LocalPort}} }}); ConvertTo-Json -InputObject $rows -Compress"
357 );
358 let raw = output(
359 "powershell.exe",
360 &["-NoProfile", "-NonInteractive", "-Command", &script],
361 )
362 .await?;
363 parse_windows_listener(&raw, port, host)
364 }
365 #[cfg(not(windows))]
366 {
367 let binary = if cfg!(target_os = "macos") {
368 "/usr/sbin/lsof"
369 } else {
370 "lsof"
371 };
372 let raw = output(
373 binary,
374 &[
375 "-nP",
376 "-a",
377 &format!("-iTCP:{port}"),
378 "-sTCP:LISTEN",
379 "-Fpn",
380 ],
381 )
382 .await?;
383 let pid = parse_lsof_listener(&raw, port, host)?;
384 let identity = self.process(pid).await?;
385 let repeated = output(
386 binary,
387 &[
388 "-nP",
389 "-a",
390 &format!("-iTCP:{port}"),
391 "-sTCP:LISTEN",
392 "-Fpn",
393 ],
394 )
395 .await?;
396 if parse_lsof_listener(&repeated, port, host)? != pid {
397 return Err(invalid("listener changed during probe"));
398 }
399 Ok(Listener {
400 identity,
401 address: host.into(),
402 port,
403 })
404 }
405 }
406 async fn process(&self, pid: u32) -> Result<ProcessIdentity, StateError> {
407 if pid == 0 || pid > i32::MAX as u32 {
408 return Err(invalid("invalid process PID"));
409 }
410 #[cfg(windows)]
411 {
412 let script = format!(
413 "$ErrorActionPreference='Stop'; $proc=Get-CimInstance Win32_Process -Filter 'ProcessId={pid}'; [pscustomobject]@{{pid=$proc.ProcessId;process=$proc.Name;executable=$proc.ExecutablePath;started=$proc.CreationDate.ToString('yyyy-MM-dd HH:mm:ss')}} | ConvertTo-Json -Compress"
414 );
415 let raw = output(
416 "powershell.exe",
417 &["-NoProfile", "-NonInteractive", "-Command", &script],
418 )
419 .await?;
420 let identity: ProcessIdentity =
421 serde_json::from_str(&raw).map_err(|_| invalid("invalid process output"))?;
422 validate_process(&identity)?;
423 if identity.pid != pid {
424 return Err(invalid("process PID drift"));
425 }
426 Ok(identity)
427 }
428 #[cfg(not(windows))]
429 {
430 let pid_text = pid.to_string();
431 let started =
432 parse_start_time(&output("/bin/ps", &["-p", &pid_text, "-o", "lstart="]).await?)?;
433 let executable = if cfg!(target_os = "macos") {
434 let raw = output(
435 "/usr/sbin/lsof",
436 &["-a", "-p", &pid_text, "-d", "txt", "-Fn"],
437 )
438 .await?;
439 let rows: Vec<_> = raw.lines().collect();
440 rows.windows(2)
441 .find_map(|pair| {
442 if pair[0] == "ftxt" {
443 pair[1].strip_prefix('n')
444 } else {
445 None
446 }
447 })
448 .ok_or_else(|| invalid("process executable unavailable"))?
449 .to_owned()
450 } else {
451 std::fs::read_link(format!("/proc/{pid}/exe"))
452 .map_err(|_| invalid("process executable unavailable"))?
453 .to_string_lossy()
454 .into_owned()
455 };
456 let executable = std::fs::canonicalize(executable)
457 .map_err(|_| invalid("process executable cannot be resolved"))?
458 .to_string_lossy()
459 .into_owned();
460 let process = std::path::Path::new(&executable)
461 .file_name()
462 .ok_or_else(|| invalid("missing process name"))?
463 .to_string_lossy()
464 .into_owned();
465 if parse_start_time(&output("/bin/ps", &["-p", &pid_text, "-o", "lstart="]).await?)?
466 != started
467 {
468 return Err(invalid("process changed during probe"));
469 }
470 let identity = ProcessIdentity {
471 pid,
472 process,
473 executable,
474 started,
475 };
476 validate_process(&identity)?;
477 Ok(identity)
478 }
479 }
480}