forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiB0d793e7Tahinli8 hours ago359 commits

mod.rs691 lines, 20.0 KiBHistoryRawDownload
1pub mod worker;
2
3use std::collections::HashMap;
4use std::future::Future;
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Mutex, PoisonError};
8use std::time::{Duration, Instant};
9
10use forge_git::GitEnv;
11use forge_git::backup::REFS_FORMAT;
12use forge_git::command::GitCommand;
13use tokio::process::Command;
14use tokio::sync::Notify;
15
16use crate::state::AppState;
17
18pub const PUSH_DEBOUNCE: Duration = Duration::from_secs(5);
19pub const KEEP_SNAPSHOTS: usize = 24;
20const DB_DIR: &str = "db";
21const REPOS_DIR: &str = "repos";
22const SNAPSHOT_PREFIX: &str = "forge-";
23const SNAPSHOT_SUFFIX: &str = ".db";
24const STAMP_LEN: usize = 16;
25
26pub fn validate_remote_path(path: &str) -> Result<(), String> {
27 let well_formed = path.starts_with('/')
28 && path.len() > 1
29 && !path.ends_with('/')
30 && !path.contains("//")
31 && !path.contains("..")
32 && path
33 .bytes()
34 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'/' | b'-'));
35 if well_formed {
36 Ok(())
37 } else {
38 Err(format!(
39 "remote path must be absolute, use only [A-Za-z0-9._/-], and have no '..': {path:?}"
40 ))
41 }
42}
43
44pub fn validate_repo_id(id: &str) -> Result<(), String> {
45 if id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) {
46 Ok(())
47 } else {
48 Err(format!("not a repo id: {id:?}"))
49 }
50}
51
52pub fn sh_quote(arg: &str) -> String {
53 format!("'{}'", arg.replace('\'', "'\\''"))
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Target {
58 pub user: Option<String>,
59 pub host: String,
60 pub port: u16,
61 pub base: String,
62}
63
64impl Target {
65 pub fn parse(spec: &str, port: u16) -> Result<Target, String> {
66 let (dest, base) = spec
67 .split_once(':')
68 .ok_or_else(|| "replication target must be [user@]host:/absolute/path".to_string())?;
69 let (user, host) = match dest.split_once('@') {
70 Some((user, host)) => (Some(user), host),
71 None => (None, dest),
72 };
73 if let Some(user) = user {
74 let ok = !user.is_empty()
75 && !user.starts_with('-')
76 && user
77 .bytes()
78 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
79 if !ok {
80 return Err(format!("invalid user in replication target: {user:?}"));
81 }
82 }
83 let host_ok = !host.is_empty()
84 && !host.starts_with('-')
85 && host
86 .bytes()
87 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'));
88 if !host_ok {
89 return Err(format!("invalid host in replication target: {host:?}"));
90 }
91 validate_remote_path(base)?;
92 Ok(Target {
93 user: user.map(str::to_owned),
94 host: host.to_owned(),
95 port,
96 base: base.to_owned(),
97 })
98 }
99
100 pub fn destination(&self) -> String {
101 match &self.user {
102 Some(user) => format!("{user}@{}", self.host),
103 None => self.host.clone(),
104 }
105 }
106
107 pub fn repo_url(&self, remote_repo_dir: &str) -> String {
108 format!(
109 "ssh://{}:{}{remote_repo_dir}",
110 self.destination(),
111 self.port
112 )
113 }
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct Layout {
118 pub base: String,
119}
120
121impl Layout {
122 pub fn new(base: &str) -> Result<Layout, String> {
123 validate_remote_path(base)?;
124 Ok(Layout {
125 base: base.to_owned(),
126 })
127 }
128
129 pub fn repos_dir(&self) -> String {
130 format!("{}/{REPOS_DIR}", self.base)
131 }
132
133 pub fn db_dir(&self) -> String {
134 format!("{}/{DB_DIR}", self.base)
135 }
136
137 pub fn repo_dir(&self, repo_id: &str) -> Result<String, String> {
138 validate_repo_id(repo_id)?;
139 Ok(format!("{}/{repo_id}.git", self.repos_dir()))
140 }
141
142 pub fn snapshot_file(&self, stamp: &str) -> String {
143 format!(
144 "{}/{SNAPSHOT_PREFIX}{stamp}{SNAPSHOT_SUFFIX}",
145 self.db_dir()
146 )
147 }
148
149 pub fn latest_link(&self) -> String {
150 format!("{}/latest", self.db_dir())
151 }
152}
153
154pub fn is_snapshot_name(name: &str) -> bool {
155 let Some(stamp) = name
156 .strip_prefix(SNAPSHOT_PREFIX)
157 .and_then(|rest| rest.strip_suffix(SNAPSHOT_SUFFIX))
158 else {
159 return false;
160 };
161 stamp.len() == STAMP_LEN
162 && stamp.bytes().enumerate().all(|(i, b)| match i {
163 8 => b == b'T',
164 15 => b == b'Z',
165 _ => b.is_ascii_digit(),
166 })
167}
168
169pub fn snapshot_stamp() -> String {
170 const FORMAT: &[time::format_description::FormatItem<'static>] =
171 time::macros::format_description!("[year][month][day]T[hour][minute][second]Z");
172 time::OffsetDateTime::now_utc()
173 .format(FORMAT)
174 .unwrap_or_else(|_| "00000000T000000Z".to_owned())
175}
176
177pub trait StandbyTransport: Send + Sync {
178 fn run(&self, remote_cmd: &str) -> impl Future<Output = Result<Vec<u8>, String>> + Send;
179
180 fn repo_url(&self, remote_repo_dir: &str) -> String;
181
182 fn local_git(&self) -> bool;
183
184 fn push_ssh_command(&self) -> Option<String>;
185
186 fn upload(
187 &self,
188 local: &Path,
189 remote_path: &str,
190 ) -> impl Future<Output = Result<(), String>> + Send;
191}
192
193fn upload_command(remote_path: &str) -> String {
194 let (dir, name) = remote_path.rsplit_once('/').unwrap_or(("", remote_path));
195 let tmp = format!("{dir}/.tmp-{name}");
196 format!(
197 "cat > {} && mv -f {} {}",
198 sh_quote(&tmp),
199 sh_quote(&tmp),
200 sh_quote(remote_path)
201 )
202}
203
204async fn pipe_file(mut command: Command, file: &Path) -> Result<(), String> {
205 use std::process::Stdio;
206 use tokio::io::AsyncWriteExt;
207 command
208 .stdin(Stdio::piped())
209 .stdout(Stdio::null())
210 .stderr(Stdio::piped())
211 .kill_on_drop(true);
212 let mut child = command
213 .spawn()
214 .map_err(|e| format!("cannot start ssh: {e}"))?;
215 let mut stdin = child
216 .stdin
217 .take()
218 .ok_or_else(|| "ssh stdin is not available".to_string())?;
219 let mut source = tokio::fs::File::open(file)
220 .await
221 .map_err(|e| format!("cannot read {}: {e}", file.display()))?;
222 tokio::io::copy(&mut source, &mut stdin)
223 .await
224 .map_err(|e| format!("upload failed: {e}"))?;
225 stdin
226 .shutdown()
227 .await
228 .map_err(|e| format!("upload failed: {e}"))?;
229 drop(stdin);
230 let out = child
231 .wait_with_output()
232 .await
233 .map_err(|e| format!("upload failed: {e}"))?;
234 if out.status.success() {
235 Ok(())
236 } else {
237 Err(format!(
238 "upload exited with {}: {}",
239 out.status,
240 String::from_utf8_lossy(&out.stderr).trim()
241 ))
242 }
243}
244
245async fn capture(mut command: Command) -> Result<Vec<u8>, String> {
246 use std::process::Stdio;
247 command.stdin(Stdio::null()).kill_on_drop(true);
248 let out = command
249 .output()
250 .await
251 .map_err(|e| format!("cannot start ssh: {e}"))?;
252 if out.status.success() {
253 Ok(out.stdout)
254 } else {
255 Err(format!(
256 "remote command exited with {}: {}",
257 out.status,
258 String::from_utf8_lossy(&out.stderr).trim()
259 ))
260 }
261}
262
263async fn push_mirror(
264 git: &GitEnv,
265 repo_dir: &Path,
266 url: &str,
267 local_git: bool,
268 ssh_command: Option<String>,
269) -> Result<(), String> {
270 let mut cmd = GitCommand::new(git, "push")
271 .git_dir(repo_dir)
272 .arg("--mirror")
273 .arg("--force")
274 .arg("--quiet");
275 if local_git {
276 cmd = cmd.allow_local_transport();
277 }
278 if let Some(ssh) = ssh_command {
279 cmd = cmd.env("GIT_SSH_COMMAND", ssh);
280 }
281 cmd.arg("--end-of-options")
282 .user_arg(url)
283 .map_err(|e| e.to_string())?
284 .status()
285 .await
286 .map_err(|e| e.to_string())
287}
288
289#[derive(Debug, Clone)]
290pub struct SshTransport {
291 target: Target,
292 identity_file: PathBuf,
293 known_hosts_file: PathBuf,
294}
295
296impl SshTransport {
297 pub fn new(target: Target, identity_file: PathBuf, known_hosts_file: PathBuf) -> SshTransport {
298 SshTransport {
299 target,
300 identity_file,
301 known_hosts_file,
302 }
303 }
304
305 pub fn ssh_options(&self) -> Vec<String> {
306 vec![
307 "-i".to_owned(),
308 self.identity_file.to_string_lossy().into_owned(),
309 "-o".to_owned(),
310 "IdentitiesOnly=yes".to_owned(),
311 "-o".to_owned(),
312 format!(
313 "UserKnownHostsFile={}",
314 self.known_hosts_file.to_string_lossy()
315 ),
316 "-o".to_owned(),
317 "StrictHostKeyChecking=yes".to_owned(),
318 "-o".to_owned(),
319 "BatchMode=yes".to_owned(),
320 "-o".to_owned(),
321 "ConnectTimeout=20".to_owned(),
322 "-p".to_owned(),
323 self.target.port.to_string(),
324 ]
325 }
326
327 pub fn ssh_argv(&self, remote_cmd: &str) -> Vec<String> {
328 let mut argv = self.ssh_options();
329 argv.push(self.target.destination());
330 argv.push(remote_cmd.to_owned());
331 argv
332 }
333
334 pub fn git_ssh_command(&self) -> String {
335 std::iter::once("ssh".to_owned())
336 .chain(self.ssh_options())
337 .map(|word| sh_quote(&word))
338 .collect::<Vec<_>>()
339 .join(" ")
340 }
341
342 fn command(&self, remote_cmd: &str) -> Command {
343 let mut cmd = Command::new("ssh");
344 cmd.args(self.ssh_argv(remote_cmd));
345 cmd
346 }
347}
348
349impl StandbyTransport for SshTransport {
350 fn run(&self, remote_cmd: &str) -> impl Future<Output = Result<Vec<u8>, String>> + Send {
351 let cmd = self.command(remote_cmd);
352 capture(cmd)
353 }
354
355 fn repo_url(&self, remote_repo_dir: &str) -> String {
356 self.target.repo_url(remote_repo_dir)
357 }
358
359 fn local_git(&self) -> bool {
360 false
361 }
362
363 fn push_ssh_command(&self) -> Option<String> {
364 Some(self.git_ssh_command())
365 }
366
367 fn upload(
368 &self,
369 local: &Path,
370 remote_path: &str,
371 ) -> impl Future<Output = Result<(), String>> + Send {
372 let cmd = self.command(&upload_command(remote_path));
373 let local = local.to_path_buf();
374 async move { pipe_file(cmd, &local).await }
375 }
376}
377
378#[cfg(any(test, feature = "test-support"))]
379#[derive(Debug, Clone, Copy, Default)]
380pub struct LocalTransport;
381
382#[cfg(any(test, feature = "test-support"))]
383impl StandbyTransport for LocalTransport {
384 fn run(&self, remote_cmd: &str) -> impl Future<Output = Result<Vec<u8>, String>> + Send {
385 let mut cmd = Command::new("sh");
386 cmd.arg("-c").arg(remote_cmd);
387 capture(cmd)
388 }
389
390 fn repo_url(&self, remote_repo_dir: &str) -> String {
391 remote_repo_dir.to_owned()
392 }
393
394 fn local_git(&self) -> bool {
395 true
396 }
397
398 fn push_ssh_command(&self) -> Option<String> {
399 None
400 }
401
402 fn upload(
403 &self,
404 local: &Path,
405 remote_path: &str,
406 ) -> impl Future<Output = Result<(), String>> + Send {
407 let mut cmd = Command::new("sh");
408 cmd.arg("-c").arg(upload_command(remote_path));
409 let local = local.to_path_buf();
410 async move { pipe_file(cmd, &local).await }
411 }
412}
413
414pub async fn push_repo<T: StandbyTransport>(
415 transport: &T,
416 git: &GitEnv,
417 repo_dir: &Path,
418 remote_repo_dir: &str,
419) -> Result<(), String> {
420 push_mirror(
421 git,
422 repo_dir,
423 &transport.repo_url(remote_repo_dir),
424 transport.local_git(),
425 transport.push_ssh_command(),
426 )
427 .await
428}
429
430pub async fn remote_refs_checksum<T: StandbyTransport>(
431 transport: &T,
432 remote_repo_dir: &str,
433) -> Result<String, String> {
434 let cmd = format!(
435 "git -C {} for-each-ref {}",
436 sh_quote(remote_repo_dir),
437 sh_quote(REFS_FORMAT)
438 );
439 let out = transport.run(&cmd).await?;
440 Ok(forge_git::backup::refs_checksum_of_listing(&out))
441}
442
443#[derive(Default)]
444pub struct ReplicationQueue {
445 notify: Notify,
446 pending: Mutex<HashMap<String, Instant>>,
447 reconcile: AtomicBool,
448}
449
450impl ReplicationQueue {
451 pub fn enqueue(&self, repo_id: &str) {
452 let due = Instant::now() + PUSH_DEBOUNCE;
453 self.pending
454 .lock()
455 .unwrap_or_else(PoisonError::into_inner)
456 .insert(repo_id.to_owned(), due);
457 self.notify.notify_one();
458 }
459
460 pub fn take_due(&self, now: Instant) -> Vec<String> {
461 let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
462 let mut due: Vec<String> = pending
463 .iter()
464 .filter(|(_, at)| **at <= now)
465 .map(|(id, _)| id.clone())
466 .collect();
467 due.sort();
468 for id in &due {
469 pending.remove(id);
470 }
471 due
472 }
473
474 pub fn next_due(&self) -> Option<Instant> {
475 self.pending
476 .lock()
477 .unwrap_or_else(PoisonError::into_inner)
478 .values()
479 .min()
480 .copied()
481 }
482
483 pub fn request_reconcile(&self) {
484 self.reconcile.store(true, Ordering::SeqCst);
485 self.notify.notify_one();
486 }
487
488 pub fn take_reconcile_request(&self) -> bool {
489 self.reconcile.swap(false, Ordering::SeqCst)
490 }
491
492 pub async fn wait(&self) {
493 self.notify.notified().await;
494 }
495}
496
497pub fn enqueue_repo(state: &AppState, repo_id: &str) {
498 if state.config.replication.enabled() {
499 state.replication.enqueue(repo_id);
500 }
501}
502
503#[cfg(test)]
504mod tests {
505 use super::*;
506
507 #[test]
508 fn remote_paths_must_be_plain_absolute_paths() {
509 for ok in ["/srv/forge-standby", "/srv/a.b_c-d/e", "/x"] {
510 assert!(validate_remote_path(ok).is_ok(), "{ok} should pass");
511 }
512 for bad in [
513 "",
514 "/",
515 "srv/forge",
516 "./srv",
517 "/srv/../etc",
518 "/srv/..",
519 "/srv/a/../b",
520 "/srv//x",
521 "/srv/x/",
522 "/srv/with space",
523 "/srv/quote'",
524 "/srv/$HOME",
525 "/srv/a;rm",
526 "/srv/a`b`",
527 "/srv/é",
528 "/srv/x\n",
529 ] {
530 assert!(validate_remote_path(bad).is_err(), "{bad:?} should fail");
531 }
532 }
533
534 #[test]
535 fn repo_ids_must_be_ulid_shaped() {
536 assert!(validate_repo_id("01ARZ3NDEKTSV4RRFFQ69G5FAV").is_ok());
537 assert!(validate_repo_id("01ARZ3NDEKTSV4RRFFQ69G5FA").is_err());
538 assert!(validate_repo_id("../../etc/passwd0000000000").is_err());
539 assert!(validate_repo_id("01ARZ3NDEKTSV4RRFFQ69G5F'V").is_err());
540 }
541
542 #[test]
543 fn quoting_survives_spaces_quotes_and_metacharacters() {
544 assert_eq!(sh_quote("/srv/x"), "'/srv/x'");
545 assert_eq!(sh_quote(""), "''");
546 assert_eq!(sh_quote("a b"), "'a b'");
547 assert_eq!(sh_quote("it's"), "'it'\\''s'");
548 assert_eq!(sh_quote("$(rm -rf /)`x`;|&"), "'$(rm -rf /)`x`;|&'");
549 assert_eq!(sh_quote("'"), "''\\'''");
550 let words = ["plain", "it's", "a b", "$HOME", "x'y'z", "back\\slash"];
551 let line = words
552 .iter()
553 .map(|w| sh_quote(w))
554 .collect::<Vec<_>>()
555 .join(" ");
556 let script = format!("printf '%s\\0' {line}");
557 let out = std::process::Command::new("sh")
558 .arg("-c")
559 .arg(&script)
560 .output()
561 .expect("sh runs");
562 let got: Vec<String> = out
563 .stdout
564 .split(|b| *b == 0)
565 .filter(|s| !s.is_empty())
566 .map(|s| String::from_utf8_lossy(s).into_owned())
567 .collect();
568 assert_eq!(got, words);
569 }
570
571 #[test]
572 fn target_parses_user_host_and_base_and_refuses_bad_specs() {
573 let t = Target::parse("sb@standby.example:/srv/forge-standby", 2222).expect("parse");
574 assert_eq!(t.user.as_deref(), Some("sb"));
575 assert_eq!(t.host, "standby.example");
576 assert_eq!(t.port, 2222);
577 assert_eq!(t.base, "/srv/forge-standby");
578 assert_eq!(
579 t.repo_url("/srv/forge-standby/repos/X.git"),
580 "ssh://sb@standby.example:2222/srv/forge-standby/repos/X.git"
581 );
582 let bare = Target::parse("standby:/srv/x", 22).expect("parse");
583 assert_eq!(bare.destination(), "standby");
584 for bad in [
585 "no-colon",
586 "sb@host",
587 "sb@host:relative",
588 "sb@host:/srv/../x",
589 "-oProxyCommand=x@host:/srv",
590 "@host:/srv",
591 "sb@:/srv",
592 "sb@-x:/srv",
593 "sb x@host:/srv",
594 "sb@ho st:/srv",
595 "sb@host:/srv/a b",
596 ] {
597 assert!(Target::parse(bad, 22).is_err(), "{bad:?} should be refused");
598 }
599 }
600
601 #[test]
602 fn layout_paths_follow_the_contract() {
603 let layout = Layout::new("/srv/sb").expect("layout");
604 assert_eq!(
605 layout.repo_dir("01ARZ3NDEKTSV4RRFFQ69G5FAV").expect("id"),
606 "/srv/sb/repos/01ARZ3NDEKTSV4RRFFQ69G5FAV.git"
607 );
608 assert!(layout.repo_dir("../x").is_err());
609 assert_eq!(
610 layout.snapshot_file("20260101T000000Z"),
611 "/srv/sb/db/forge-20260101T000000Z.db"
612 );
613 assert_eq!(layout.latest_link(), "/srv/sb/db/latest");
614 assert!(Layout::new("relative").is_err());
615 }
616
617 #[test]
618 fn snapshot_names_are_recognised_strictly() {
619 assert!(is_snapshot_name("forge-20260101T120000Z.db"));
620 assert!(!is_snapshot_name("forge-20260101T120000Z.db.tmp"));
621 assert!(!is_snapshot_name("latest"));
622 assert!(!is_snapshot_name(".tmp-forge-20260101T120000Z.db"));
623 assert!(!is_snapshot_name("forge-2026-01-01T12:00:00Z.db"));
624 assert!(!is_snapshot_name("forge-20260101X120000Z.db"));
625 let stamp = snapshot_stamp();
626 assert!(is_snapshot_name(&format!("forge-{stamp}.db")), "{stamp}");
627 }
628
629 #[test]
630 fn ssh_argv_pins_the_host_key_and_identity() {
631 let target = Target::parse("sb@standby.example:/srv/sb", 2200).expect("target");
632 let transport = SshTransport::new(
633 target,
634 PathBuf::from("/etc/forge/standby_key"),
635 PathBuf::from("/etc/forge/standby_known_hosts"),
636 );
637 let argv = transport.ssh_argv("true");
638 let expected = [
639 "-i",
640 "/etc/forge/standby_key",
641 "-o",
642 "IdentitiesOnly=yes",
643 "-o",
644 "UserKnownHostsFile=/etc/forge/standby_known_hosts",
645 "-o",
646 "StrictHostKeyChecking=yes",
647 "-o",
648 "BatchMode=yes",
649 "-o",
650 "ConnectTimeout=20",
651 "-p",
652 "2200",
653 "sb@standby.example",
654 "true",
655 ];
656 assert_eq!(argv, expected);
657 assert!(!argv.iter().any(|a| a.contains("StrictHostKeyChecking=no")));
658 assert_eq!(
659 transport.git_ssh_command(),
660 "'ssh' '-i' '/etc/forge/standby_key' '-o' 'IdentitiesOnly=yes' \
661 '-o' 'UserKnownHostsFile=/etc/forge/standby_known_hosts' \
662 '-o' 'StrictHostKeyChecking=yes' '-o' 'BatchMode=yes' \
663 '-o' 'ConnectTimeout=20' '-p' '2200'"
664 );
665 }
666
667 #[test]
668 fn upload_command_writes_a_temp_then_renames() {
669 assert_eq!(
670 upload_command("/srv/sb/db/forge-20260101T000000Z.db"),
671 "cat > '/srv/sb/db/.tmp-forge-20260101T000000Z.db' && mv -f \
672 '/srv/sb/db/.tmp-forge-20260101T000000Z.db' '/srv/sb/db/forge-20260101T000000Z.db'"
673 );
674 }
675
676 #[test]
677 fn queue_debounces_and_drains_due_repos() {
678 let queue = ReplicationQueue::default();
679 queue.enqueue("b");
680 queue.enqueue("a");
681 assert!(queue.take_due(Instant::now()).is_empty(), "not due yet");
682 let later = Instant::now() + PUSH_DEBOUNCE + Duration::from_millis(10);
683 assert_eq!(queue.take_due(later), ["a", "b"]);
684 assert!(queue.take_due(later).is_empty(), "drained");
685 assert_eq!(queue.next_due(), None, "nothing left to wait for");
686 assert!(!queue.take_reconcile_request());
687 queue.request_reconcile();
688 assert!(queue.take_reconcile_request());
689 assert!(!queue.take_reconcile_request(), "one request, one pass");
690 }
691}