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