1use crate::nodes::Target;
22use sha2::{Digest, Sha256};
23use std::io::Read;
24use std::path::{Path, PathBuf};
25use std::process::{Command, Stdio};
26use std::time::{Duration, Instant};
27
28pub const KEEP_VERSIONS: usize = 3;
29pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(30);
31
32pub fn sha256_hex(bytes: &[u8]) -> String {
33 hex::encode(Sha256::digest(bytes))
34}
35
36pub fn hash_file(path: &Path) -> Result<Option<String>, String> {
38 match std::fs::read(path) {
39 Ok(b) => Ok(Some(sha256_hex(&b))),
40 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
41 Err(e) => Err(format!("{}: {e}", path.display())),
42 }
43}
44
45fn run(cmd: &str, content: &str, timeout: Duration) -> Result<(), String> {
52 #[cfg(windows)]
53 let mut c = {
54 let mut c = Command::new("cmd");
55 c.args(["/C", cmd]);
56 c
57 };
58 #[cfg(not(windows))]
59 let mut c = {
60 let mut c = Command::new("sh");
61 c.args(["-c", cmd]);
62 c
63 };
64 let mut child = c
65 .stdin(Stdio::null())
66 .stdout(Stdio::piped())
67 .stderr(Stdio::piped())
68 .spawn()
69 .map_err(|e| format!("could not start '{cmd}': {e}"))?;
70 let drain = |pipe: Option<Box<dyn Read + Send>>| {
73 let (tx, rx) = std::sync::mpsc::channel::<String>();
74 if let Some(mut pipe) = pipe {
75 std::thread::spawn(move || {
76 let mut head = Vec::new();
77 let mut chunk = [0u8; 8192];
78 loop {
79 match pipe.read(&mut chunk) {
80 Ok(0) | Err(_) => break,
81 Ok(n) => {
82 if head.len() < 8192 {
83 let take = n.min(8192 - head.len());
84 head.extend_from_slice(&chunk[..take]);
85 }
86 }
87 }
88 }
89 let _ = tx.send(String::from_utf8_lossy(&head).into_owned());
90 });
91 }
92 rx
93 };
94 let out_rx = drain(
95 child
96 .stdout
97 .take()
98 .map(|p| Box::new(p) as Box<dyn Read + Send>),
99 );
100 let err_rx = drain(
101 child
102 .stderr
103 .take()
104 .map(|p| Box::new(p) as Box<dyn Read + Send>),
105 );
106 let start = Instant::now();
107 let status = loop {
108 match child.try_wait().map_err(|e| e.to_string())? {
109 Some(s) => break s,
110 None if start.elapsed() > timeout => {
111 let _ = child.kill();
112 let _ = child.wait();
113 return Err(format!(
114 "'{cmd}' did not finish in {}s",
115 timeout.as_secs().max(1)
116 ));
117 }
118 None => std::thread::sleep(Duration::from_millis(25)),
119 }
120 };
121 if status.success() {
122 return Ok(());
123 }
124 let mut text = err_rx
126 .recv_timeout(Duration::from_millis(500))
127 .unwrap_or_default();
128 if text.trim().is_empty() {
129 text = out_rx
130 .recv_timeout(Duration::from_millis(500))
131 .unwrap_or_default();
132 }
133 Err(format!(
134 "'{cmd}' exited {}: {}",
135 status.code().map_or("by signal".into(), |c| c.to_string()),
136 scrub(&text, content)
137 ))
138}
139
140pub fn scrub(output: &str, content: &str) -> String {
145 let file_lines: std::collections::HashSet<&str> = content
146 .lines()
147 .map(str::trim)
148 .filter(|l| l.len() >= 8)
149 .collect();
150 let lines: Vec<&str> = output
151 .lines()
152 .map(str::trim)
153 .filter(|l| !l.is_empty())
154 .collect();
155 let tail = &lines[lines.len().saturating_sub(3)..];
156 tail.iter()
157 .map(|l| {
158 if file_lines.contains(l) || file_lines.iter().any(|f| l.contains(f)) {
159 "[a line of the file elided]".to_string()
160 } else {
161 l.chars().take(200).collect()
162 }
163 })
164 .collect::<Vec<_>>()
165 .join(" | ")
166}
167
168fn versions_dir(state_dir: &Path, id: &str) -> PathBuf {
169 state_dir.join("versions").join(id)
170}
171
172static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
173
174fn write_atomic(
175 path: &Path,
176 bytes: &[u8],
177 mode_from: Option<&std::fs::Metadata>,
178 perm: Perm,
179) -> Result<(), String> {
180 use std::io::Write;
181 let dir = path.parent().ok_or("target has no parent directory")?;
182 let name = path.file_name().ok_or("target has no file name")?;
183 let tmp = dir.join(format!(
186 ".{}.unv-node.{}.{}.tmp",
187 name.to_string_lossy(),
188 std::process::id(),
189 TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
190 ));
191 let mut opts = std::fs::OpenOptions::new();
192 opts.write(true).create_new(true);
193 #[cfg(unix)]
194 {
195 use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
196 opts.mode(
198 perm.mode
199 .unwrap_or_else(|| mode_from.map_or(0o600, |m| m.mode() & 0o7777)),
200 );
201 }
202 #[cfg(not(unix))]
203 let _ = (mode_from, perm.mode, perm.owner);
204 let mut f = opts
205 .open(&tmp)
206 .map_err(|e| format!("cannot write beside {}: {e}", path.display()))?;
207 f.write_all(bytes).map_err(|e| e.to_string())?;
208 f.sync_all().map_err(|e| e.to_string())?;
209 #[cfg(unix)]
210 if let Some((uid, gid)) = perm.owner {
211 if let Err(e) = std::os::unix::fs::fchown(&f, Some(uid), Some(gid)) {
213 drop(f);
214 let _ = std::fs::remove_file(&tmp);
215 return Err(format!(
216 "cannot give {} to the owner named in the target: {e}",
217 path.display()
218 ));
219 }
220 }
221 drop(f);
222 crate::platform::replace_file(&tmp, path).map_err(|e| {
223 let _ = std::fs::remove_file(&tmp);
224 format!("cannot replace {}: {e}", path.display())
225 })?;
226 #[cfg(unix)]
227 if let Ok(d) = std::fs::File::open(dir) {
228 let _ = d.sync_all();
229 }
230 Ok(())
231}
232
233fn restore(
237 path: &Path,
238 wrote: &[u8],
239 previous: &Option<Vec<u8>>,
240 meta: Option<&std::fs::Metadata>,
241 perm: Perm,
242) -> Result<(), String> {
243 if std::fs::read(path).ok().as_deref() != Some(wrote) {
244 return Err(
245 "the file was changed by someone else meanwhile, so it was left as it is".into(),
246 );
247 }
248 match previous {
249 Some(b) => write_atomic(path, b, meta, perm),
250 None => std::fs::remove_file(path).map_err(|e| e.to_string()),
251 }
252}
253
254fn keep_version(state_dir: &Path, id: &str, bytes: &[u8]) -> Result<(), String> {
255 let dir = versions_dir(state_dir, id);
256 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
257 let secs = std::time::SystemTime::now()
258 .duration_since(std::time::UNIX_EPOCH)
259 .map_or(0, |d| d.as_secs());
260 let name = format!("{secs:012}-{}", &sha256_hex(bytes)[..8]);
261 let p = dir.join(name);
262 write_atomic(&p, bytes, None, Perm::default())?;
265 let mut all: Vec<_> = std::fs::read_dir(&dir)
266 .map_err(|e| e.to_string())?
267 .flatten()
268 .map(|e| e.path())
269 .filter(|p| {
270 !p.file_name()
271 .is_some_and(|n| n.to_string_lossy().starts_with('.'))
272 })
273 .collect();
274 all.sort();
275 while all.len() > KEEP_VERSIONS {
276 let _ = std::fs::remove_file(all.remove(0));
277 }
278 Ok(())
279}
280
281pub fn kept_versions(state_dir: &Path, id: &str) -> Vec<PathBuf> {
283 let mut v: Vec<PathBuf> = std::fs::read_dir(versions_dir(state_dir, id))
284 .map(|d| d.flatten().map(|e| e.path()).collect())
285 .unwrap_or_default();
286 v.sort();
287 v
288}
289
290#[derive(Debug, PartialEq)]
291pub enum Applied {
292 Unchanged,
294 Written,
295}
296
297pub fn reload_signal_path(state_dir: &Path, id: &str) -> PathBuf {
302 state_dir.join("reload").join(id)
303}
304
305pub fn reload_signal_unit_path(state_dir: &str, id: &str) -> String {
308 format!("{}/reload/{id}", state_dir.trim_end_matches('/'))
309}
310
311fn signal_reload(state_dir: &Path, id: &str, sha: &str) -> Result<(), String> {
312 let p = reload_signal_path(state_dir, id);
313 if let Some(dir) = p.parent() {
314 std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
315 }
316 write_atomic(&p, format!("{sha}\n").as_bytes(), None, Perm::default())
318}
319
320pub type Phases = Vec<&'static str>;
323
324fn probe_http(url: &str, timeout: Duration) -> Result<(), String> {
327 use std::io::Write;
328 let rest = url.strip_prefix("http://").ok_or("not an http:// URL")?;
329 let (hostport, path) = rest
330 .split_once('/')
331 .map_or((rest, "/".to_string()), |(h, p)| (h, format!("/{p}")));
332 let addr = if hostport.contains(':') {
333 hostport.to_string()
334 } else {
335 format!("{hostport}:80")
336 };
337 let sock = std::net::ToSocketAddrs::to_socket_addrs(&addr)
338 .map_err(|e| format!("{addr}: {e}"))?
339 .next()
340 .ok_or_else(|| format!("{addr}: no address"))?;
341 let mut stream = std::net::TcpStream::connect_timeout(&sock, timeout)
342 .map_err(|e| format!("could not connect to {addr}: {e}"))?;
343 stream.set_read_timeout(Some(timeout)).ok();
344 stream.set_write_timeout(Some(timeout)).ok();
345 stream
346 .write_all(
347 format!("GET {path} HTTP/1.0\r\nHost: {hostport}\r\nConnection: close\r\n\r\n")
348 .as_bytes(),
349 )
350 .map_err(|e| e.to_string())?;
351 let mut head = [0u8; 64];
352 let n = stream
353 .read(&mut head)
354 .map_err(|e| format!("no answer from {addr}: {e}"))?;
355 let line = String::from_utf8_lossy(&head[..n]);
356 let code = line.split_whitespace().nth(1).unwrap_or("");
357 if code.starts_with('2') {
358 Ok(())
359 } else {
360 Err(format!(
361 "{url} answered {}",
362 if code.is_empty() {
363 "nothing readable"
364 } else {
365 code
366 }
367 ))
368 }
369}
370
371fn run_check(check: &str, text: &str) -> Result<(), String> {
372 if check.starts_with("http://") {
373 probe_http(check, COMMAND_TIMEOUT)
374 } else {
375 run(check, text, COMMAND_TIMEOUT)
376 }
377}
378
379pub fn apply(
381 target: &Target,
382 content: &[u8],
383 expected_sha: &str,
384 state_dir: &Path,
385) -> Result<Applied, String> {
386 apply_with_phases(target, content, expected_sha, state_dir).0
387}
388
389pub fn apply_with_phases(
399 target: &Target,
400 content: &[u8],
401 expected_sha: &str,
402 state_dir: &Path,
403) -> (Result<Applied, String>, Phases) {
404 let mut phases: Phases = Vec::new();
405 let result = apply_inner(target, content, expected_sha, state_dir, &mut phases);
406 (result, phases)
407}
408
409fn apply_inner(
410 target: &Target,
411 content: &[u8],
412 expected_sha: &str,
413 state_dir: &Path,
414 phases: &mut Phases,
415) -> Result<Applied, String> {
416 if target.mode != "push" || !target.apply {
417 return Err(format!(
418 "target '{}' is not set to apply; the node's config decides that, not the hub",
419 target.id
420 ));
421 }
422 if sha256_hex(content) != expected_sha {
423 return Err(
424 "content does not match the hash the hub announced; nothing was written".into(),
425 );
426 }
427 let text = String::from_utf8_lossy(content).into_owned();
428 let path = &target.path;
429 let perm = Perm::of(target);
430 let (validate, reload) = (effective_validate(target), effective_reload(target));
431 let meta = std::fs::metadata(path).ok();
432 let previous = match std::fs::read(path) {
433 Ok(b) => Some(b),
434 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
435 Err(e) => return Err(format!("{}: {e}", path.display())),
436 };
437 if previous.as_deref() == Some(content) {
438 return Ok(Applied::Unchanged);
439 }
440 if let Some(p) = &previous {
441 keep_version(state_dir, &target.id, p)?;
442 }
443
444 let path_validator = validate.as_deref().filter(|v| v.contains("{file}"));
446 if let Some(v) = path_validator {
447 let tmp = temp_beside(path)?;
448 write_atomic(&tmp, content, meta.as_ref(), perm)?;
449 let outcome = run(
450 &v.replace("{file}", &shell_quote(&tmp)),
451 &text,
452 COMMAND_TIMEOUT,
453 );
454 let _ = std::fs::remove_file(&tmp);
455 if let Err(e) = outcome {
456 return Err(format!("validate failed, the file was not replaced: {e}"));
457 }
458 phases.push("validated");
459 }
460 write_atomic(path, content, meta.as_ref(), perm)?;
461 phases.insert(0, "written");
462
463 if let Some(v) = validate.as_deref().filter(|v| !v.contains("{file}")) {
464 if let Err(e) = run(v, &text, COMMAND_TIMEOUT) {
465 return Err(
466 match restore(path, content, &previous, meta.as_ref(), perm) {
467 Ok(()) => format!("validate failed, previous file restored: {e}"),
468 Err(r) => {
469 format!("validate failed AND restoring the previous file failed ({r}): {e}")
470 }
471 },
472 );
473 }
474 phases.push("validated");
475 }
476 if let Some(r) = &reload {
477 if let Err(e) = run(r, &text, COMMAND_TIMEOUT) {
478 return Err(match restore(path, content, &previous, meta.as_ref(), perm) {
479 Ok(()) => format!(
480 "reload failed, previous file restored and the service was not reloaded again: {e}"
481 ),
482 Err(x) => format!("reload failed AND restoring the previous file failed ({x}): {e}"),
483 });
484 }
485 phases.push("reloaded");
486 }
487 if let Some(c) = &target.check {
488 if let Err(e) = run_check(c, &text) {
489 let restored = restore(path, content, &previous, meta.as_ref(), perm);
490 let reloaded = match (&restored, &reload) {
492 (Ok(()), Some(r)) => run(r, &text, COMMAND_TIMEOUT).err(),
493 _ => None,
494 };
495 return Err(match (restored, reloaded) {
496 (Ok(()), None) => format!("check failed, previous file restored and reloaded: {e}"),
497 (Ok(()), Some(x)) => format!(
498 "check failed, previous file restored but reloading it failed ({x}): {e}"
499 ),
500 (Err(x), _) => {
501 format!("check failed AND restoring the previous file failed ({x}): {e}")
502 }
503 });
504 }
505 phases.push("checked");
506 }
507 if let Err(e) = signal_reload(state_dir, &target.id, expected_sha) {
508 return Err(
509 match restore(path, content, &previous, meta.as_ref(), perm) {
510 Ok(()) => format!("could not signal the reload, previous file restored: {e}"),
511 Err(x) => format!("could not signal the reload AND restoring failed ({x}): {e}"),
512 },
513 );
514 }
515 if target.compose_project.is_some() {
517 let _ = std::fs::remove_dir_all(versions_dir(state_dir, &target.id));
518 }
519 Ok(Applied::Written)
520}
521
522fn temp_beside(path: &Path) -> Result<PathBuf, String> {
524 let dir = path.parent().ok_or("target has no parent directory")?;
525 let name = path.file_name().ok_or("target has no file name")?;
526 Ok(dir.join(format!(
527 ".{}.unv-check.{}.{}.tmp",
528 name.to_string_lossy(),
529 std::process::id(),
530 TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
531 )))
532}
533
534fn effective_validate(t: &Target) -> Option<String> {
537 match (&t.compose_project, &t.compose_file) {
538 (Some(p), Some(f)) => Some(format!(
539 "docker compose -p {p} -f {} config -q",
540 shell_quote(f)
541 )),
542 _ => t.validate.clone(),
543 }
544}
545
546fn effective_reload(t: &Target) -> Option<String> {
549 match (&t.compose_project, &t.compose_file) {
550 (Some(p), Some(f)) => Some(format!(
551 "docker compose -p {p} -f {} up -d --no-deps --force-recreate {}",
552 shell_quote(f),
553 t.services.join(" ")
554 )),
555 _ => t.reload.clone(),
556 }
557}
558
559#[derive(Clone, Copy, Default)]
561struct Perm {
562 mode: Option<u32>,
563 owner: Option<(u32, u32)>,
564}
565
566impl Perm {
567 fn of(t: &Target) -> Self {
568 Self {
569 mode: t.file_mode_bits(),
570 owner: t.owner_ids(),
571 }
572 }
573}
574
575fn shell_quote(path: &Path) -> String {
577 let text = path.to_string_lossy();
578 #[cfg(windows)]
579 {
580 format!("\"{text}\"")
581 }
582 #[cfg(not(windows))]
583 {
584 format!("'{}'", text.replace('\'', "'\\''"))
585 }
586}
587
588#[cfg(test)]
589mod tests {
590 use super::*;
591
592 fn scratch(tag: &str) -> PathBuf {
593 let n = {
596 use std::sync::atomic::{AtomicU64, Ordering};
597 static SEQ: AtomicU64 = AtomicU64::new(0);
598 format!(
599 "{}-{}",
600 std::process::id(),
601 SEQ.fetch_add(1, Ordering::SeqCst)
602 )
603 };
604 let d = std::env::temp_dir().join(format!("unv-apply-{tag}-{n}"));
605 std::fs::create_dir_all(&d).unwrap();
606 d
607 }
608
609 fn target(dir: &Path, validate: Option<&str>, reload: Option<&str>) -> Target {
610 Target {
611 id: "t".into(),
612 path: dir.join("app.conf"),
613 project: "p".into(),
614 exporter: "nginx".into(),
615 mode: "push".into(),
616 apply: true,
617 validate: validate.map(String::from),
618 reload: reload.map(String::from),
619 require_approval: false,
620 check: None,
621 accept_rule_approval: false,
622 file_mode: None,
623 owner: None,
624 compose_project: None,
625 compose_file: None,
626 services: Vec::new(),
627 }
628 }
629
630 #[test]
631 fn a_hash_mismatch_writes_nothing() {
632 let d = scratch("hash");
633 let t = target(&d, None, None);
634 let e = apply(&t, b"new", &sha256_hex(b"other"), &d).unwrap_err();
635 assert!(e.contains("does not match"));
636 assert!(!t.path.exists());
637 }
638
639 #[test]
640 fn apply_is_refused_unless_the_nodes_own_config_allows_it() {
641 let d = scratch("noapply");
642 let mut t = target(&d, None, None);
643 t.apply = false;
644 assert!(apply(&t, b"x", &sha256_hex(b"x"), &d)
645 .unwrap_err()
646 .contains("not set to apply"));
647 t.apply = true;
648 t.mode = "pull".into();
649 assert!(apply(&t, b"x", &sha256_hex(b"x"), &d).is_err());
650 assert!(!t.path.exists());
651 }
652
653 #[test]
654 fn writes_the_file_and_keeps_the_previous_one() {
655 let d = scratch("write");
656 let t = target(&d, None, None);
657 std::fs::write(&t.path, "old").unwrap();
658 assert_eq!(
659 apply(&t, b"new", &sha256_hex(b"new"), &d).unwrap(),
660 Applied::Written
661 );
662 assert_eq!(std::fs::read_to_string(&t.path).unwrap(), "new");
663 let kept = kept_versions(&d, "t");
664 assert_eq!(kept.len(), 1);
665 assert_eq!(std::fs::read_to_string(&kept[0]).unwrap(), "old");
666 assert_eq!(
668 apply(&t, b"new", &sha256_hex(b"new"), &d).unwrap(),
669 Applied::Unchanged
670 );
671 assert_eq!(kept_versions(&d, "t").len(), 1);
672 }
673
674 #[test]
675 fn only_the_last_three_versions_are_kept() {
676 let d = scratch("keep");
677 let t = target(&d, None, None);
678 std::fs::write(&t.path, "v0").unwrap();
679 for i in 1..=6 {
680 let c = format!("v{i}");
681 apply(&t, c.as_bytes(), &sha256_hex(c.as_bytes()), &d).unwrap();
684 }
685 assert_eq!(kept_versions(&d, "t").len(), KEEP_VERSIONS);
686 }
687
688 #[cfg(unix)]
690 #[test]
691 fn the_reload_signal_is_written_only_after_a_file_validated() {
692 let d = scratch("signal");
693 let ok = target(&d, Some("exit 0"), None);
694 std::fs::write(&ok.path, "old").unwrap();
695 apply(&ok, b"new", &sha256_hex(b"new"), &d).unwrap();
696 let sig = std::fs::read_to_string(reload_signal_path(&d, "t")).unwrap();
697 assert_eq!(sig.trim(), sha256_hex(b"new"));
698
699 let d2 = scratch("signal-bad");
700 let bad = target(&d2, Some("exit 1"), None);
701 std::fs::write(&bad.path, "old").unwrap();
702 apply(&bad, b"new", &sha256_hex(b"new"), &d2).unwrap_err();
703 assert!(
704 !reload_signal_path(&d2, "t").exists(),
705 "a rejected file must not trigger a reload"
706 );
707 }
708
709 #[cfg(unix)]
712 #[test]
713 fn a_rollback_never_overwrites_an_edit_made_during_validation() {
714 let d = scratch("clobber");
715 let t = target(&d, None, None);
716 let mut t = t;
717 t.validate = Some(format!(
718 "echo edited-by-hand > '{}'; exit 1",
719 t.path.display()
720 ));
721 std::fs::write(&t.path, "old").unwrap();
722 let e = apply(&t, b"new", &sha256_hex(b"new"), &d).unwrap_err();
723 assert!(e.contains("changed by someone else"), "{e}");
724 assert_eq!(
725 std::fs::read_to_string(&t.path).unwrap().trim(),
726 "edited-by-hand"
727 );
728 }
729
730 #[test]
731 fn two_writes_never_share_a_temp_file() {
732 let d = scratch("tmpname");
733 let p = d.join("app.conf");
734 write_atomic(&p, b"a", None, Perm::default()).unwrap();
735 write_atomic(&p, b"b", None, Perm::default()).unwrap();
736 let strays = std::fs::read_dir(&d)
737 .unwrap()
738 .flatten()
739 .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
740 .count();
741 assert_eq!(strays, 0);
742 assert_eq!(std::fs::read(&p).unwrap(), b"b");
743 }
744
745 #[cfg(unix)]
746 #[test]
747 fn a_failing_validate_restores_the_old_file_and_never_reloads() {
748 let d = scratch("validate");
749 let marker = d.join("reloaded");
750 let t = target(
751 &d,
752 Some("echo bad config >&2; exit 1"),
753 Some(&format!("touch {}", marker.display())),
754 );
755 std::fs::write(&t.path, "old").unwrap();
756 let e = apply(&t, b"new", &sha256_hex(b"new"), &d).unwrap_err();
757 assert!(e.contains("validate failed, previous file restored"), "{e}");
758 assert!(e.contains("bad config"), "{e}");
759 assert_eq!(std::fs::read_to_string(&t.path).unwrap(), "old");
760 assert!(!marker.exists(), "reload ran after a failed validate");
761 }
762
763 #[test]
764 fn a_failing_validate_on_a_new_file_removes_it() {
765 let d = scratch("validate-new");
766 let t = target(&d, Some("exit 3"), None);
767 assert!(apply(&t, b"new", &sha256_hex(b"new"), &d).is_err());
768 assert!(!t.path.exists());
769 }
770
771 #[test]
772 fn a_failing_reload_restores_the_old_file() {
773 let d = scratch("reload");
774 let t = target(&d, Some("exit 0"), Some("exit 2"));
775 std::fs::write(&t.path, "old").unwrap();
776 let e = apply(&t, b"new", &sha256_hex(b"new"), &d).unwrap_err();
777 assert!(e.contains("reload failed, previous file restored"), "{e}");
778 assert_eq!(std::fs::read_to_string(&t.path).unwrap(), "old");
779 }
780
781 #[cfg(unix)]
782 #[test]
783 fn validate_sees_the_new_file_in_place() {
784 let d = scratch("inplace");
785 let t = target(
786 &d,
787 Some(&format!("grep -q NEW {}", d.join("app.conf").display())),
788 None,
789 );
790 std::fs::write(&t.path, "old").unwrap();
791 assert!(apply(&t, b"NEW", &sha256_hex(b"NEW"), &d).is_ok());
792 }
793
794 #[cfg(unix)]
795 #[test]
796 fn a_runaway_command_is_killed_at_the_timeout() {
797 let t0 = Instant::now();
798 let e = run("sleep 30", "", Duration::from_millis(300)).unwrap_err();
799 assert!(e.contains("did not finish"), "{e}");
800 assert!(
801 t0.elapsed() < Duration::from_secs(5),
802 "waited for the command"
803 );
804 }
805
806 #[cfg(unix)]
807 #[test]
808 fn an_existing_files_mode_is_kept_and_a_new_one_is_private() {
809 use std::os::unix::fs::PermissionsExt;
810 let d = scratch("mode");
811 let t = target(&d, None, None);
812 std::fs::write(&t.path, "old").unwrap();
813 std::fs::set_permissions(&t.path, std::fs::Permissions::from_mode(0o640)).unwrap();
814 apply(&t, b"new", &sha256_hex(b"new"), &d).unwrap();
815 assert_eq!(
816 std::fs::metadata(&t.path).unwrap().permissions().mode() & 0o777,
817 0o640
818 );
819
820 let t2 = Target {
821 id: "u".into(),
822 path: d.join("fresh.conf"),
823 ..t
824 };
825 apply(&t2, b"x", &sha256_hex(b"x"), &d).unwrap();
826 assert_eq!(
827 std::fs::metadata(&t2.path).unwrap().permissions().mode() & 0o777,
828 0o600
829 );
830 let kept = kept_versions(&d, "t");
832 assert_eq!(
833 std::fs::metadata(&kept[0]).unwrap().permissions().mode() & 0o777,
834 0o600
835 );
836 }
837
838 #[test]
839 fn scrub_elides_a_line_of_the_file_and_keeps_the_rest() {
840 let content = "server {\n secret_token abcdef123456;\n}\n";
841 let out = scrub(
842 "nginx: [emerg] unknown directive in conf:2\nsecret_token abcdef123456;\n",
843 content,
844 );
845 assert!(!out.contains("abcdef123456"));
846 assert!(out.contains("unknown directive"));
847 assert!(out.contains("elided"));
848 }
849
850 #[test]
851 fn a_missing_file_has_no_hash_and_a_present_one_does() {
852 let d = scratch("hashfile");
853 assert_eq!(hash_file(&d.join("nope")).unwrap(), None);
854 std::fs::write(d.join("f"), "abc").unwrap();
855 assert_eq!(
856 hash_file(&d.join("f")).unwrap().unwrap(),
857 sha256_hex(b"abc")
858 );
859 }
860
861 #[cfg(unix)]
864 #[test]
865 fn a_validator_printing_a_megabyte_neither_deadlocks_nor_fails() {
866 let d = scratch("megabyte");
867 let t = target(
868 &d,
869 Some("head -c 1048576 /dev/zero | tr '\\0' 'x'; head -c 1048576 /dev/zero | tr '\\0' 'e' >&2; exit 0"),
870 None,
871 );
872 let started = Instant::now();
873 apply(&t, b"new", &sha256_hex(b"new"), &d).unwrap();
874 assert!(started.elapsed() < Duration::from_secs(10));
875 let bad = target(
877 &d,
878 Some("head -c 1048576 /dev/zero | tr '\\0' 'e' >&2; exit 3"),
879 None,
880 );
881 std::fs::write(&bad.path, "old").unwrap();
882 let err = apply(&bad, b"new2", &sha256_hex(b"new2"), &d).unwrap_err();
883 assert!(err.contains("exited 3"), "{err}");
884 assert_eq!(std::fs::read_to_string(&bad.path).unwrap(), "old");
885 }
886
887 #[cfg(unix)]
888 #[test]
889 fn a_path_validator_checks_a_temporary_file_and_the_live_file_is_never_invalid() {
890 let d = scratch("pathvalidate");
891 let marker = d.join("saw");
892 let validator = format!(
894 "echo {{file}} > '{}'; grep -q good {{file}}",
895 marker.display()
896 );
897 let t = target(&d, Some(&validator), None);
898 std::fs::write(&t.path, "old-good").unwrap();
899 let err = apply(&t, b"bad content", &sha256_hex(b"bad content"), &d).unwrap_err();
900 assert!(err.contains("the file was not replaced"), "{err}");
901 assert_eq!(std::fs::read_to_string(&t.path).unwrap(), "old-good");
902 let seen = std::fs::read_to_string(&marker).unwrap();
903 assert!(
904 seen.trim() != t.path.to_string_lossy() && seen.contains(".unv-check."),
905 "the validator saw the temporary file, not the target: {seen}"
906 );
907 let left: Vec<_> = std::fs::read_dir(&d)
908 .unwrap()
909 .flatten()
910 .filter(|e| e.file_name().to_string_lossy().contains(".unv-check."))
911 .collect();
912 assert!(left.is_empty(), "the temporary file is removed");
913 let (result, phases) = apply_with_phases(&t, b"good new", &sha256_hex(b"good new"), &d);
914 assert_eq!(result.unwrap(), Applied::Written);
915 assert_eq!(phases, vec!["written", "validated"]);
916 assert_eq!(std::fs::read_to_string(&t.path).unwrap(), "good new");
917 }
918
919 #[cfg(unix)]
920 #[test]
921 fn phases_name_each_step_and_a_failing_check_restores_and_reloads_the_previous_file() {
922 let d = scratch("check");
923 let reloads = d.join("reloads");
924 let mut t = target(
925 &d,
926 Some("exit 0"),
927 Some(&format!("echo r >> '{}'", reloads.display())),
928 );
929 t.check = Some("exit 0".into());
930 std::fs::write(&t.path, "old").unwrap();
931 let (result, phases) = apply_with_phases(&t, b"new", &sha256_hex(b"new"), &d);
932 assert_eq!(result.unwrap(), Applied::Written);
933 assert_eq!(phases, vec!["written", "validated", "reloaded", "checked"]);
934
935 let mut failing = target(
937 &d,
938 None,
939 Some(&format!("echo r >> '{}'", reloads.display())),
940 );
941 failing.check = Some("echo 'unhealthy' >&2; exit 1".into());
942 failing.id = "t2".into();
943 std::fs::write(&failing.path, "stable").unwrap();
944 let before = std::fs::read_to_string(&reloads).unwrap().lines().count();
945 let (result, phases) = apply_with_phases(&failing, b"broken", &sha256_hex(b"broken"), &d);
946 let err = result.unwrap_err();
947 assert!(
948 err.contains("check failed, previous file restored and reloaded"),
949 "{err}"
950 );
951 assert_eq!(std::fs::read_to_string(&failing.path).unwrap(), "stable");
952 assert_eq!(phases, vec!["written", "reloaded"]);
953 let after = std::fs::read_to_string(&reloads).unwrap().lines().count();
954 assert_eq!(
955 after - before,
956 2,
957 "once for the new file and once back onto the old"
958 );
959 assert!(
960 !reload_signal_path(&d, "t2").exists(),
961 "a failed check never signals a reload"
962 );
963 }
964
965 #[test]
966 fn an_http_check_wants_a_2xx_answer() {
967 let ok = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
968 let addr = ok.local_addr().unwrap();
969 let handle = std::thread::spawn(move || {
970 use std::io::Write;
971 for (n, stream) in ok.incoming().enumerate().take(2) {
972 let mut s = stream.unwrap();
973 let mut buf = [0u8; 256];
974 let _ = s.read(&mut buf);
975 let line = if n == 0 {
976 "HTTP/1.0 200 OK\r\n\r\n"
977 } else {
978 "HTTP/1.0 503 Service Unavailable\r\n\r\n"
979 };
980 let _ = s.write_all(line.as_bytes());
981 }
982 });
983 assert!(probe_http(&format!("http://{addr}/health"), Duration::from_secs(5)).is_ok());
984 let err = probe_http(&format!("http://{addr}/health"), Duration::from_secs(5)).unwrap_err();
985 assert!(err.contains("503"), "{err}");
986 handle.join().unwrap();
987 assert!(probe_http("https://example.test", Duration::from_secs(1)).is_err());
988 }
989
990 #[cfg(unix)]
993 fn stub_docker() {
994 use std::os::unix::fs::PermissionsExt;
995 static ONCE: std::sync::Once = std::sync::Once::new();
996 ONCE.call_once(|| {
997 let bin = scratch("docker-stub");
998 let script = bin.join("docker");
999 std::fs::write(
1000 &script,
1001 "#!/bin/sh\nd=$(dirname \"$5\")\necho \"$@\" >> \"$d/docker.log\"\n[ -e \"$d/fail\" ] && { echo 'service db: invalid' >&2; exit 1; }\nexit 0\n",
1002 )
1003 .unwrap();
1004 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
1005 let old = std::env::var("PATH").unwrap_or_default();
1006 std::env::set_var("PATH", format!("{}:{old}", bin.display()));
1007 });
1008 }
1009
1010 #[cfg(unix)]
1011 fn compose(d: &Path) -> Target {
1012 Target {
1013 path: d.join("db_password"),
1014 exporter: "compose-secret".into(),
1015 compose_project: Some("demo".into()),
1016 compose_file: Some(d.join("compose.yaml")),
1017 services: vec!["db".into()],
1018 ..target(d, None, None)
1019 }
1020 }
1021
1022 #[cfg(unix)]
1023 #[test]
1024 fn a_compose_target_writes_a_0400_file_validates_then_recreates_only_its_services() {
1025 use std::os::unix::fs::PermissionsExt;
1026 stub_docker();
1027 let d = scratch("compose-ok");
1028 let t = compose(&d);
1029 std::fs::write(&t.path, "old").unwrap();
1030 let (r, phases) = apply_with_phases(&t, b"s3cret", &sha256_hex(b"s3cret"), &d);
1031 assert_eq!(r.unwrap(), Applied::Written);
1032 assert_eq!(phases, vec!["written", "validated", "reloaded"]);
1033 assert_eq!(std::fs::read(&t.path).unwrap(), b"s3cret");
1034 assert_eq!(
1035 std::fs::metadata(&t.path).unwrap().permissions().mode() & 0o777,
1036 0o400
1037 );
1038 let f = d.join("compose.yaml");
1039 let log = std::fs::read_to_string(d.join("docker.log")).unwrap();
1040 assert_eq!(
1041 log,
1042 format!(
1043 "compose -p demo -f {f} config -q\ncompose -p demo -f {f} up -d --no-deps --force-recreate db\n",
1044 f = f.display()
1045 )
1046 );
1047 assert!(kept_versions(&d, "t").is_empty());
1049 }
1050
1051 #[cfg(unix)]
1052 #[test]
1053 fn a_failing_compose_validation_puts_the_old_file_back_with_its_mode_and_recreates_nothing() {
1054 use std::os::unix::fs::PermissionsExt;
1055 stub_docker();
1056 let d = scratch("compose-bad");
1057 let t = compose(&d);
1058 std::fs::write(&t.path, "old").unwrap();
1059 std::fs::set_permissions(&t.path, std::fs::Permissions::from_mode(0o400)).unwrap();
1060 std::fs::write(d.join("fail"), "").unwrap();
1061 let (r, phases) = apply_with_phases(&t, b"s3cret", &sha256_hex(b"s3cret"), &d);
1062 let e = r.unwrap_err();
1063 assert!(e.contains("validate failed, previous file restored"), "{e}");
1064 assert!(!e.contains("s3cret"));
1065 assert_eq!(phases, vec!["written"]);
1066 assert_eq!(std::fs::read(&t.path).unwrap(), b"old");
1067 assert_eq!(
1068 std::fs::metadata(&t.path).unwrap().permissions().mode() & 0o777,
1069 0o400
1070 );
1071 let log = std::fs::read_to_string(d.join("docker.log")).unwrap();
1072 assert_eq!(log.lines().count(), 1, "only the config check ran: {log}");
1073 assert!(!log.contains("up -d"));
1074 }
1075
1076 #[cfg(unix)]
1077 #[test]
1078 fn a_first_write_that_fails_validation_leaves_no_file_at_all() {
1079 stub_docker();
1080 let d = scratch("compose-new-bad");
1081 let t = compose(&d);
1082 std::fs::write(d.join("fail"), "").unwrap();
1083 assert!(apply(&t, b"s3cret", &sha256_hex(b"s3cret"), &d).is_err());
1084 assert!(!t.path.exists());
1085 }
1086
1087 #[cfg(unix)]
1088 #[test]
1089 fn an_explicit_file_mode_and_an_owner_apply_to_any_target() {
1090 use std::os::unix::fs::{MetadataExt, PermissionsExt};
1091 let d = scratch("perm");
1092 let me = std::fs::metadata(&d).unwrap();
1093 let t = Target {
1094 file_mode: Some("0440".into()),
1095 owner: Some(format!("{}:{}", me.uid(), me.gid())),
1096 ..target(&d, None, None)
1097 };
1098 apply(&t, b"x", &sha256_hex(b"x"), &d).unwrap();
1099 let m = std::fs::metadata(&t.path).unwrap();
1100 assert_eq!(m.permissions().mode() & 0o777, 0o440);
1101 assert_eq!((m.uid(), m.gid()), (me.uid(), me.gid()));
1102 }
1103
1104 #[cfg(unix)]
1105 #[test]
1106 fn an_owner_the_node_may_not_give_is_refused_before_the_file_changes() {
1107 use std::os::unix::fs::MetadataExt;
1108 let d = scratch("perm-refused");
1109 if std::fs::metadata(&d).unwrap().uid() == 0 {
1110 return; }
1112 let t = Target {
1113 owner: Some("0:0".into()),
1114 ..target(&d, None, None)
1115 };
1116 std::fs::write(&t.path, "old").unwrap();
1117 let e = apply(&t, b"new", &sha256_hex(b"new"), &d).unwrap_err();
1118 assert!(e.contains("cannot give"), "{e}");
1119 assert_eq!(std::fs::read(&t.path).unwrap(), b"old");
1120 let stray: Vec<_> = std::fs::read_dir(&d)
1121 .unwrap()
1122 .flatten()
1123 .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
1124 .collect();
1125 assert!(stray.is_empty(), "no temporary file is left behind");
1126 }
1127}