diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 5b48a1db..36775765 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -650,6 +650,7 @@ or removing a command fails until the table changes in the same commit. | `processLifecycle.inventory` | Group a process snapshot of one Lithe instance into terminals, Agent tasks and background services | | `processLifecycle.settle` | Turn confirmation answers into what ends, what is kept and the updated settings | | `processMemory.summarize` | Sum a process table's memory, compressed memory, graphics memory and processor and graphics use by part of one Lithe instance: the host, language servers, plugin services, system helpers and other child processes | +| `process.listeningPorts` | Filter, normalize, deduplicate, and format listening TCP ports for one run process tree | | `markdown.render` | Renders and sanitizes shared Markdown | | `markdown.outline` | Outlines the headings of shared Markdown as a document-symbol tree | | `markdown.resolveReference` | Decides what a link or an image of a rendered Markdown document points at | @@ -6295,6 +6296,32 @@ A table without the host or with a repeated process ID, or a `logicalProcessors` of 0, is `invalid_request`. Fixtures live in `rust/fixtures/process-lifecycle/memory-summary-v1.json`. +`process.listeningPorts` accepts `{ rootProcessId, processes, sockets, +excludePorts?, limit? }` and returns `{ schemaVersion, ports, truncated }` for +one running session's process tree: + +- `rootProcessId` must be a positive integer. `processes` is a list of + `{ processId, parentProcessId, startTime? }`; parent links where + `parent.startTime > child.startTime` are ignored as PID reuse, and + `rootProcessId` itself is always included even when `processes` is empty. +- `sockets` is a list of `{ processId, address, port }`. Addresses are trimmed, + unwrapped from `[...]`, stripped of IPv6 `%zone` suffixes, mapped from `""` / + `"*"` to `"0.0.0.0"`, and unwrapped from IPv4-mapped IPv6 `::ffff:a.b.c.d` to + IPv4; non-IP strings return `invalid_request`. +- Sockets with `port == 0`, ports listed in `excludePorts` (such as an + attached debugger port), or `processId` outside the tree are filtered out. +- Multiple sockets sharing a port (for example dual-stack `0.0.0.0` + `::`) + collapse deterministically to one entry, preferring loopback/unspecified binds, + then IPv4 over IPv6, then loopback over unspecified, then lowest `processId`. +- Loopback and unspecified binds (`127.0.0.0/8`, `0.0.0.0`, `::1`, `::`) format + `label` as `:` and `url` as `http://localhost:`; specific + interface binds format `label` as `:` / `[]:` and `url` + as `http://:` / `http://[]:`. +- Results are ordered ascending by `port`; `limit` defaults to 8 and is clamped + to `1..=32`, with `truncated: true` when more matching ports existed. + +Fixtures live in `rust/fixtures/process-lifecycle/listening-ports-v1.json`. + ## Local IDE capability broker `ideHost.control` accepts `{action, arguments}` and delegates to the native diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 29646957..e0ee6d9f 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -130,6 +130,9 @@ pub enum CoreCommand { ProcessLifecycleSettle, /// Sums a process table's memory by part of the instance (`processMemory.summarize`). ProcessMemorySummarize, + /// Filters, normalizes, and formats listening TCP ports of one process tree + /// (`process.listeningPorts`). + ProcessListeningPorts, /// Renders and sanitizes shared Markdown (`markdown.render`). MarkdownRender, /// Outlines the headings of shared Markdown as document symbols (`markdown.outline`). @@ -1336,6 +1339,7 @@ impl CoreCommand { "processLifecycle.inventory" => Some(Self::ProcessLifecycleInventory), "processLifecycle.settle" => Some(Self::ProcessLifecycleSettle), "processMemory.summarize" => Some(Self::ProcessMemorySummarize), + "process.listeningPorts" => Some(Self::ProcessListeningPorts), "markdown.render" => Some(Self::MarkdownRender), "markdown.outline" => Some(Self::MarkdownOutline), "markdown.resolveReference" => Some(Self::MarkdownResolveReference), @@ -1820,6 +1824,10 @@ mod tests { CoreCommand::parse("processMemory.summarize"), Some(CoreCommand::ProcessMemorySummarize) )); + assert!(matches!( + CoreCommand::parse("process.listeningPorts"), + Some(CoreCommand::ProcessListeningPorts) + )); } #[test] diff --git a/rust/crates/core/src/runtime/dispatcher.rs b/rust/crates/core/src/runtime/dispatcher.rs index 044b0e8e..8b135290 100644 --- a/rust/crates/core/src/runtime/dispatcher.rs +++ b/rust/crates/core/src/runtime/dispatcher.rs @@ -462,6 +462,25 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon ), } } + CoreCommand::ProcessListeningPorts => { + match serde_json::from_value::( + parsed.payload, + ) + .map_err(|error| error.to_string()) + .and_then(|request| { + lithe_process::ports::resolve(&request).map_err(|error| error.to_string()) + }) { + Ok(ports) => CoreResponse::success( + id, + serde_json::to_value(ports).expect("listening ports response should encode"), + ), + Err(details) => CoreResponse::failure( + id, + CoreError::new(ErrorCode::InvalidRequest, "Invalid listening ports request") + .with_details(details), + ), + } + } CoreCommand::Editor(command) => editor::dispatch(command, id, parsed.payload, document), CoreCommand::WorkbenchChromeLayoutReduce => { rules_response(id, "workbench.chromeLayout.reduce", parsed.payload) diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index 45ca6dc1..b9df12bb 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -197,8 +197,10 @@ pub(crate) fn is_hot(method: &str) -> bool { method, "workspace.filterChanges" | "lsp.workspaceFilesChanged" | "git.classifyMetadataChanges" ) - // The status bar sums the instance's memory every few seconds while it is shown. + // The status bar sums the instance's memory every few seconds while it is shown, + // and active runs probe their process tree's listening ports periodically. || method == "processMemory.summarize" + || method == "process.listeningPorts" } /// Explicit host provenance wins; Git provenance covers hosts that send only that. @@ -275,6 +277,7 @@ mod tests { "git.classifyMetadataChanges", "debug.transport.handle", "processMemory.summarize", + "process.listeningPorts", ] { assert!(is_hot(method), "{method}"); } diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 7bad3c33..02dff963 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -54,6 +54,7 @@ mod plugin_settings_documents; mod plugin_source_settings; mod plugin_views; mod process_memory; +mod process_ports; mod project; mod project_generators; mod project_tree; diff --git a/rust/crates/core/src/tests/process_ports.rs b/rust/crates/core/src/tests/process_ports.rs new file mode 100644 index 00000000..4470984e --- /dev/null +++ b/rust/crates/core/src/tests/process_ports.rs @@ -0,0 +1,33 @@ +//! `process.listeningPorts` against the shared listening-ports fixture. + +use serde_json::{json, Value}; + +fn run(request: &Value) -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"command": "process.listeningPorts", "payload": request}).to_string(), + )) + .unwrap() +} + +#[test] +fn shared_listening_ports_fixture_runs_every_case() { + let fixture: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../fixtures/process-lifecycle/listening-ports-v1.json" + ))) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let response = run(&case["request"]); + assert_eq!(response["ok"], true, "case {}: {response}", case["name"]); + assert_eq!(response["data"], case["expected"], "case {}", case["name"]); + } + for case in fixture["invalid"].as_array().unwrap() { + let response = run(&case["request"]); + assert_eq!(response["ok"], false, "case {}: {response}", case["name"]); + assert_eq!( + response["error"]["code"], "invalid_request", + "case {}", + case["name"] + ); + } +} diff --git a/rust/crates/process/src/lib.rs b/rust/crates/process/src/lib.rs index c2dc3438..128a5685 100644 --- a/rust/crates/process/src/lib.rs +++ b/rust/crates/process/src/lib.rs @@ -4,3 +4,4 @@ pub mod inventory; pub mod lifecycle; pub mod memory; +pub mod ports; diff --git a/rust/crates/process/src/ports.rs b/rust/crates/process/src/ports.rs new file mode 100644 index 00000000..7fb00295 --- /dev/null +++ b/rust/crates/process/src/ports.rs @@ -0,0 +1,596 @@ +//! Listening TCP port attribution, normalization, and formatting for one run process tree. +//! +//! Hosts supply the OS process table and raw listening sockets for candidate +//! processes; Core filters sockets to the run's live process tree (ignoring +//! reused PIDs whose parent started later and any caller-excluded debug ports), +//! normalizes bind addresses, deduplicates dual-stack bindings, and formats +//! stable display labels and browser URLs. Fixtures live in +//! `rust/fixtures/process-lifecycle/listening-ports-v1.json`. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + +use serde::{Deserialize, Serialize}; + +/// Schema version of [`ListeningPortsResponse`]. +pub const SCHEMA_VERSION: u32 = 1; + +/// Default maximum number of listening ports returned in one response. +const DEFAULT_LIMIT: usize = 8; + +/// Hard upper bound on listening ports returned in one response. +const MAX_LIMIT: usize = 32; + +/// One row of the host's process table used to reconstruct the run's process tree. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PortProcess { + /// Operating-system process ID. + pub process_id: i64, + /// Parent process ID reported by the operating system. + pub parent_process_id: i64, + /// Start time in microseconds since 1970. When both child and parent carry + /// a start time and the parent started later, the parent ID was reused and + /// the parent link is ignored. + #[serde(default)] + pub start_time: Option, +} + +/// One raw listening TCP socket observed by the host. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ListeningSocket { + /// Process ID that owns the listening socket descriptor. + pub process_id: i64, + /// Bound IP address string (IPv4, IPv6, bracketed IPv6, optional `%zone`, + /// or `""` / `"*"` for unspecified wildcard). + pub address: String, + /// Bound TCP port number (`1..=65535` for live sockets). + pub port: u16, +} + +/// Request of `process.listeningPorts`. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ListeningPortsRequest { + /// Root process ID of the run session. Must be positive. + pub root_process_id: i64, + /// Process rows used to find descendants of [`Self::root_process_id`]. + #[serde(default)] + pub processes: Vec, + /// Candidate listening TCP sockets read by the host. + #[serde(default)] + pub sockets: Vec, + /// Ports to omit from the result, such as an attached debugger port. + #[serde(default)] + pub exclude_ports: Vec, + /// Maximum number of deduplicated ports to return, defaulted to 8 and + /// clamped to `1..=32`. + #[serde(default)] + pub limit: Option, +} + +/// One deduplicated, normalized listening TCP port of a run. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ListeningPort { + /// TCP port number. + pub port: u16, + /// Canonical bound IP address (`"0.0.0.0"`, `"127.0.0.1"`, `"::"`, etc.). + pub address: String, + /// Compact display label (`":8080"`, `"192.168.1.5:8080"`, or `"[fe80::1]:8080"`). + pub label: String, + /// Browser-ready HTTP URL (`"http://localhost:8080"`, `"http://192.168.1.5:8080"`, etc.). + pub url: String, + /// Process ID selected as the owner of this port. + pub process_id: i64, +} + +/// Response of `process.listeningPorts`. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ListeningPortsResponse { + /// Contract schema version (`1`). + pub schema_version: u32, + /// Deduplicated listening ports ordered ascending by [`ListeningPort::port`]. + pub ports: Vec, + /// Whether more than the effective limit of ports matched before truncation. + pub truncated: bool, +} + +/// Resolves, normalizes, deduplicates, and formats listening TCP ports belonging +/// to the process tree rooted at `request.root_process_id`. +pub fn resolve(request: &ListeningPortsRequest) -> Result { + if request.root_process_id <= 0 { + return Err("rootProcessId must be positive".to_string()); + } + + let tree_pids = collect_tree_pids(request.root_process_id, &request.processes)?; + let excluded: HashSet = request.exclude_ports.iter().copied().collect(); + let limit = request.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT); + + #[derive(Clone)] + struct Candidate { + ip: IpAddr, + address: String, + process_id: i64, + } + + let mut by_port: BTreeMap = BTreeMap::new(); + for socket in &request.sockets { + let ip = normalize_address(&socket.address)?; + if socket.port == 0 + || excluded.contains(&socket.port) + || !tree_pids.contains(&socket.process_id) + { + continue; + } + let address = ip.to_string(); + let candidate = Candidate { + ip, + address, + process_id: socket.process_id, + }; + let replace = match by_port.get(&socket.port) { + None => true, + Some(existing) => { + candidate_rank(candidate.ip, candidate.process_id, &candidate.address) + < candidate_rank(existing.ip, existing.process_id, &existing.address) + } + }; + if replace { + by_port.insert(socket.port, candidate); + } + } + + let total = by_port.len(); + let truncated = total > limit; + let ports = by_port + .into_iter() + .take(limit) + .map(|(port, candidate)| ListeningPort { + port, + address: candidate.address, + label: format_label(candidate.ip, port), + url: format_url(candidate.ip, port), + process_id: candidate.process_id, + }) + .collect(); + + Ok(ListeningPortsResponse { + schema_version: SCHEMA_VERSION, + ports, + truncated, + }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum TreeMembership { + Unknown, + Visiting, + InTree, + OutOfTree, +} + +/// Builds the set of PIDs in the process tree rooted at `root_pid`, rejecting +/// duplicate process rows and ignoring parent links whose parent started after +/// its reported child (indicating PID reuse). +fn collect_tree_pids(root_pid: i64, processes: &[PortProcess]) -> Result, String> { + let mut positions = HashMap::with_capacity(processes.len()); + for (index, process) in processes.iter().enumerate() { + if positions.insert(process.process_id, index).is_some() { + return Err(format!( + "process {} appears more than once", + process.process_id + )); + } + } + + let mut states = vec![TreeMembership::Unknown; processes.len()]; + let mut path = Vec::new(); + + for start in 0..processes.len() { + if !matches!(states[start], TreeMembership::Unknown) { + continue; + } + path.clear(); + let mut current = start; + let resolved = loop { + match states[current] { + TreeMembership::InTree => break TreeMembership::InTree, + TreeMembership::OutOfTree => break TreeMembership::OutOfTree, + TreeMembership::Visiting => { + // Any cycle that never visited the root cannot descend from it. + let at = path + .iter() + .position(|&idx| idx == current) + .expect("visiting node must be on current path"); + for &member in &path[at..] { + states[member] = TreeMembership::OutOfTree; + } + path.truncate(at); + break TreeMembership::OutOfTree; + } + TreeMembership::Unknown => {} + } + states[current] = TreeMembership::Visiting; + path.push(current); + + let process = &processes[current]; + if process.process_id == root_pid { + break TreeMembership::InTree; + } + if process.parent_process_id == root_pid && !positions.contains_key(&root_pid) { + // Allow callers that pass only descendants without the root row itself. + break TreeMembership::InTree; + } + let Some(&parent) = positions.get(&process.parent_process_id) else { + break TreeMembership::OutOfTree; + }; + if parent == current { + break TreeMembership::OutOfTree; + } + if let (Some(child_start), Some(parent_start)) = + (process.start_time, processes[parent].start_time) + { + if parent_start > child_start { + break TreeMembership::OutOfTree; + } + } + current = parent; + }; + + for &member in &path { + states[member] = resolved; + } + } + + let mut tree_pids = HashSet::new(); + tree_pids.insert(root_pid); + for (process, state) in processes.iter().zip(states) { + if state == TreeMembership::InTree { + tree_pids.insert(process.process_id); + } + } + Ok(tree_pids) +} + +/// Normalizes a socket bind address into a canonical [`IpAddr`], folding +/// empty/wildcard strings to `0.0.0.0` and IPv4-mapped IPv6 (`::ffff:a.b.c.d`) +/// to IPv4. +fn normalize_address(raw: &str) -> Result { + let trimmed = raw.trim(); + let unwrapped = if trimmed.starts_with('[') && trimmed.ends_with(']') && trimmed.len() >= 2 { + &trimmed[1..trimmed.len() - 1] + } else { + trimmed + }; + if unwrapped.is_empty() || unwrapped == "*" { + return Ok(IpAddr::V4(Ipv4Addr::UNSPECIFIED)); + } + let without_zone = match unwrapped.split_once('%') { + Some((addr, _zone)) if addr.contains(':') => addr, + _ => unwrapped, + }; + let parsed: IpAddr = without_zone + .parse() + .map_err(|_| format!("invalid listening socket address: {raw}"))?; + Ok(unwrap_ipv4_mapped(parsed)) +} + +fn unwrap_ipv4_mapped(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V4(v4) => IpAddr::V4(v4), + IpAddr::V6(v6) => match ipv4_mapped_octets(v6) { + Some(v4) => IpAddr::V4(v4), + None => IpAddr::V6(v6), + }, + } +} + +fn ipv4_mapped_octets(v6: Ipv6Addr) -> Option { + match v6.octets() { + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => Some(Ipv4Addr::new(a, b, c, d)), + _ => None, + } +} + +fn is_local_bind(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => v4.is_loopback() || v4.is_unspecified(), + IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(), + } +} + +fn candidate_rank(ip: IpAddr, process_id: i64, address: &str) -> (bool, bool, bool, i64, &str) { + ( + !is_local_bind(ip), + !ip.is_ipv4(), + !ip.is_loopback(), + process_id, + address, + ) +} + +fn format_label(ip: IpAddr, port: u16) -> String { + if is_local_bind(ip) { + return format!(":{port}"); + } + match ip { + IpAddr::V4(v4) => format!("{v4}:{port}"), + IpAddr::V6(v6) => format!("[{v6}]:{port}"), + } +} + +fn format_url(ip: IpAddr, port: u16) -> String { + if is_local_bind(ip) { + return format!("http://localhost:{port}"); + } + match ip { + IpAddr::V4(v4) => format!("http://{v4}:{port}"), + IpAddr::V6(v6) => format!("http://[{v6}]:{port}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn proc_row(process_id: i64, parent_process_id: i64, start_time: Option) -> PortProcess { + PortProcess { + process_id, + parent_process_id, + start_time, + } + } + + fn sock(process_id: i64, address: &str, port: u16) -> ListeningSocket { + ListeningSocket { + process_id, + address: address.to_string(), + port, + } + } + + #[test] + fn resolves_tree_descendants_even_when_root_is_absent_or_processes_empty() { + let root_only = resolve(&ListeningPortsRequest { + root_process_id: 500, + processes: Vec::new(), + sockets: vec![sock(500, "127.0.0.1", 8080), sock(999, "127.0.0.1", 9090)], + exclude_ports: Vec::new(), + limit: None, + }) + .unwrap(); + assert_eq!(root_only.schema_version, 1); + assert_eq!(root_only.ports.len(), 1); + assert_eq!(root_only.ports[0].port, 8080); + assert_eq!(root_only.ports[0].label, ":8080"); + assert_eq!(root_only.ports[0].url, "http://localhost:8080"); + + let with_child = resolve(&ListeningPortsRequest { + root_process_id: 500, + processes: vec![proc_row(501, 500, Some(200)), proc_row(502, 501, Some(300))], + sockets: vec![sock(502, "0.0.0.0", 8081), sock(600, "0.0.0.0", 8082)], + exclude_ports: Vec::new(), + limit: None, + }) + .unwrap(); + assert_eq!(with_child.ports.len(), 1); + assert_eq!(with_child.ports[0].port, 8081); + assert_eq!(with_child.ports[0].process_id, 502); + } + + #[test] + fn ignores_reused_pid_parent_links_and_cycles() { + let response = resolve(&ListeningPortsRequest { + root_process_id: 100, + processes: vec![ + proc_row(100, 1, Some(5000)), + // Child started BEFORE root 100 => 100 was reused; must NOT belong to tree. + proc_row(200, 100, Some(1000)), + // Valid child started AFTER root 100. + proc_row(201, 100, Some(5500)), + // Disconnected cycle. + proc_row(300, 301, None), + proc_row(301, 300, None), + ], + sockets: vec![ + sock(200, "127.0.0.1", 7000), + sock(201, "127.0.0.1", 8080), + sock(300, "127.0.0.1", 7001), + ], + exclude_ports: Vec::new(), + limit: None, + }) + .unwrap(); + assert_eq!(response.ports.len(), 1); + assert_eq!(response.ports[0].port, 8080); + assert_eq!(response.ports[0].process_id, 201); + } + + #[test] + fn excludes_specified_ports_and_zero_ports() { + let response = resolve(&ListeningPortsRequest { + root_process_id: 100, + processes: vec![proc_row(100, 1, None)], + sockets: vec![ + sock(100, "127.0.0.1", 0), + sock(100, "127.0.0.1", 5005), + sock(100, "0.0.0.0", 8080), + ], + exclude_ports: vec![5005], + limit: None, + }) + .unwrap(); + assert_eq!(response.ports.len(), 1); + assert_eq!(response.ports[0].port, 8080); + } + + #[test] + fn deduplicates_dual_stack_and_worker_sockets_deterministically() { + let response = resolve(&ListeningPortsRequest { + root_process_id: 100, + processes: vec![ + proc_row(100, 1, None), + proc_row(101, 100, None), + proc_row(102, 100, None), + ], + sockets: vec![ + sock(102, "192.168.1.5", 8080), + sock(102, "::", 8080), + sock(101, "0.0.0.0", 8080), + sock(102, "[::ffff:127.0.0.1]", 8081), + sock(101, "::1", 8081), + sock(101, "192.168.1.10", 9000), + sock(102, "10.0.0.2", 9000), + ], + exclude_ports: Vec::new(), + limit: None, + }) + .unwrap(); + assert_eq!(response.ports.len(), 3); + // 8080: IPv4 unspecified 0.0.0.0 beats IPv6 :: and specific interface. + assert_eq!(response.ports[0].port, 8080); + assert_eq!(response.ports[0].address, "0.0.0.0"); + assert_eq!(response.ports[0].label, ":8080"); + assert_eq!(response.ports[0].url, "http://localhost:8080"); + assert_eq!(response.ports[0].process_id, 101); + // 8081: IPv4-mapped ::ffff:127.0.0.1 unwraps to IPv4 127.0.0.1 and beats ::1. + assert_eq!(response.ports[1].port, 8081); + assert_eq!(response.ports[1].address, "127.0.0.1"); + assert_eq!(response.ports[1].label, ":8081"); + assert_eq!(response.ports[1].url, "http://localhost:8081"); + // 9000: two specific IPv4 addresses => lowest process_id (101) wins. + assert_eq!(response.ports[2].port, 9000); + assert_eq!(response.ports[2].address, "192.168.1.10"); + assert_eq!(response.ports[2].label, "192.168.1.10:9000"); + assert_eq!(response.ports[2].url, "http://192.168.1.10:9000"); + assert_eq!(response.ports[2].process_id, 101); + } + + #[test] + fn normalizes_wildcards_brackets_zones_and_formats_ipv6_urls() { + let response = resolve(&ListeningPortsRequest { + root_process_id: 100, + processes: Vec::new(), + sockets: vec![ + sock(100, "", 3000), + sock(100, " * ", 3001), + sock(100, "[::1]", 3002), + sock(100, "[fe80::1%en0]", 3003), + sock(100, "2001:db8::5", 3004), + ], + exclude_ports: Vec::new(), + limit: None, + }) + .unwrap(); + assert_eq!(response.ports[0].address, "0.0.0.0"); + assert_eq!(response.ports[0].label, ":3000"); + assert_eq!(response.ports[0].url, "http://localhost:3000"); + + assert_eq!(response.ports[1].address, "0.0.0.0"); + assert_eq!(response.ports[1].label, ":3001"); + + assert_eq!(response.ports[2].address, "::1"); + assert_eq!(response.ports[2].label, ":3002"); + assert_eq!(response.ports[2].url, "http://localhost:3002"); + + assert_eq!(response.ports[3].address, "fe80::1"); + assert_eq!(response.ports[3].label, "[fe80::1]:3003"); + assert_eq!(response.ports[3].url, "http://[fe80::1]:3003"); + + assert_eq!(response.ports[4].address, "2001:db8::5"); + assert_eq!(response.ports[4].label, "[2001:db8::5]:3004"); + assert_eq!(response.ports[4].url, "http://[2001:db8::5]:3004"); + } + + #[test] + fn enforces_limit_clamping_and_truncation_flag() { + let sockets = (1..=40).map(|i| sock(100, "127.0.0.1", 8000 + i)).collect(); + let default_capped = resolve(&ListeningPortsRequest { + root_process_id: 100, + processes: Vec::new(), + sockets, + exclude_ports: Vec::new(), + limit: None, + }) + .unwrap(); + assert_eq!(default_capped.ports.len(), 8); + assert!(default_capped.truncated); + assert_eq!(default_capped.ports[0].port, 8001); + assert_eq!(default_capped.ports[7].port, 8008); + + let min_clamped = resolve(&ListeningPortsRequest { + root_process_id: 100, + processes: Vec::new(), + sockets: vec![sock(100, "127.0.0.1", 8080), sock(100, "127.0.0.1", 8081)], + exclude_ports: Vec::new(), + limit: Some(0), + }) + .unwrap(); + assert_eq!(min_clamped.ports.len(), 1); + assert!(min_clamped.truncated); + + let max_clamped = resolve(&ListeningPortsRequest { + root_process_id: 100, + processes: Vec::new(), + sockets: (1..=40).map(|i| sock(100, "127.0.0.1", 9000 + i)).collect(), + exclude_ports: Vec::new(), + limit: Some(100), + }) + .unwrap(); + assert_eq!(max_clamped.ports.len(), 32); + assert!(max_clamped.truncated); + } + + #[test] + fn rejects_invalid_root_duplicate_processes_and_malformed_addresses() { + assert!(resolve(&ListeningPortsRequest { + root_process_id: 0, + processes: Vec::new(), + sockets: Vec::new(), + exclude_ports: Vec::new(), + limit: None, + }) + .is_err()); + + assert!(resolve(&ListeningPortsRequest { + root_process_id: -5, + processes: Vec::new(), + sockets: Vec::new(), + exclude_ports: Vec::new(), + limit: None, + }) + .is_err()); + + assert!(resolve(&ListeningPortsRequest { + root_process_id: 100, + processes: vec![proc_row(100, 1, None), proc_row(100, 1, None)], + sockets: Vec::new(), + exclude_ports: Vec::new(), + limit: None, + }) + .is_err()); + + for bad in [ + "not-an-ip", + "localhost", + "[::1", + "999.999.999.999", + "127.0.0.1%eth0", + ] { + assert!( + resolve(&ListeningPortsRequest { + root_process_id: 100, + processes: Vec::new(), + sockets: vec![sock(100, bad, 8080)], + exclude_ports: Vec::new(), + limit: None, + }) + .is_err(), + "expected {bad} to be rejected" + ); + } + } +} diff --git a/rust/fixtures/process-lifecycle/listening-ports-v1.json b/rust/fixtures/process-lifecycle/listening-ports-v1.json new file mode 100644 index 00000000..53eed4e4 --- /dev/null +++ b/rust/fixtures/process-lifecycle/listening-ports-v1.json @@ -0,0 +1,192 @@ +{ + "schemaVersion": 1, + "cases": [ + { + "name": "filters process tree, excludes debug port, and deduplicates dual-stack binds", + "request": { + "rootProcessId": 100, + "processes": [ + { + "processId": 100, + "parentProcessId": 1, + "startTime": 5000 + }, + { + "processId": 101, + "parentProcessId": 100, + "startTime": 5500 + }, + { + "processId": 102, + "parentProcessId": 101, + "startTime": 6000 + }, + { + "processId": 200, + "parentProcessId": 100, + "startTime": 1000 + }, + { + "processId": 300, + "parentProcessId": 1, + "startTime": 5100 + } + ], + "sockets": [ + { + "processId": 102, + "address": "::", + "port": 8080 + }, + { + "processId": 101, + "address": "0.0.0.0", + "port": 8080 + }, + { + "processId": 100, + "address": "127.0.0.1", + "port": 5005 + }, + { + "processId": 102, + "address": "[::ffff:127.0.0.1]", + "port": 9090 + }, + { + "processId": 101, + "address": "192.168.1.5", + "port": 8443 + }, + { + "processId": 102, + "address": "[fe80::1%en0]", + "port": 9091 + }, + { + "processId": 200, + "address": "127.0.0.1", + "port": 7000 + }, + { + "processId": 300, + "address": "127.0.0.1", + "port": 7001 + } + ], + "excludePorts": [5005], + "limit": 8 + }, + "expected": { + "schemaVersion": 1, + "ports": [ + { + "port": 8080, + "address": "0.0.0.0", + "label": ":8080", + "url": "http://localhost:8080", + "processId": 101 + }, + { + "port": 8443, + "address": "192.168.1.5", + "label": "192.168.1.5:8443", + "url": "http://192.168.1.5:8443", + "processId": 101 + }, + { + "port": 9090, + "address": "127.0.0.1", + "label": ":9090", + "url": "http://localhost:9090", + "processId": 102 + }, + { + "port": 9091, + "address": "fe80::1", + "label": "[fe80::1]:9091", + "url": "http://[fe80::1]:9091", + "processId": 102 + } + ], + "truncated": false + } + }, + { + "name": "applies limit and sets truncated", + "request": { + "rootProcessId": 100, + "processes": [], + "sockets": [ + { + "processId": 100, + "address": "*", + "port": 3002 + }, + { + "processId": 100, + "address": "", + "port": 3000 + }, + { + "processId": 100, + "address": "::1", + "port": 3001 + } + ], + "limit": 2 + }, + "expected": { + "schemaVersion": 1, + "ports": [ + { + "port": 3000, + "address": "0.0.0.0", + "label": ":3000", + "url": "http://localhost:3000", + "processId": 100 + }, + { + "port": 3001, + "address": "::1", + "label": ":3001", + "url": "http://localhost:3001", + "processId": 100 + } + ], + "truncated": true + } + } + ], + "invalid": [ + { + "name": "non-positive rootProcessId", + "request": { + "rootProcessId": 0, + "processes": [], + "sockets": [] + } + }, + { + "name": "duplicate processId", + "request": { + "rootProcessId": 100, + "processes": [ + { "processId": 100, "parentProcessId": 1 }, + { "processId": 100, "parentProcessId": 1 } + ], + "sockets": [] + } + }, + { + "name": "malformed socket address", + "request": { + "rootProcessId": 100, + "processes": [], + "sockets": [ + { "processId": 100, "address": "not-an-ip", "port": 8080 } + ] + } + } + ] +}