1use crate::caller_identity::CallerIdentity;
5use std::path::Path;
6
7const SUMMARY_LIMIT: usize = 200;
8const TARGET_LIMIT: usize = 64;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum PrivilegedOperation<'a> {
14 Restart { module_id: &'a str },
15 Swap { module_id: &'a str },
16 Reload { module_id: &'a str },
17 Rescan,
18 SetEnabled { module_id: &'a str, enabled: bool },
19 ReleaseReserved { module_id: &'a str },
20}
21
22impl PrivilegedOperation<'_> {
23 fn description(self) -> String {
24 let (verb, target) = match self {
25 Self::Restart { module_id } => ("Restart module", module_id),
26 Self::Swap { module_id } => ("Swap module", module_id),
27 Self::Reload { module_id } => ("Reload module", module_id),
28 Self::SetEnabled { module_id, enabled } => (
29 if enabled {
30 "Start module"
31 } else {
32 "Stop module"
33 },
34 module_id,
35 ),
36 Self::ReleaseReserved { module_id } => ("Release reserved module id", module_id),
37 Self::Rescan => {
38 return "Apply the daemon config file as it reads when approved (rescan)".into();
41 }
42 };
43 format!("{verb} {}", truncate_target(&sanitize(target)))
44 }
45}
46
47pub fn prompt_text(operation: PrivilegedOperation<'_>, caller: &CallerIdentity) -> String {
50 match caller.pid().zip(caller.executable()) {
51 Some((pid, path)) => resolved_prompt_text(operation, pid, path),
52 None => format!(
53 "{} — requested by an unidentified local process",
54 operation.description()
55 ),
56 }
57}
58
59fn resolved_prompt_text(operation: PrivilegedOperation<'_>, pid: u32, path: &Path) -> String {
60 let prefix = format!("{} — requested by pid {pid} (", operation.description());
61 let path_budget = SUMMARY_LIMIT - prefix.chars().count() - 1;
62 let path = shorten_path(&sanitize(&path.to_string_lossy()), path_budget);
63 format!("{prefix}{path})")
64}
65
66fn sanitize(text: &str) -> String {
67 text.chars()
68 .map(|c| if forbidden(c) { '?' } else { c })
69 .collect()
70}
71
72pub(crate) fn gate_prompt_text(
75 description: &str,
76 targets: &[&str],
77 caller: &CallerIdentity,
78) -> Option<String> {
79 if sanitize(description) != description
80 || targets
81 .iter()
82 .any(|target| target.chars().count() > TARGET_LIMIT || sanitize(target) != *target)
83 {
84 return None;
85 }
86 let text = match caller.pid().zip(caller.executable()) {
87 Some((pid, path)) => {
88 let prefix = format!("{description} — requested by pid {pid} (");
89 let budget = SUMMARY_LIMIT.checked_sub(prefix.chars().count() + 1)?;
90 if budget < 3 {
91 return None;
92 }
93 format!(
94 "{prefix}{})",
95 shorten_path(&sanitize(&path.to_string_lossy()), budget)
96 )
97 }
98 None => format!("{description} — requested by an unidentified local process"),
99 };
100 (text.chars().count() <= SUMMARY_LIMIT).then_some(text)
101}
102
103fn forbidden(c: char) -> bool {
104 c.is_control()
109 || matches!(c,
110 '\u{00ad}' | '\u{034f}' | '\u{061c}' | '\u{115f}' | '\u{1160}' |
111 '\u{17b4}' | '\u{17b5}' | '\u{180b}'..='\u{180f}' |
112 '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' |
113 '\u{2060}'..='\u{206f}' | '\u{3164}' | '\u{fe00}'..='\u{fe0f}' |
114 '\u{feff}' | '\u{ffa0}' | '\u{fff9}'..='\u{fffb}' |
115 '\u{1bca0}'..='\u{1bca3}' | '\u{1d173}'..='\u{1d17a}' |
116 '\u{e0000}'..='\u{e0fff}')
117}
118
119fn truncate_target(target: &str) -> String {
120 if target.chars().count() <= TARGET_LIMIT {
121 target.to_owned()
122 } else {
123 target.chars().take(TARGET_LIMIT - 1).chain(['…']).collect()
124 }
125}
126
127fn shorten_path(path: &str, budget: usize) -> String {
128 let count = path.chars().count();
129 if count <= budget {
130 return path.to_owned();
131 }
132 let component = path.rsplit(['/', '\\']).next().unwrap_or(path);
133 if component.chars().count() < budget {
134 std::iter::once('…')
136 .chain(path.chars().skip(count - (budget - 1)))
137 .collect()
138 } else {
139 std::iter::once('…')
141 .chain(component.chars().take(budget - 2))
142 .chain(['…'])
143 .collect()
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 fn resolved(operation: PrivilegedOperation<'_>) -> String {
152 resolved_prompt_text(operation, 4121, Path::new("/bin/node"))
153 }
154
155 #[test]
156 fn operation_and_target_precede_the_resolved_caller() {
157 let cases = [
158 (
159 PrivilegedOperation::Restart { module_id: "aft" },
160 "Restart module aft",
161 ),
162 (
163 PrivilegedOperation::Swap { module_id: "aft" },
164 "Swap module aft",
165 ),
166 (
167 PrivilegedOperation::Reload { module_id: "aft" },
168 "Reload module aft",
169 ),
170 (
171 PrivilegedOperation::SetEnabled {
172 module_id: "aft",
173 enabled: true,
174 },
175 "Start module aft",
176 ),
177 (
178 PrivilegedOperation::SetEnabled {
179 module_id: "aft",
180 enabled: false,
181 },
182 "Stop module aft",
183 ),
184 (
185 PrivilegedOperation::ReleaseReserved { module_id: "aft" },
186 "Release reserved module id aft",
187 ),
188 ];
189 for (operation, description) in cases {
190 assert_eq!(
191 resolved(operation),
192 format!("{description} — requested by pid 4121 (/bin/node)")
193 );
194 }
195 }
196
197 #[test]
198 fn rescan_covers_the_config_read_after_approval_without_a_module_count() {
199 assert_eq!(
200 resolved(PrivilegedOperation::Rescan),
201 "Apply the daemon config file as it reads when approved (rescan) — requested by pid 4121 (/bin/node)"
202 );
203 }
204
205 #[test]
206 fn failed_lookup_names_an_unidentified_local_process() {
207 assert_eq!(
208 prompt_text(
209 PrivilegedOperation::Restart { module_id: "aft" },
210 &CallerIdentity::default()
211 ),
212 "Restart module aft — requested by an unidentified local process"
213 );
214 }
215
216 #[test]
224 #[ignore = "re-exec socket owner fixture"]
225 fn prompt_caller_child_holds_socket() {
226 use std::io::{Read, Write};
227 let address = std::env::var("SUBC_TEST_PROMPT_CALLER_ADDRESS").unwrap();
228 let mut socket = std::net::TcpStream::connect(address).unwrap();
229 socket.write_all(b"R").unwrap();
230 let mut byte = [0];
231 assert_eq!(socket.read(&mut byte).unwrap(), 0);
232 }
233
234 struct KilledOnDrop(std::process::Child);
235
236 impl Drop for KilledOnDrop {
237 fn drop(&mut self) {
238 let _ = self.0.kill();
239 let _ = self.0.wait();
240 }
241 }
242
243 #[cfg(any(target_os = "macos", target_os = "linux", windows))]
244 #[tokio::test]
245 async fn resolved_connection_identity_flows_into_the_public_prompt_builder() {
246 use tokio::io::AsyncReadExt;
247 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
248 let caller = KilledOnDrop(
249 std::process::Command::new(std::env::current_exe().unwrap())
250 .args([
251 "--exact",
252 "privileged_prompt::tests::prompt_caller_child_holds_socket",
253 "--ignored",
254 ])
255 .env(
256 "SUBC_TEST_PROMPT_CALLER_ADDRESS",
257 listener.local_addr().unwrap().to_string(),
258 )
259 .stdout(std::process::Stdio::null())
260 .spawn()
261 .unwrap(),
262 );
263 let (mut accepted, _) =
264 tokio::time::timeout(std::time::Duration::from_secs(10), listener.accept())
265 .await
266 .expect("socket owner child connects")
267 .unwrap();
268 let mut ready = [0];
269 tokio::time::timeout(
270 std::time::Duration::from_secs(10),
271 accepted.read_exact(&mut ready),
272 )
273 .await
274 .expect("socket owner child signals readiness")
275 .unwrap();
276 assert_eq!(&ready, b"R");
277 let accepted = accepted.into_std().unwrap();
278
279 #[cfg(unix)]
283 let _mid_spawn_copy = KilledOnDrop(
284 std::process::Command::new("/bin/sleep")
285 .arg("30")
286 .stdin(std::process::Stdio::from(std::os::fd::OwnedFd::from(
287 accepted.try_clone().unwrap(),
288 )))
289 .spawn()
290 .unwrap(),
291 );
292
293 let accepted = tokio::net::TcpStream::from_std(accepted).unwrap();
294 let caller_identity = CallerIdentity::lookup(&accepted);
295 let summary = prompt_text(
296 PrivilegedOperation::Restart { module_id: "aft" },
297 &caller_identity,
298 );
299 assert!(
300 summary.starts_with(&format!(
301 "Restart module aft — requested by pid {} (",
302 caller.0.id()
303 )),
304 "{summary}"
305 );
306 let executable = std::env::current_exe().unwrap();
307 let filename = executable.file_name().unwrap().to_string_lossy();
308 assert!(summary.ends_with(&format!("{filename})")), "{summary}");
309 drop(accepted);
310 }
311
312 #[test]
313 fn target_limits_count_scalars_and_mark_only_a_cut_target() {
314 for count in [63, 64, 65, 300] {
315 let target = "界".repeat(count);
316 let expected = if count <= 64 {
317 target.clone()
318 } else {
319 format!("{}…", "界".repeat(63))
320 };
321 assert_eq!(
322 resolved(PrivilegedOperation::Restart { module_id: &target }),
323 format!("Restart module {expected} — requested by pid 4121 (/bin/node)")
324 );
325 }
326 }
327
328 #[test]
329 fn controls_zero_width_and_bidi_are_replaced_in_target_and_path() {
330 let bad: String = (0..=0x9f)
331 .filter_map(char::from_u32)
332 .filter(|c| c.is_control())
333 .chain(['\u{00ad}', '\u{034f}', '\u{061c}', '\u{180e}', '\u{feff}'])
334 .chain(('\u{200b}'..='\u{200f}').chain('\u{2028}'..='\u{202e}'))
335 .chain('\u{2060}'..='\u{206f}')
336 .collect();
337 for c in bad.chars() {
338 let target = format!("a{c}ft");
339 let path = format!("/bin/n{c}de");
340 assert_eq!(
341 resolved_prompt_text(
342 PrivilegedOperation::Restart { module_id: &target },
343 4121,
344 Path::new(&path)
345 ),
346 "Restart module a?ft — requested by pid 4121 (/bin/n?de)"
347 );
348 }
349 }
350
351 #[test]
352 fn path_shortening_keeps_the_final_component_for_unix_and_windows_paths() {
353 assert_eq!(shorten_path("/bin/node", 9), "/bin/node");
354 assert_eq!(shorten_path("/long/directory/bin/node", 10), "…/bin/node");
355 assert_eq!(
356 shorten_path(r"C:\long\directory\bin\node.exe", 14),
357 r"…\bin\node.exe"
358 );
359 assert_eq!(
360 shorten_path("/long/path/界界界界界界界界界界", 10),
361 "…界界界界界界界界…"
362 );
363 assert_eq!(shorten_path("/path/abcdefghij", 10), "…abcdefgh…");
364 }
365
366 fn oversized_facts() -> (String, String) {
367 let target = format!("{}\u{202e}{}", "界".repeat(31), "界".repeat(268));
368 let path = format!("/{}\u{200b}/bin/node", "路".repeat(489));
369 assert_eq!(target.chars().count(), 300);
370 assert_eq!(path.chars().count(), 500);
371 (target, path)
372 }
373
374 #[test]
375 fn oversized_unicode_facts_fit_without_losing_operation_or_pid() {
376 let (target, path) = oversized_facts();
377 let summary = resolved_prompt_text(
378 PrivilegedOperation::Restart { module_id: &target },
379 4121,
380 Path::new(&path),
381 );
382 assert_eq!(summary.chars().count(), 200);
383 assert!(summary.starts_with(&format!(
384 "Restart module {}?{}… — requested by pid 4121 (…",
385 "界".repeat(31),
386 "界".repeat(31)
387 )));
388 assert!(summary.ends_with("/bin/node)"));
389 assert!(!summary.chars().any(forbidden));
390
391 let long_filename = format!("/{}", "路".repeat(499));
392 for operation in [
393 PrivilegedOperation::ReleaseReserved { module_id: &target },
394 PrivilegedOperation::Rescan,
395 ] {
396 let summary = resolved_prompt_text(operation, u32::MAX, Path::new(&long_filename));
397 assert_eq!(summary.chars().count(), 200);
398 assert!(summary.contains(" — requested by pid 4294967295 (…"));
399 assert!(summary.ends_with("…)"));
400 }
401 }
402
403 #[tokio::test]
404 async fn oversized_unicode_summary_passes_operator_confirm_admission_rule() {
405 use crate::{
406 forwarding::{ChannelFlow, ModuleEndpointId, RouteBinding},
407 operator_confirm::{
408 OperatorConfirms, OperatorLimits, OperatorProvider, OperatorWithdraw,
409 ProviderResult,
410 },
411 router::{FrameSink, RouteCtx},
412 ConnectionId, Frame,
413 };
414 use std::sync::Arc;
415 use subc_protocol::{
416 error_codes, session::OperatorConfirmRequest, Flags, FrameType, Principal, Priority,
417 PROTOCOL_VERSION,
418 };
419
420 struct UnavailableProvider;
421 impl OperatorProvider for UnavailableProvider {
422 fn prompt(
423 &self,
424 _: &str,
425 _: Box<dyn FnOnce(Arc<dyn OperatorWithdraw>) + Send>,
426 ) -> ProviderResult {
427 ProviderResult::Unavailable
428 }
429 }
430
431 let confirms = Arc::new(OperatorConfirms::default());
432 confirms.configure(Arc::new(UnavailableProvider), OperatorLimits::default());
433 let (tx, mut rx) = tokio::sync::mpsc::channel(4);
434 let ctx = RouteCtx {
435 connection_id: ConnectionId::new(1),
436 egress: FrameSink::new(tx),
437 };
438 let binding = RouteBinding {
439 client_connection_id: ConnectionId::new(2),
440 client_sink: ctx.egress.clone(),
441 client_negotiated_ver: PROTOCOL_VERSION,
442 client_channel: 1,
443 client_epoch: 1,
444 module_id: "fixture".into(),
445 module_endpoint: ModuleEndpointId {
446 connection_id: ctx.connection_id,
447 generation: 1,
448 },
449 module_sink: ctx.egress.clone(),
450 module_negotiated_ver: PROTOCOL_VERSION,
451 module_channel: 1,
452 module_epoch: 1,
453 principal: Principal::Direct,
454 harness: "fixture".into(),
455 build_class: None,
456 operator_app: None,
457 project_root: None,
458 bound_at: tokio::time::Instant::now(),
459 flow: Arc::new(ChannelFlow::new(64 * 1024)),
460 scope: None,
461 caller_authority: None,
462 target_authority: None,
463 accepts_close_reasons: None,
464 };
465 let frame = Frame::build(
466 FrameType::Request,
467 Flags::new(false, Priority::Passive, false),
468 0,
469 0,
470 1,
471 b"{}".to_vec(),
472 )
473 .unwrap();
474
475 for invalid in ["界".repeat(201), "hidden\u{202e}text".into()] {
479 let refusal = confirms.admit(
480 &ctx,
481 frame.clone(),
482 "fixture".into(),
483 true,
484 OperatorConfirmRequest::new(invalid, 1, 1),
485 Some(&binding),
486 );
487 assert_eq!(refusal.len(), 1);
488 let body: serde_json::Value = serde_json::from_slice(&refusal[0].body).unwrap();
489 assert_eq!(body["code"], error_codes::OPERATOR_SUMMARY_INVALID);
490 }
491
492 let (target, path) = oversized_facts();
493 let summary = resolved_prompt_text(
494 PrivilegedOperation::Restart { module_id: &target },
495 4121,
496 Path::new(&path),
497 );
498 assert!(confirms
499 .admit(
500 &ctx,
501 frame,
502 "fixture".into(),
503 true,
504 OperatorConfirmRequest::new(summary, 1, 1),
505 Some(&binding),
506 )
507 .is_empty());
508 let outcome = tokio::time::timeout(std::time::Duration::from_secs(4), rx.recv())
509 .await
510 .unwrap()
511 .unwrap();
512 let body: serde_json::Value = serde_json::from_slice(&outcome.frame.body).unwrap();
513 assert_eq!(body["code"], error_codes::OPERATOR_PRESENCE_UNAVAILABLE);
514 assert_eq!(body["detail"]["reason"], "provider_error");
515 }
516}