Skip to main content

rigspark_runtime/
identity.rs

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    /// Return argv including the executable; unavailable introspection must fail closed.
301    async fn command_line(&self, _pid: u32) -> Result<Vec<String>, StateError> {
302        Err(invalid("process command line unavailable"))
303    }
304    /// Whether any process holds `pid`; probes that cannot tell must fail closed.
305    async fn alive(&self, _pid: u32) -> Result<bool, StateError> {
306        Err(invalid("process liveness unavailable"))
307    }
308}
309pub struct NativeProcessProbe;
310async fn output(binary: &str, args: &[&str]) -> Result<String, StateError> {
311    crate::hardware::command_output(binary, args)
312        .await
313        .map_err(|_| invalid("process identity probe failed"))
314}
315#[async_trait::async_trait]
316impl ProcessProbe for NativeProcessProbe {
317    async fn alive(&self, pid: u32) -> Result<bool, StateError> {
318        if pid == 0 || pid > i32::MAX as u32 {
319            return Err(invalid("invalid process PID"));
320        }
321        tokio::task::spawn_blocking(move || {
322            let mut system = sysinfo::System::new();
323            let pid = sysinfo::Pid::from_u32(pid);
324            system.refresh_processes_specifics(
325                sysinfo::ProcessesToUpdate::Some(&[pid]),
326                true,
327                sysinfo::ProcessRefreshKind::nothing(),
328            );
329            system.process(pid).is_some()
330        })
331        .await
332        .map_err(|_| invalid("process liveness probe failed"))
333    }
334    async fn command_line(&self, pid: u32) -> Result<Vec<String>, StateError> {
335        tokio::task::spawn_blocking(move || {
336            let mut system = sysinfo::System::new();
337            let pid = sysinfo::Pid::from_u32(pid);
338            system.refresh_processes_specifics(
339                sysinfo::ProcessesToUpdate::Some(&[pid]),
340                true,
341                sysinfo::ProcessRefreshKind::nothing().with_cmd(sysinfo::UpdateKind::Always),
342            );
343            let process = system
344                .process(pid)
345                .ok_or_else(|| invalid("process command line unavailable"))?;
346            let args = process.cmd();
347            if args.is_empty()
348                || args.len() > 1024
349                || args.iter().map(|arg| arg.len()).sum::<usize>() > 65536
350            {
351                return Err(invalid("invalid process command line"));
352            }
353            args.iter()
354                .map(|arg| {
355                    arg.to_str()
356                        .map(str::to_owned)
357                        .ok_or_else(|| invalid("non-UTF-8 process command line"))
358                })
359                .collect()
360        })
361        .await
362        .map_err(|_| invalid("process command line probe failed"))?
363    }
364
365    async fn listener(&self, port: u16, host: &str) -> Result<Listener, StateError> {
366        loopback(&format!(
367            "http://{}:{port}",
368            if host.contains(':') && !host.starts_with('[') {
369                format!("[{host}]")
370            } else {
371                host.into()
372            }
373        ))?;
374        #[cfg(windows)]
375        {
376            let script = format!(
377                "$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"
378            );
379            let raw = output(
380                "powershell.exe",
381                &["-NoProfile", "-NonInteractive", "-Command", &script],
382            )
383            .await?;
384            parse_windows_listener(&raw, port, host)
385        }
386        #[cfg(not(windows))]
387        {
388            let binary = if cfg!(target_os = "macos") {
389                "/usr/sbin/lsof"
390            } else {
391                "lsof"
392            };
393            let raw = output(
394                binary,
395                &[
396                    "-nP",
397                    "-a",
398                    &format!("-iTCP:{port}"),
399                    "-sTCP:LISTEN",
400                    "-Fpn",
401                ],
402            )
403            .await?;
404            let pid = parse_lsof_listener(&raw, port, host)?;
405            let identity = self.process(pid).await?;
406            let repeated = output(
407                binary,
408                &[
409                    "-nP",
410                    "-a",
411                    &format!("-iTCP:{port}"),
412                    "-sTCP:LISTEN",
413                    "-Fpn",
414                ],
415            )
416            .await?;
417            if parse_lsof_listener(&repeated, port, host)? != pid {
418                return Err(invalid("listener changed during probe"));
419            }
420            Ok(Listener {
421                identity,
422                address: host.into(),
423                port,
424            })
425        }
426    }
427    async fn process(&self, pid: u32) -> Result<ProcessIdentity, StateError> {
428        if pid == 0 || pid > i32::MAX as u32 {
429            return Err(invalid("invalid process PID"));
430        }
431        #[cfg(windows)]
432        {
433            let script = format!(
434                "$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"
435            );
436            let raw = output(
437                "powershell.exe",
438                &["-NoProfile", "-NonInteractive", "-Command", &script],
439            )
440            .await?;
441            let identity: ProcessIdentity =
442                serde_json::from_str(&raw).map_err(|_| invalid("invalid process output"))?;
443            validate_process(&identity)?;
444            if identity.pid != pid {
445                return Err(invalid("process PID drift"));
446            }
447            Ok(identity)
448        }
449        #[cfg(not(windows))]
450        {
451            let pid_text = pid.to_string();
452            let started =
453                parse_start_time(&output("/bin/ps", &["-p", &pid_text, "-o", "lstart="]).await?)?;
454            let executable = if cfg!(target_os = "macos") {
455                let raw = output(
456                    "/usr/sbin/lsof",
457                    &["-a", "-p", &pid_text, "-d", "txt", "-Fn"],
458                )
459                .await?;
460                let rows: Vec<_> = raw.lines().collect();
461                rows.windows(2)
462                    .find_map(|pair| {
463                        if pair[0] == "ftxt" {
464                            pair[1].strip_prefix('n')
465                        } else {
466                            None
467                        }
468                    })
469                    .ok_or_else(|| invalid("process executable unavailable"))?
470                    .to_owned()
471            } else {
472                std::fs::read_link(format!("/proc/{pid}/exe"))
473                    .map_err(|_| invalid("process executable unavailable"))?
474                    .to_string_lossy()
475                    .into_owned()
476            };
477            let executable = std::fs::canonicalize(executable)
478                .map_err(|_| invalid("process executable cannot be resolved"))?
479                .to_string_lossy()
480                .into_owned();
481            let process = std::path::Path::new(&executable)
482                .file_name()
483                .ok_or_else(|| invalid("missing process name"))?
484                .to_string_lossy()
485                .into_owned();
486            if parse_start_time(&output("/bin/ps", &["-p", &pid_text, "-o", "lstart="]).await?)?
487                != started
488            {
489                return Err(invalid("process changed during probe"));
490            }
491            let identity = ProcessIdentity {
492                pid,
493                process,
494                executable,
495                started,
496            };
497            validate_process(&identity)?;
498            Ok(identity)
499        }
500    }
501}
502
503#[cfg(test)]
504mod boundary_tests {
505    use super::*;
506
507    fn identity() -> ProcessIdentity {
508        ProcessIdentity {
509            pid: 42,
510            process: "llama-server".into(),
511            executable: "/opt/llama-server".into(),
512            started: "2026-11-08 10:00:00".into(),
513        }
514    }
515    fn listener(port: u16, address: &str) -> Listener {
516        Listener {
517            identity: identity(),
518            address: address.into(),
519            port,
520        }
521    }
522    fn active() -> ServerState {
523        ServerState {
524            backend: "llamacpp".into(),
525            model_id: "qwen3:8b".into(),
526            endpoint: "http://127.0.0.1:8080".into(),
527            port: 8080,
528            owned_by_us: true,
529            pid: Some(42),
530            runtime_model_id: None,
531            context: None,
532            integrity: None,
533            local_manifest_digest: None,
534            model_path: None,
535            process_executable: Some("/opt/llama-server".into()),
536            process_started_at: Some("2026-11-08 10:00:00".into()),
537            auth_token: None,
538            cache: None,
539        }
540    }
541
542    #[test]
543    fn a_listener_must_match_both_port_and_address() {
544        let listeners = [listener(8080, "10.0.0.5"), listener(9090, "127.0.0.1")];
545        assert!(choose_listener(&listeners, 8080, "127.0.0.1").is_err());
546        assert!(choose_listener(&listeners, 9090, "localhost").is_ok());
547        // Another address on the same port, or the same address on another port, is ignored.
548        let listeners = [listener(8080, "10.0.0.5"), listener(8080, "127.0.0.1")];
549        assert!(choose_listener(&listeners, 8080, "127.0.0.1").is_ok());
550        let listeners = [listener(9090, "127.0.0.1")];
551        assert!(choose_listener(&listeners, 8080, "127.0.0.1").is_err());
552    }
553
554    #[test]
555    fn identities_hash_up_to_one_mib() {
556        assert!(hash(&"x".repeat(1048574)).is_ok());
557        assert!(hash(&"x".repeat(1048575)).is_err());
558    }
559
560    #[test]
561    fn a_capture_needs_every_identity_field() {
562        let observed = listener(8080, "127.0.0.1");
563        assert!(capture(&active(), &observed, true).is_ok());
564        for change in [
565            |i: &mut ProcessIdentity| i.executable.clear(),
566            |i: &mut ProcessIdentity| i.started.clear(),
567            |i: &mut ProcessIdentity| i.process.clear(),
568            |i: &mut ProcessIdentity| i.pid = 0,
569        ] {
570            let mut missing = observed.clone();
571            change(&mut missing.identity);
572            assert!(capture(&active(), &missing, true).is_err(), "{missing:?}");
573            // Even when the record has nothing to compare against.
574            let mut unrecorded = active();
575            unrecorded.owned_by_us = false;
576            unrecorded.pid = None;
577            unrecorded.process_executable = None;
578            unrecorded.process_started_at = None;
579            assert!(capture(&unrecorded, &observed, true).is_ok());
580            assert!(capture(&unrecorded, &missing, true).is_err(), "{missing:?}");
581        }
582    }
583
584    fn state(owned: bool) -> RuntimeState {
585        let mut entry = active();
586        entry.owned_by_us = owned;
587        RuntimeState {
588            schema_version: 2,
589            active: Some(entry),
590        }
591    }
592
593    #[test]
594    fn confirmations_name_a_target_only_when_replacing() {
595        let observed = listener(8080, "127.0.0.1");
596        let live = capture(&active(), &observed, true).unwrap();
597        let owned = state(true);
598        assert!(
599            Confirmation::prepare(Operation::ReplaceServer, &owned, None, Some(&live)).is_err()
600        );
601        assert!(
602            Confirmation::prepare(
603                Operation::ReplaceServer,
604                &owned,
605                Some("llama3:8b"),
606                Some(&live)
607            )
608            .is_ok()
609        );
610        assert!(Confirmation::prepare(Operation::Down, &owned, Some("x"), Some(&live)).is_err());
611        assert!(Confirmation::prepare(Operation::Down, &owned, None, Some(&live)).is_ok());
612        let attached = state(false);
613        let live = capture(attached.active.as_ref().unwrap(), &observed, true).unwrap();
614        assert!(
615            Confirmation::prepare(Operation::Detach, &attached, Some("x"), Some(&live)).is_err()
616        );
617        assert!(Confirmation::prepare(Operation::Detach, &attached, None, Some(&live)).is_ok());
618    }
619
620    #[test]
621    fn confirmation_targets_are_safe_model_ids() {
622        let observed = listener(8080, "127.0.0.1");
623        let live = capture(&active(), &observed, true).unwrap();
624        let owned = state(true);
625        let replace = |target: &str| {
626            Confirmation::prepare(Operation::ReplaceServer, &owned, Some(target), Some(&live))
627        };
628        assert!(replace("hf.co/owner/model:Q4_K_M").is_ok());
629        assert!(replace(&"m".repeat(8192)).is_ok());
630        for bad in ["", "-model", "a/../b", "a b", "a?b", &"m".repeat(8193)] {
631            assert!(replace(bad).is_err(), "{bad:?}");
632        }
633    }
634
635    #[test]
636    fn lsof_and_windows_listener_output_is_capped_at_64_kib() {
637        let line = "p42\nn127.0.0.1:8080\n";
638        let padded = |size: usize| format!("{line}{}", "f\n".repeat((size - line.len()) / 2));
639        assert_eq!(
640            parse_lsof_listener(&padded(65536), 8080, "127.0.0.1").unwrap(),
641            42
642        );
643        assert!(parse_lsof_listener(&padded(65538), 8080, "127.0.0.1").is_err());
644        let row = serde_json::json!([{"pid": 42, "process": "llama-server.exe",
645            "executable": "C:\\\\llama-server.exe", "started": "2026-11-08 10:00:00",
646            "address": "127.0.0.1", "port": 8080}])
647        .to_string();
648        let windows = |size: usize| format!("{row}{}", " ".repeat(size - row.len()));
649        assert!(parse_windows_listener(&windows(65536), 8080, "127.0.0.1").is_ok());
650        assert!(parse_windows_listener(&windows(65537), 8080, "127.0.0.1").is_err());
651    }
652
653    #[test]
654    fn start_times_are_one_well_formed_ps_line() {
655        assert_eq!(
656            parse_start_time("Sun Nov  8 14:28:37 2026\n").unwrap(),
657            "2026-11-08 14:28:37"
658        );
659        let padded = format!("Sun Nov  8 14:28:37 2026{}", " ".repeat(4096 - 24));
660        assert!(parse_start_time(&padded).is_ok());
661        assert!(parse_start_time(&format!("{padded} ")).is_err());
662        assert!(parse_start_time("Sun Nov 31 23:59:59 2026").is_ok());
663        for bad in [
664            "Sun Nov 8 14:28:37",
665            "Xyz Nov 8 14:28:37 2026",
666            "Sun Nov 0 14:28:37 2026",
667            "Sun Nov 32 14:28:37 2026",
668            "Sun Nov 8 14:28:37 26",
669            "Sun Nov 8 14:28:37 2O26",
670            "Sun Nov 8 14:28 2026",
671            "Sun Nov 8 14:28:37:00 2026",
672            "Sun Nov 8 1:28:37 2026",
673            "Sun Nov 8 24:28:37 2026",
674            "Sun Nov 8 14:60:37 2026",
675            "Sun Nov 8 14:28:60 2026",
676            "Sun Nov 8 aa:28:37 2026",
677        ] {
678            assert!(parse_start_time(bad).is_err(), "{bad:?}");
679        }
680    }
681
682    #[test]
683    fn process_identities_are_complete_and_in_range() {
684        assert!(validate_process(&identity()).is_ok());
685        let mut maximum = identity();
686        maximum.pid = i32::MAX as u32;
687        assert!(validate_process(&maximum).is_ok());
688        for change in [
689            |i: &mut ProcessIdentity| i.pid = 0,
690            |i: &mut ProcessIdentity| i.pid = i32::MAX as u32 + 1,
691            |i: &mut ProcessIdentity| i.process.clear(),
692            |i: &mut ProcessIdentity| i.executable.clear(),
693            |i: &mut ProcessIdentity| i.started.clear(),
694        ] {
695            let mut value = identity();
696            change(&mut value);
697            assert!(validate_process(&value).is_err(), "{value:?}");
698        }
699    }
700
701    struct Minimal;
702    #[async_trait::async_trait]
703    impl ProcessProbe for Minimal {
704        async fn listener(&self, _: u16, _: &str) -> Result<Listener, StateError> {
705            Err(invalid("none"))
706        }
707        async fn process(&self, _: u32) -> Result<ProcessIdentity, StateError> {
708            Err(invalid("none"))
709        }
710    }
711
712    #[tokio::test]
713    async fn probes_without_introspection_fail_closed() {
714        assert!(Minimal.command_line(1).await.is_err());
715        assert!(Minimal.alive(1).await.is_err());
716    }
717
718    #[tokio::test]
719    async fn the_native_probe_sees_this_process_and_refuses_impossible_pids() {
720        let me = std::process::id();
721        assert!(NativeProcessProbe.alive(me).await.unwrap());
722        let mut child = std::process::Command::new("true").spawn().unwrap();
723        let gone = child.id();
724        child.wait().unwrap();
725        assert!(!NativeProcessProbe.alive(gone).await.unwrap());
726        for pid in [0, i32::MAX as u32 + 1] {
727            assert!(NativeProcessProbe.alive(pid).await.is_err(), "{pid}");
728            assert!(NativeProcessProbe.process(pid).await.is_err(), "{pid}");
729        }
730        // The largest PID is still looked up; out-of-range PIDs never reach `ps`.
731        assert!(!NativeProcessProbe.alive(i32::MAX as u32).await.unwrap());
732        for pid in [0, i32::MAX as u32 + 1] {
733            assert_eq!(
734                NativeProcessProbe.process(pid).await.unwrap_err().message,
735                "invalid process PID"
736            );
737        }
738        assert_ne!(
739            NativeProcessProbe
740                .process(i32::MAX as u32)
741                .await
742                .unwrap_err()
743                .message,
744            "invalid process PID"
745        );
746        let args = NativeProcessProbe.command_line(me).await.unwrap();
747        let exe = std::env::current_exe().unwrap();
748        assert!(
749            args[0].ends_with(exe.file_name().unwrap().to_str().unwrap()),
750            "{args:?}"
751        );
752        assert!(NativeProcessProbe.command_line(gone).await.is_err());
753        #[cfg(target_os = "linux")]
754        {
755            let identity = NativeProcessProbe.process(me).await.unwrap();
756            assert_eq!(identity.pid, me);
757            assert_eq!(
758                identity.executable,
759                exe.canonicalize().unwrap().to_string_lossy()
760            );
761            assert_eq!(identity.process, exe.file_name().unwrap().to_string_lossy());
762            assert_eq!(identity.started.len(), "2026-11-08 14:28:37".len());
763        }
764    }
765
766    #[cfg(target_os = "linux")]
767    #[tokio::test]
768    async fn command_lines_are_capped_at_1024_arguments_and_64_kib() {
769        // `sh -c 'sleep 30' <name> <args…>` keeps the arguments on a live process.
770        async fn probe(args: &[String]) -> Result<Vec<String>, StateError> {
771            let mut child = std::process::Command::new("/bin/sh")
772                .args(["-c", "sleep 30", "s"])
773                .args(args)
774                .spawn()
775                .unwrap();
776            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
777            let result = NativeProcessProbe.command_line(child.id()).await;
778            child.kill().unwrap();
779            child.wait().unwrap();
780            result
781        }
782        // "/bin/sh" "-c" "sleep 30" "s" are four arguments and 18 bytes.
783        assert_eq!(probe(&vec!["a".into(); 1020]).await.unwrap().len(), 1024);
784        assert!(probe(&vec!["a".into(); 1021]).await.is_err());
785        assert!(probe(&["b".repeat(65536 - 18)]).await.is_ok());
786        assert!(probe(&["b".repeat(65537 - 18)]).await.is_err());
787    }
788
789    #[cfg(target_os = "linux")]
790    #[tokio::test]
791    async fn the_native_probe_finds_the_process_listening_on_a_port() {
792        if std::process::Command::new("lsof")
793            .arg("-v")
794            .output()
795            .is_err()
796        {
797            eprintln!("lsof is not installed; skipping");
798            return;
799        }
800        let socket = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
801        let port = socket.local_addr().unwrap().port();
802        let found = NativeProcessProbe
803            .listener(port, "127.0.0.1")
804            .await
805            .unwrap();
806        assert_eq!(found.identity.pid, std::process::id());
807        assert_eq!(found.port, port);
808        drop(socket);
809    }
810
811    #[cfg(unix)]
812    #[tokio::test]
813    async fn the_native_probe_reads_command_output() {
814        assert_eq!(output("echo", &["hello"]).await.unwrap().trim(), "hello");
815    }
816}