1use std::error::Error;
2use std::fmt;
3use std::io::{self, Read, Write};
4use std::path::Path;
5use std::process::ExitStatus;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::thread::{self, JoinHandle};
9use std::time::Duration;
10
11use anyhow::{Context, Result, bail, ensure};
12
13use crate::{env, registry_token};
14
15pub const DEFAULT_TIMEOUT: Duration = Duration::from_mins(1);
17pub const DEFAULT_OUTPUT_LIMIT: usize = 8 * 1024 * 1024;
19
20pub fn filter(argv: &[String], stdin: &str, env: &[(&str, &str)]) -> Result<String> {
31 filter_limited(argv, stdin, env, DEFAULT_TIMEOUT, DEFAULT_OUTPUT_LIMIT)
32}
33
34pub fn run_limited(argv: &[String], env: &[(&str, &str)], timeout: Duration) -> Result<String> {
41 filter_limited(argv, "", env, timeout, DEFAULT_OUTPUT_LIMIT)
42}
43
44const STDERR_TAIL: usize = 64 * 1024;
46
47pub fn run_inherit(argv: &[String], timeout: Duration) -> Result<()> {
66 run_inherit_in(argv, None, timeout)
67}
68
69pub fn run_inherit_in(argv: &[String], dir: Option<&Path>, timeout: Duration) -> Result<()> {
76 inherit(argv, dir, &[], timeout)
77}
78
79pub fn run_inherit_env(argv: &[String], env: &[(&str, &str)], timeout: Duration) -> Result<()> {
87 inherit(argv, None, env, timeout)
88}
89
90const GITHUB_CREDENTIALS: [&str; 2] = ["GITHUB_TOKEN", "GH_TOKEN"];
95
96fn command(argv: &[String], env: &[(&str, &str)]) -> duct::Expression {
106 let expression = env.iter().fold(
107 duct::cmd(&argv[0], &argv[1..]),
108 |expression, (key, value)| expression.env(key, value),
109 );
110 registry_token::SOURCES
111 .iter()
112 .chain(&[registry_token::OWNER, env::PACKSLIP_KEY])
113 .chain(&GITHUB_CREDENTIALS)
114 .fold(expression, |expression, variable| {
115 expression.env_remove(variable)
116 })
117}
118
119fn inherit(
120 argv: &[String],
121 dir: Option<&Path>,
122 env: &[(&str, &str)],
123 timeout: Duration,
124) -> Result<()> {
125 ensure!(!argv.is_empty(), "driver argv is empty");
126 let (stderr_r, stderr_w) = os_pipe::pipe().context("command stderr pipe")?;
127 let mut expression = command(argv, env);
128 if let Some(dir) = dir {
129 expression = expression.dir(dir);
130 }
131 let handle = expression
133 .stdout_to_stderr()
134 .stderr_file(stderr_w)
135 .unchecked()
136 .start()
137 .context("spawn command")?;
138 let tail = thread::spawn(move || stream_tail(stderr_r));
139 let waited = match handle.wait_timeout(timeout) {
140 Ok(output) => output.is_some(),
141 Err(error) => {
142 let _ = handle.kill();
143 let _ = handle.wait();
144 let _ = tail.join();
145 return Err(error).context("command");
146 }
147 };
148 if !waited {
149 let _ = handle.kill();
150 let _ = handle.wait();
151 let _ = tail.join();
152 bail!("command timed out after {timeout:?}");
153 }
154 #[expect(
155 clippy::map_err_ignore,
156 reason = "a thread join error is a panic payload (`Box<dyn Any>`), not an `Error`, so it cannot be a source"
157 )]
158 let stderr = tail
159 .join()
160 .map_err(|_| anyhow::anyhow!("stderr reader panicked"))?;
161 let status = handle
162 .try_wait()
163 .context("command")?
164 .context("command exited without a status")?
165 .status;
166 if !status.success() {
167 bail!(
168 "command failed: {}: {}",
169 argv.join(" "),
170 String::from_utf8_lossy(&stderr).trim()
171 );
172 }
173 Ok(())
174}
175
176fn stream_tail(mut reader: impl Read) -> Vec<u8> {
179 let mut tail = Vec::new();
180 let mut chunk = [0_u8; 8192];
181 let mut stderr = io::stderr();
182 loop {
183 match reader.read(&mut chunk) {
184 Ok(0) | Err(_) => return tail,
185 Ok(read) => {
186 let _ = stderr.write_all(&chunk[..read]);
187 tail.extend_from_slice(&chunk[..read]);
188 if tail.len() > STDERR_TAIL {
189 tail.drain(..tail.len() - STDERR_TAIL);
190 }
191 }
192 }
193 }
194}
195
196#[must_use]
198pub fn argv(parts: &[&str]) -> Vec<String> {
199 parts.iter().map(|part| (*part).to_owned()).collect()
200}
201
202pub fn filter_limited(
219 argv: &[String],
220 stdin: &str,
221 env: &[(&str, &str)],
222 timeout: Duration,
223 output_limit: usize,
224) -> Result<String> {
225 capture(argv, stdin, env, None, timeout, output_limit)
226}
227
228pub fn run_in(
246 argv: &[String],
247 dir: &Path,
248 env: &[(&str, &str)],
249 timeout: Duration,
250) -> Result<String> {
251 capture(argv, "", env, Some(dir), timeout, DEFAULT_OUTPUT_LIMIT)
252}
253
254#[derive(Debug)]
256pub struct ExitFailure {
257 pub command: String,
259 pub status: ExitStatus,
261 pub stderr: String,
263}
264
265impl fmt::Display for ExitFailure {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 let Self {
268 command,
269 status,
270 stderr,
271 } = self;
272 if stderr.is_empty() {
273 write!(f, "driver command failed: {command}: {status}")
274 } else {
275 write!(f, "driver command failed: {command}: {status}: {stderr}")
276 }
277 }
278}
279
280impl Error for ExitFailure {}
281
282#[derive(Debug)]
284pub struct TimedOut {
285 pub timeout: Duration,
287}
288
289impl fmt::Display for TimedOut {
290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291 write!(f, "driver command timed out after {:?}", self.timeout)
292 }
293}
294
295impl Error for TimedOut {}
296
297fn capture(
298 argv: &[String],
299 stdin: &str,
300 env: &[(&str, &str)],
301 dir: Option<&Path>,
302 timeout: Duration,
303 output_limit: usize,
304) -> Result<String> {
305 ensure!(!argv.is_empty(), "driver argv is empty");
306 let mut expr = command(argv, env);
307 if let Some(dir) = dir {
308 expr = expr.dir(dir);
309 }
310 let (stdout_r, stdout_w) = os_pipe::pipe().context("driver stdout pipe")?;
311 let (stderr_r, stderr_w) = os_pipe::pipe().context("driver stderr pipe")?;
312 let handle = Arc::new(
313 expr.stdin_bytes(stdin.as_bytes().to_vec())
314 .stdout_file(stdout_w)
315 .stderr_file(stderr_w)
316 .unchecked()
317 .start()
318 .context("spawn driver command")?,
319 );
320 let mut guard = ChildGuard {
321 handle: Arc::clone(&handle),
322 reaped: false,
323 };
324 let exceeded = Arc::new(AtomicBool::new(false));
325 let stdout_h = spawn_capped(
326 stdout_r,
327 output_limit,
328 Arc::clone(&handle),
329 Arc::clone(&exceeded),
330 );
331 let stderr_h = spawn_capped(
332 stderr_r,
333 output_limit,
334 Arc::clone(&handle),
335 Arc::clone(&exceeded),
336 );
337
338 let waited = match handle.wait_timeout(timeout) {
339 Ok(output) => output.is_some(),
340 Err(error) => {
341 let _ = handle.kill();
342 let _ = handle.wait();
343 let _ = take_capped(stdout_h);
344 let _ = take_capped(stderr_h);
345 guard.reaped = true;
346 return Err(error).context("driver command");
347 }
348 };
349 if !waited {
350 let _ = handle.kill();
351 let _ = handle.wait();
352 let _ = take_capped(stdout_h);
353 let _ = take_capped(stderr_h);
354 guard.reaped = true;
355 return Err(TimedOut { timeout }.into());
356 }
357
358 let stdout = take_capped(stdout_h)?;
359 let stderr = take_capped(stderr_h)?;
360 guard.reaped = true;
361
362 if exceeded.load(Ordering::SeqCst) {
363 bail!("driver command output exceeded {output_limit} bytes");
364 }
365 let status = handle
366 .try_wait()
367 .context("driver command")?
368 .context("driver exited without a status")?
369 .status;
370 if !status.success() {
371 return Err(ExitFailure {
372 command: argv.join(" "),
373 status,
374 stderr: String::from_utf8_lossy(&stderr).trim().to_owned(),
375 }
376 .into());
377 }
378 String::from_utf8(stdout).context("driver stdout is not UTF-8")
379}
380
381struct ChildGuard {
382 handle: Arc<duct::Handle>,
383 reaped: bool,
384}
385
386impl Drop for ChildGuard {
387 fn drop(&mut self) {
388 if !self.reaped {
389 let _ = self.handle.kill();
390 let _ = self.handle.try_wait();
391 }
392 }
393}
394
395enum CapRead {
396 Bytes(Vec<u8>),
397 Exceeded,
398}
399
400fn spawn_capped(
401 reader: os_pipe::PipeReader,
402 limit: usize,
403 handle: Arc<duct::Handle>,
404 exceeded: Arc<AtomicBool>,
405) -> JoinHandle<io::Result<CapRead>> {
406 thread::spawn(move || {
407 let result = read_capped(reader, limit);
408 if matches!(result, Ok(CapRead::Exceeded)) {
409 exceeded.store(true, Ordering::SeqCst);
410 let _ = handle.kill();
411 }
412 result
413 })
414}
415
416fn read_capped(mut reader: os_pipe::PipeReader, limit: usize) -> io::Result<CapRead> {
417 let mut buf = Vec::new();
418 let mut chunk = [0_u8; 8192];
419 loop {
420 let n = reader.read(&mut chunk)?;
421 if n == 0 {
422 return Ok(CapRead::Bytes(buf));
423 }
424 if buf.len().saturating_add(n) > limit {
425 return Ok(CapRead::Exceeded);
426 }
427 buf.extend_from_slice(&chunk[..n]);
428 }
429}
430
431fn take_capped(handle: JoinHandle<io::Result<CapRead>>) -> Result<Vec<u8>> {
432 match handle.join() {
433 Ok(Ok(CapRead::Bytes(bytes))) => Ok(bytes),
434 Ok(Ok(CapRead::Exceeded)) => bail!("driver command output exceeded the cap"),
435 Ok(Err(error)) => Err(error).context("read driver output"),
436 Err(_) => bail!("driver output reader panicked"),
437 }
438}
439
440#[cfg(test)]
441mod tests {
442 use std::time::{Duration, Instant};
443
444 use super::{argv, command, filter, filter_limited, run_inherit};
445
446 #[test]
447 fn a_failed_command_reports_its_stderr() {
448 let error = run_inherit(
449 &[
450 "sh".into(),
451 "-c".into(),
452 "echo 'crate x@0.0.1 already exists on crates.io index' >&2; exit 1".into(),
453 ],
454 Duration::from_secs(5),
455 )
456 .expect_err("failure");
457 let message = format!("{error:#}");
458 assert!(
459 message.contains("already exists on crates.io index"),
460 "{message}"
461 );
462 }
463
464 #[test]
465 fn a_command_writes_its_stdout_to_stderr() {
466 let error = run_inherit(
467 &[
468 "sh".into(),
469 "-c".into(),
470 "echo 'lint failed: function_missing'; exit 1".into(),
471 ],
472 Duration::from_secs(5),
473 )
474 .expect_err("failure");
475 let message = format!("{error:#}");
476 assert!(message.contains("function_missing"), "{message}");
477 }
478
479 #[test]
480 fn filter_returns_stdout() {
481 let out = filter(&["tr".into(), "-d".into(), "\n".into()], "1.2.3\n", &[]).expect("filter");
482 assert_eq!(out, "1.2.3");
483 }
484
485 #[test]
486 fn filter_times_out_and_kills() {
487 let start = Instant::now();
488 let error = filter_limited(
489 &["sleep".into(), "30".into()],
490 "",
491 &[],
492 Duration::from_millis(200),
493 1024,
494 )
495 .expect_err("timeout");
496 let message = format!("{error:#}");
497 assert!(message.contains("timed out"), "{message}");
498 assert!(
499 start.elapsed() < Duration::from_secs(5),
500 "kill did not return promptly: {:?}",
501 start.elapsed()
502 );
503 }
504
505 #[test]
506 fn filter_rejects_oversized_stdout_without_buffering_it() {
507 let start = Instant::now();
508 let error = filter_limited(
509 &[
510 "sh".into(),
511 "-c".into(),
512 format!("while :; do echo {}; done", "x".repeat(64)),
513 ],
514 "",
515 &[],
516 Duration::from_secs(10),
517 4096,
518 )
519 .expect_err("limit");
520 let message = format!("{error:#}");
521 assert!(message.contains("exceeded"), "{message}");
522 assert!(
523 start.elapsed() < Duration::from_secs(3),
524 "cap waited for the firehose instead of killing: {:?}",
525 start.elapsed()
526 );
527 }
528
529 #[test]
530 fn filter_reports_nonzero_status() {
531 let error = filter(&["false".into()], "", &[]).expect_err("fail");
532 assert_eq!(
533 format!("{error:#}"),
534 "driver command failed: false: exit status: 1"
535 );
536 }
537
538 #[test]
539 fn filter_reports_the_stderr_of_a_failed_command() {
540 let error = filter(
541 &["sh".into(), "-c".into(), "echo boom >&2; exit 3".into()],
542 "",
543 &[],
544 )
545 .expect_err("fail");
546 assert_eq!(
547 format!("{error:#}"),
548 "driver command failed: sh -c echo boom >&2; exit 3: exit status: 3: boom"
549 );
550 }
551
552 fn seen_by_child(inherited: &[(&str, &str)], given: &[(&str, &str)]) -> String {
556 let script = r#"printf '[%s][%s][%s][%s][%s]' "$GITHUB_TOKEN" "$GH_TOKEN" "$VERCTL_REGISTRY_TOKEN" "$VERCTL_OWNER_TOKEN" "$VERCTL_PACKSLIP_KEY""#;
557 let mut expression = command(&argv(&["sh", "-c", script]), given);
558 for (key, value) in inherited {
559 expression = expression.env(key, value);
560 }
561 let output = expression.stdout_capture().run().expect("run");
562 String::from_utf8(output.stdout).expect("UTF-8")
563 }
564
565 #[test]
566 fn no_child_inherits_a_github_credential_a_registry_token_or_the_packslip_key() {
567 let inherited = [
568 ("GITHUB_TOKEN", "github"),
569 ("GH_TOKEN", "gh"),
570 ("VERCTL_REGISTRY_TOKEN", "registry"),
571 ("VERCTL_OWNER_TOKEN", "owner"),
572 ("VERCTL_PACKSLIP_KEY", "key"),
573 ];
574 assert_eq!(seen_by_child(&inherited, &[]), "[][][][][]");
575 }
576
577 #[test]
581 fn a_credential_a_command_is_given_stays_set() {
582 let inherited = [("GITHUB_TOKEN", "github"), ("GH_TOKEN", "gh")];
583 assert_eq!(
584 seen_by_child(&inherited, &[("GITHUB_TOKEN", "given")]),
585 "[given][][][][]"
586 );
587 }
588}