A builtin job with network = true gets its own network namespace through pasta (internet yes
Browse files at this commit570e5920c047dc7c86c82577ac025a151536fc00Parent: 389919a- harden
- a builtin job with network = true gets its own network namespace through pasta (internet yes
- the runner's localhost, private and link-local ranges no
- IPv6 none), and shares the host's only when pasta is missing, saying so in the job log
- a job may fill limits.job_disk_gb (20, on the runner page) of disk before it is stopped
- the runner removes leftover job dirs, cgroups, pasta processes and workspaces at startup
15 changed files +613 -20
- crates/forge-core/src/ci.rs +5 -0
- crates/forge-runner/src/check.rs +1 -0
- crates/forge-runner/src/cli.rs +3 -0
- crates/forge-runner/src/config.rs +14 -0
- crates/forge-runner/src/disk.rs +64 -0
- crates/forge-runner/src/executor.rs +158 -3
- crates/forge-runner/src/lib.rs +1 -0
- crates/forge-runner/src/sandbox/helper.rs +21 -4
- crates/forge-runner/src/sandbox/mod.rs +8 -1
- crates/forge-runner/src/sandbox/net.rs +264 -0
- crates/forge-runner/src/sandbox/spec.rs +19 -6
- crates/forge-runner/tests/integration/builtin.rs +27 -0
- crates/forge-runner/tests/integration/sandbox.rs +1 -0
- crates/forge-web/src/pages/admin_runners.rs +10 -0
- docs/ci.md +17 -6
crates/forge-core/src/ci.rsmodified+5 -0
| @@ -245,6 +245,10 @@ pub const RUNNER_FIELDS: &[RunnerField] = &[ | |||
| 245 | key: "limits.image_max_gb", | 245 | key: "limits.image_max_gb", |
| 246 | kind: FieldKind::Restart, | 246 | kind: FieldKind::Restart, |
| 247 | }, | 247 | }, |
| 248 | + RunnerField { | ||
| 249 | + key: "limits.job_disk_gb", | ||
| 250 | + kind: FieldKind::Restart, | ||
| 251 | + }, | ||
| 248 | RunnerField { | 252 | RunnerField { |
| 249 | key: "images.keep_days", | 253 | key: "images.keep_days", |
| 250 | kind: FieldKind::Restart, | 254 | kind: FieldKind::Restart, |
| @@ -385,6 +389,7 @@ pub fn validate_runner_field( | |||
| 385 | } | 389 | } |
| 386 | "limits.pids" => int_in(raw, 1, 4_194_304, "pids"), | 390 | "limits.pids" => int_in(raw, 1, 4_194_304, "pids"), |
| 387 | "limits.image_max_gb" => int_in(raw, 1, 100_000, "image_max_gb"), | 391 | "limits.image_max_gb" => int_in(raw, 1, 100_000, "image_max_gb"), |
| 392 | + "limits.job_disk_gb" => int_in(raw, 0, 1_000_000, "job_disk_gb"), | ||
| 388 | "images.keep_days" => int_in(raw, 0, 3650, "keep_days"), | 393 | "images.keep_days" => int_in(raw, 0, 3650, "keep_days"), |
| 389 | "cache_max_gib" => int_in(raw, 0, 1_000_000, "cache_max_gib"), | 394 | "cache_max_gib" => int_in(raw, 0, 1_000_000, "cache_max_gib"), |
| 390 | _ => Err("this field cannot be changed from the forge".into()), | 395 | _ => Err("this field cannot be changed from the forge".into()), |
crates/forge-runner/src/check.rsmodified+1 -0
| @@ -174,6 +174,7 @@ async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe, | |||
| 174 | env: Vec::new(), | 174 | env: Vec::new(), |
| 175 | run: script.to_owned(), | 175 | run: script.to_owned(), |
| 176 | network: false, | 176 | network: false, |
| 177 | + pasta: None, | ||
| 177 | limits: Limits::default(), | 178 | limits: Limits::default(), |
| 178 | idmap: map.clone(), | 179 | idmap: map.clone(), |
| 179 | }; | 180 | }; |
crates/forge-runner/src/cli.rsmodified+3 -0
| @@ -161,6 +161,7 @@ fn hidden_dispatch(args: &[OsString]) -> i32 { | |||
| 161 | match args.first().map(|arg| arg.as_encoded_bytes()) { | 161 | match args.first().map(|arg| arg.as_encoded_bytes()) { |
| 162 | Some(b"__sandbox") => crate::sandbox::helper_main(), | 162 | Some(b"__sandbox") => crate::sandbox::helper_main(), |
| 163 | Some(b"__sandbox-rm") => crate::sandbox::idmap::rm_helper_main(&args[1..]), | 163 | Some(b"__sandbox-rm") => crate::sandbox::idmap::rm_helper_main(&args[1..]), |
| 164 | + Some(b"__sandbox-net") => crate::sandbox::net::net_helper_main(&args[1..]), | ||
| 164 | Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]), | 165 | Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]), |
| 165 | Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(), | 166 | Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(), |
| 166 | _ => { | 167 | _ => { |
| @@ -265,6 +266,8 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 265 | let images = ImageStore::new(root) | 266 | let images = ImageStore::new(root) |
| 266 | .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb)) | 267 | .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb)) |
| 267 | .with_idmap(map.clone(), helper.clone()); | 268 | .with_idmap(map.clone(), helper.clone()); |
| 269 | + // Before the first job: what an earlier run left behind. | ||
| 270 | + crate::executor::sweep_leftovers(&cfg.work_dir, &map, &helper).await; | ||
| 268 | let jobs_dir = cfg.work_dir.join("jobs"); | 271 | let jobs_dir = cfg.work_dir.join("jobs"); |
| 269 | let executor = | 272 | let executor = |
| 270 | BuiltinExecutor::new(images, cfg.limits.clone(), helper, jobs_dir) | 273 | BuiltinExecutor::new(images, cfg.limits.clone(), helper, jobs_dir) |
crates/forge-runner/src/config.rsmodified+14 -0
| @@ -40,6 +40,10 @@ pub struct Limits { | |||
| 40 | /// The cap on the unpacked size of one image, in GB. Used by the builtin executor. | 40 | /// The cap on the unpacked size of one image, in GB. Used by the builtin executor. |
| 41 | #[serde(default = "default_image_max_gb")] | 41 | #[serde(default = "default_image_max_gb")] |
| 42 | pub image_max_gb: u64, | 42 | pub image_max_gb: u64, |
| 43 | + /// The disk one job may fill, in GB: its workspace, its `/tmp` and what it writes over the | ||
| 44 | + /// image. Past it the job is stopped and fails. 0 means no cap. Used by the builtin executor. | ||
| 45 | + #[serde(default = "default_job_disk_gb")] | ||
| 46 | + pub job_disk_gb: u64, | ||
| 43 | /// What a job that declares no `memory` reserves when it is admitted, and the floor for its | 47 | /// What a job that declares no `memory` reserves when it is admitted, and the floor for its |
| 44 | /// cgroup limit. Live: an admin can change it from the forge without a restart. | 48 | /// cgroup limit. Live: an admin can change it from the forge without a restart. |
| 45 | #[serde(default = "default_reserve_memory")] | 49 | #[serde(default = "default_reserve_memory")] |
| @@ -72,6 +76,7 @@ impl Default for Limits { | |||
| 72 | cpus: "2".to_owned(), | 76 | cpus: "2".to_owned(), |
| 73 | pids: 4096, | 77 | pids: 4096, |
| 74 | image_max_gb: default_image_max_gb(), | 78 | image_max_gb: default_image_max_gb(), |
| 79 | + job_disk_gb: default_job_disk_gb(), | ||
| 75 | reserve_memory: default_reserve_memory(), | 80 | reserve_memory: default_reserve_memory(), |
| 76 | memory_budget: None, | 81 | memory_budget: None, |
| 77 | memory_headroom: default_memory_headroom(), | 82 | memory_headroom: default_memory_headroom(), |
| @@ -240,6 +245,10 @@ pub fn default_image_max_gb() -> u64 { | |||
| 240 | 20 | 245 | 20 |
| 241 | } | 246 | } |
| 242 | 247 | ||
| 248 | +pub fn default_job_disk_gb() -> u64 { | ||
| 249 | + 20 | ||
| 250 | +} | ||
| 251 | + | ||
| 243 | impl fmt::Debug for RunnerConfig { | 252 | impl fmt::Debug for RunnerConfig { |
| 244 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | 253 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 245 | f.debug_struct("RunnerConfig") | 254 | f.debug_struct("RunnerConfig") |
| @@ -330,6 +339,7 @@ impl RunnerConfig { | |||
| 330 | "limits.image_max_gb".into(), | 339 | "limits.image_max_gb".into(), |
| 331 | json!(self.limits.image_max_gb), | 340 | json!(self.limits.image_max_gb), |
| 332 | ); | 341 | ); |
| 342 | + m.insert("limits.job_disk_gb".into(), json!(self.limits.job_disk_gb)); | ||
| 333 | let executor = match self.executor { | 343 | let executor = match self.executor { |
| 334 | ExecutorKind::Builtin => "builtin", | 344 | ExecutorKind::Builtin => "builtin", |
| 335 | ExecutorKind::Podman => "podman", | 345 | ExecutorKind::Podman => "podman", |
| @@ -399,6 +409,10 @@ impl RunnerConfig { | |||
| 399 | .as_u64() | 409 | .as_u64() |
| 400 | .map(|v| self.limits.image_max_gb = v) | 410 | .map(|v| self.limits.image_max_gb = v) |
| 401 | .is_some(), | 411 | .is_some(), |
| 412 | + "limits.job_disk_gb" => value | ||
| 413 | + .as_u64() | ||
| 414 | + .map(|v| self.limits.job_disk_gb = v) | ||
| 415 | + .is_some(), | ||
| 402 | "images.keep_days" => value | 416 | "images.keep_days" => value |
| 403 | .as_u64() | 417 | .as_u64() |
| 404 | .and_then(|v| u32::try_from(v).ok()) | 418 | .and_then(|v| u32::try_from(v).ok()) |
crates/forge-runner/src/disk.rsadded+64 -0
| @@ -0,0 +1,64 @@ | |||
| 1 | +//! The disk cap of a builtin job (`limits.job_disk_gb`). | ||
| 2 | +//! | ||
| 3 | +//! A rootless runner has no quotas, so the runner measures what the job wrote every few seconds | ||
| 4 | +//! and stops it once that passes the cap. A job can overshoot by what it writes between two | ||
| 5 | +//! checks. In subuid mode a dir the job made unreadable to the runner is not counted. | ||
| 6 | + | ||
| 7 | +use std::collections::HashSet; | ||
| 8 | +use std::fs; | ||
| 9 | +use std::os::unix::fs::MetadataExt; | ||
| 10 | +use std::path::PathBuf; | ||
| 11 | +use std::sync::Arc; | ||
| 12 | +use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 13 | +use std::time::{Duration, Instant}; | ||
| 14 | + | ||
| 15 | +use tokio_util::sync::CancellationToken; | ||
| 16 | + | ||
| 17 | +/// How often the job's disk use is measured, at most. A measurement that takes long (a huge tree) | ||
| 18 | +/// spaces the next one out to four times its own length, so the walk stays a small share of the | ||
| 19 | +/// runner's time. | ||
| 20 | +const INTERVAL: Duration = Duration::from_secs(2); | ||
| 21 | + | ||
| 22 | +/// The bytes allocated under `roots`. Symlinks are not followed, and a file with several hard | ||
| 23 | +/// links counts once. Entries that can't be read are skipped. | ||
| 24 | +pub fn usage(roots: &[PathBuf]) -> u64 { | ||
| 25 | + let mut seen = HashSet::new(); | ||
| 26 | + let mut total = 0u64; | ||
| 27 | + let mut stack: Vec<PathBuf> = roots.to_vec(); | ||
| 28 | + while let Some(path) = stack.pop() { | ||
| 29 | + let Ok(meta) = fs::symlink_metadata(&path) else { | ||
| 30 | + continue; | ||
| 31 | + }; | ||
| 32 | + if meta.nlink() > 1 && !meta.is_dir() && !seen.insert((meta.dev(), meta.ino())) { | ||
| 33 | + continue; | ||
| 34 | + } | ||
| 35 | + total = total.saturating_add(meta.blocks().saturating_mul(512)); | ||
| 36 | + if meta.is_dir() | ||
| 37 | + && let Ok(entries) = fs::read_dir(&path) | ||
| 38 | + { | ||
| 39 | + stack.extend(entries.flatten().map(|entry| entry.path())); | ||
| 40 | + } | ||
| 41 | + } | ||
| 42 | + total | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// Measures `roots` about every [`INTERVAL`] until it passes `cap` bytes, then sets `over` and cancels | ||
| 46 | +/// `job`. Runs until it fires or is aborted. | ||
| 47 | +pub async fn watch(roots: Vec<PathBuf>, cap: u64, job: CancellationToken, over: Arc<AtomicBool>) { | ||
| 48 | + let roots = Arc::new(roots); | ||
| 49 | + let mut pause = INTERVAL; | ||
| 50 | + loop { | ||
| 51 | + tokio::time::sleep(pause).await; | ||
| 52 | + let measured = Arc::clone(&roots); | ||
| 53 | + let started = Instant::now(); | ||
| 54 | + let Ok(used) = tokio::task::spawn_blocking(move || usage(&measured)).await else { | ||
| 55 | + return; | ||
| 56 | + }; | ||
| 57 | + pause = INTERVAL.max(started.elapsed() * 4); | ||
| 58 | + if used > cap { | ||
| 59 | + over.store(true, Ordering::SeqCst); | ||
| 60 | + job.cancel(); | ||
| 61 | + return; | ||
| 62 | + } | ||
| 63 | + } | ||
| 64 | +} | ||
crates/forge-runner/src/executor.rsmodified+158 -3
| @@ -15,6 +15,8 @@ use std::fs; | |||
| 15 | use std::future::Future; | 15 | use std::future::Future; |
| 16 | use std::path::{Path, PathBuf}; | 16 | use std::path::{Path, PathBuf}; |
| 17 | use std::pin::Pin; | 17 | use std::pin::Pin; |
| 18 | +use std::sync::Arc; | ||
| 19 | +use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 18 | use std::process::{ExitStatus, Stdio}; | 20 | use std::process::{ExitStatus, Stdio}; |
| 19 | use std::time::Duration; | 21 | use std::time::Duration; |
| 20 | 22 | ||
| @@ -647,6 +649,7 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 647 | memory_budget, | 649 | memory_budget, |
| 648 | } = req; | 650 | } = req; |
| 649 | let limits = self.limits.for_builtin_job(job.memory_bytes, memory_budget); | 651 | let limits = self.limits.for_builtin_job(job.memory_bytes, memory_budget); |
| 652 | + let disk_gb = limits.job_disk_gb; | ||
| 650 | if let Err(e) = validate_job_id(&job.job_id) { | 653 | if let Err(e) = validate_job_id(&job.job_id) { |
| 651 | return error_result(e.to_string()); | 654 | return error_result(e.to_string()); |
| 652 | } | 655 | } |
| @@ -672,10 +675,27 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 672 | .await; | 675 | .await; |
| 673 | 676 | ||
| 674 | let job_dir = self.jobs_dir.join(&job.job_id); | 677 | let job_dir = self.jobs_dir.join(&job.job_id); |
| 675 | - // A leftover from an earlier run of this job id would hold stale overlay state. | 678 | + // A leftover from an earlier run of this job id would hold stale overlay state, and maybe |
| 679 | + // the pid of a pasta that outlived its helper. | ||
| 680 | + crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir)); | ||
| 676 | if let Err(e) = remove_job_dir(&self.idmap, &self.helper, &job_dir).await { | 681 | if let Err(e) = remove_job_dir(&self.idmap, &self.helper, &job_dir).await { |
| 677 | tracing::warn!("cannot remove stale {}: {e}", job_dir.display()); | 682 | tracing::warn!("cannot remove stale {}: {e}", job_dir.display()); |
| 678 | } | 683 | } |
| 684 | + let pasta = if job.network { | ||
| 685 | + let pasta = crate::sandbox::net::find_pasta(); | ||
| 686 | + if pasta.is_none() { | ||
| 687 | + let _ = logs | ||
| 688 | + .send( | ||
| 689 | + b"runner: pasta is not installed, so this job shares the runner's network; \ | ||
| 690 | + install passt to isolate it\n" | ||
| 691 | + .to_vec(), | ||
| 692 | + ) | ||
| 693 | + .await; | ||
| 694 | + } | ||
| 695 | + pasta | ||
| 696 | + } else { | ||
| 697 | + None | ||
| 698 | + }; | ||
| 679 | let request = SandboxRequest { | 699 | let request = SandboxRequest { |
| 680 | job_id: job.job_id.clone(), | 700 | job_id: job.job_id.clone(), |
| 681 | rootfs: image.rootfs, | 701 | rootfs: image.rootfs, |
| @@ -685,6 +705,7 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 685 | env, | 705 | env, |
| 686 | run: job.run.clone(), | 706 | run: job.run.clone(), |
| 687 | network: job.network, | 707 | network: job.network, |
| 708 | + pasta, | ||
| 688 | limits, | 709 | limits, |
| 689 | idmap: self.idmap.clone(), | 710 | idmap: self.idmap.clone(), |
| 690 | }; | 711 | }; |
| @@ -716,6 +737,25 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 716 | } | 737 | } |
| 717 | drop(json); | 738 | drop(json); |
| 718 | 739 | ||
| 740 | + // The disk cap stops the job through its own token, so a stop for disk can be told apart | ||
| 741 | + // from a cancel. | ||
| 742 | + let job_cancel = cancel.child_token(); | ||
| 743 | + let over_disk = Arc::new(AtomicBool::new(false)); | ||
| 744 | + let disk_cap = disk_gb.saturating_mul(1 << 30); | ||
| 745 | + let watcher = (disk_cap > 0).then(|| { | ||
| 746 | + let job_dir = self.jobs_dir.join(&job.job_id); | ||
| 747 | + let roots = vec![ | ||
| 748 | + workspace.to_owned(), | ||
| 749 | + job_dir.join("tmp"), | ||
| 750 | + job_dir.join("overlay/upper"), | ||
| 751 | + ]; | ||
| 752 | + tokio::spawn(crate::disk::watch( | ||
| 753 | + roots, | ||
| 754 | + disk_cap, | ||
| 755 | + job_cancel.clone(), | ||
| 756 | + Arc::clone(&over_disk), | ||
| 757 | + )) | ||
| 758 | + }); | ||
| 719 | let Supervised { | 759 | let Supervised { |
| 720 | cancelled, | 760 | cancelled, |
| 721 | status, | 761 | status, |
| @@ -724,7 +764,7 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 724 | } = supervise( | 764 | } = supervise( |
| 725 | child, | 765 | child, |
| 726 | logs, | 766 | logs, |
| 727 | - cancel, | 767 | + job_cancel, |
| 728 | Stopper::Helper { pid }, | 768 | Stopper::Helper { pid }, |
| 729 | Some(JobCleanup { | 769 | Some(JobCleanup { |
| 730 | helper_pid: pid, | 770 | helper_pid: pid, |
| @@ -735,9 +775,22 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 735 | }), | 775 | }), |
| 736 | ) | 776 | ) |
| 737 | .await; | 777 | .await; |
| 778 | + if let Some(watcher) = watcher { | ||
| 779 | + watcher.abort(); | ||
| 780 | + } | ||
| 738 | if let Some(events) = oom { | 781 | if let Some(events) = oom { |
| 739 | oom_sink.record(events); | 782 | oom_sink.record(events); |
| 740 | } | 783 | } |
| 784 | + if over_disk.load(Ordering::SeqCst) && !cancel.is_cancelled() { | ||
| 785 | + return ExecResult { | ||
| 786 | + outcome: Outcome::Failure, | ||
| 787 | + exit_code: None, | ||
| 788 | + message: Some(format!( | ||
| 789 | + "job was stopped: it filled more than {disk_gb} GB of disk (workspace, /tmp \ | ||
| 790 | + and writes over the image)" | ||
| 791 | + )), | ||
| 792 | + }; | ||
| 793 | + } | ||
| 741 | if cancelled { | 794 | if cancelled { |
| 742 | return cancelled_result(); | 795 | return cancelled_result(); |
| 743 | } | 796 | } |
| @@ -808,7 +861,7 @@ struct JobCleanup { | |||
| 808 | 861 | ||
| 809 | /// Cleans up after a job's helper has exited, whatever the reason. A helper killed with SIGKILL | 862 | /// Cleans up after a job's helper has exited, whatever the reason. A helper killed with SIGKILL |
| 810 | /// cannot delete its container, so the container could otherwise keep running. This kills what is | 863 | /// cannot delete its container, so the container could otherwise keep running. This kills what is |
| 811 | -/// left in the job cgroup, removes the cgroup, and removes the job dir. | 864 | +/// left in the job cgroup, removes the cgroup, stops a leftover pasta, and removes the job dir. |
| 812 | async fn reap_job(job: &JobCleanup) { | 865 | async fn reap_job(job: &JobCleanup) { |
| 813 | if let Ok(relative) = job_cgroup_path(&job.job_id, job.helper_pid) { | 866 | if let Ok(relative) = job_cgroup_path(&job.job_id, job.helper_pid) { |
| 814 | let dir = Path::new(CGROUP_ROOT).join(relative.strip_prefix("/").unwrap_or(&relative)); | 867 | let dir = Path::new(CGROUP_ROOT).join(relative.strip_prefix("/").unwrap_or(&relative)); |
| @@ -823,11 +876,97 @@ async fn reap_job(job: &JobCleanup) { | |||
| 823 | } | 876 | } |
| 824 | } | 877 | } |
| 825 | } | 878 | } |
| 879 | + // A helper killed with SIGKILL could not stop its pasta either. | ||
| 880 | + crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job.job_dir)); | ||
| 826 | if let Err(e) = remove_job_dir(&job.idmap, &job.helper, &job.job_dir).await { | 881 | if let Err(e) = remove_job_dir(&job.idmap, &job.helper, &job.job_dir).await { |
| 827 | tracing::warn!("cannot remove {}: {e}", job.job_dir.display()); | 882 | tracing::warn!("cannot remove {}: {e}", job.job_dir.display()); |
| 828 | } | 883 | } |
| 829 | } | 884 | } |
| 830 | 885 | ||
| 886 | +/// Cleans up after an earlier run of the runner that did not get to (a crash, a SIGKILL, a power | ||
| 887 | +/// cut): for every leftover `work_dir/jobs/<id>` it stops a pasta, kills the job's cgroups and | ||
| 888 | +/// removes the dir, and it removes leftover workspaces `work_dir/<id>`. Call it at startup, | ||
| 889 | +/// before any job runs. Only job ids found in this runner's own dirs are touched, so another | ||
| 890 | +/// runner's jobs in a shared cgroup are left alone. | ||
| 891 | +pub async fn sweep_leftovers(work_dir: &Path, map: &IdMap, helper: &Path) { | ||
| 892 | + let (work_dir, map, helper) = (work_dir.to_owned(), map.clone(), helper.to_owned()); | ||
| 893 | + let swept = tokio::task::spawn_blocking(move || sweep_blocking(&work_dir, &map, &helper)).await; | ||
| 894 | + if let Err(e) = swept { | ||
| 895 | + tracing::warn!("cannot sweep leftover jobs: {e}"); | ||
| 896 | + } | ||
| 897 | +} | ||
| 898 | + | ||
| 899 | +fn sweep_blocking(work_dir: &Path, map: &IdMap, helper: &Path) { | ||
| 900 | + let jobs_dir = work_dir.join("jobs"); | ||
| 901 | + let cgroup_bases: Vec<PathBuf> = crate::sandbox::helper::job_cgroup_base() | ||
| 902 | + .map(|base| { | ||
| 903 | + let base = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base)); | ||
| 904 | + vec![base.join(crate::sandbox::helper::BOX_NAME), base] | ||
| 905 | + }) | ||
| 906 | + .unwrap_or_default(); | ||
| 907 | + for job_id in job_ids_in(&jobs_dir) { | ||
| 908 | + let job_dir = jobs_dir.join(&job_id); | ||
| 909 | + tracing::info!("removing leftover job {job_id}"); | ||
| 910 | + crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir)); | ||
| 911 | + let prefix = format!("forge-job-{job_id}-"); | ||
| 912 | + for base in &cgroup_bases { | ||
| 913 | + let Ok(entries) = fs::read_dir(base) else { | ||
| 914 | + continue; | ||
| 915 | + }; | ||
| 916 | + for entry in entries.flatten() { | ||
| 917 | + let name = entry.file_name(); | ||
| 918 | + let Some(pid) = name.to_str().and_then(|n| n.strip_prefix(&prefix)) else { | ||
| 919 | + continue; | ||
| 920 | + }; | ||
| 921 | + if pid.parse::<u32>().is_err() { | ||
| 922 | + continue; | ||
| 923 | + } | ||
| 924 | + let dir = entry.path(); | ||
| 925 | + kill_cgroup(&dir); | ||
| 926 | + for _ in 0..REAP_POLLS { | ||
| 927 | + if fs::remove_dir(&dir).is_ok() || !dir.exists() { | ||
| 928 | + break; | ||
| 929 | + } | ||
| 930 | + std::thread::sleep(REAP_POLL); | ||
| 931 | + } | ||
| 932 | + } | ||
| 933 | + } | ||
| 934 | + if let Err(e) = remove_tree(map, &job_dir, helper) { | ||
| 935 | + tracing::warn!("cannot remove {}: {e}", job_dir.display()); | ||
| 936 | + } | ||
| 937 | + } | ||
| 938 | + // `work_dir` may be shared with other files (an operator could point it at a home dir), so | ||
| 939 | + // only names shaped like the forge's job ids (ULIDs) count as workspaces. | ||
| 940 | + for job_id in job_ids_in(work_dir).into_iter().filter(|id| is_ulid(id)) { | ||
| 941 | + let workspace = work_dir.join(&job_id); | ||
| 942 | + tracing::info!("removing leftover workspace {job_id}"); | ||
| 943 | + if let Err(e) = remove_tree(map, &workspace, helper) { | ||
| 944 | + tracing::warn!("cannot remove {}: {e}", workspace.display()); | ||
| 945 | + } | ||
| 946 | + } | ||
| 947 | +} | ||
| 948 | + | ||
| 949 | +/// 26 Crockford base32 digits, the shape of every job id the forge hands out. | ||
| 950 | +fn is_ulid(name: &str) -> bool { | ||
| 951 | + name.len() == 26 | ||
| 952 | + && name | ||
| 953 | + .bytes() | ||
| 954 | + .all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b))) | ||
| 955 | +} | ||
| 956 | + | ||
| 957 | +/// The names of the dirs in `dir` that are valid job ids. Symlinks are skipped. | ||
| 958 | +fn job_ids_in(dir: &Path) -> Vec<String> { | ||
| 959 | + let Ok(entries) = fs::read_dir(dir) else { | ||
| 960 | + return Vec::new(); | ||
| 961 | + }; | ||
| 962 | + entries | ||
| 963 | + .flatten() | ||
| 964 | + .filter(|entry| entry.file_type().is_ok_and(|t| t.is_dir())) | ||
| 965 | + .filter_map(|entry| entry.file_name().into_string().ok()) | ||
| 966 | + .filter(|name| validate_job_id(name).is_ok()) | ||
| 967 | + .collect() | ||
| 968 | +} | ||
| 969 | + | ||
| 831 | /// Removes a job dir under `map`. Its files may be owned by subordinate ids, so this goes through | 970 | /// Removes a job dir under `map`. Its files may be owned by subordinate ids, so this goes through |
| 832 | /// the helper in subuid mode (see [`remove_tree`]). The removal blocks, so it runs off the async | 971 | /// the helper in subuid mode (see [`remove_tree`]). The removal blocks, so it runs off the async |
| 833 | /// runtime. | 972 | /// runtime. |
| @@ -849,6 +988,22 @@ mod tests { | |||
| 849 | use super::*; | 988 | use super::*; |
| 850 | use std::collections::BTreeMap; | 989 | use std::collections::BTreeMap; |
| 851 | 990 | ||
| 991 | + #[test] | ||
| 992 | + fn sweep_removes_only_leftover_jobs_and_ulid_workspaces() { | ||
| 993 | + let dir = tempfile::tempdir().unwrap(); | ||
| 994 | + let work = dir.path(); | ||
| 995 | + for d in ["jobs/job_01/overlay", "01JD6Z8Q4XW3N5R7T9V2B4C6E8/src", "oci", "notes", "check-7"] { | ||
| 996 | + fs::create_dir_all(work.join(d)).unwrap(); | ||
| 997 | + } | ||
| 998 | + fs::create_dir_all(work.join(".cache")).unwrap(); | ||
| 999 | + sweep_blocking(work, &IdMap::single(), Path::new("/nonexistent")); | ||
| 1000 | + assert!(!work.join("jobs/job_01").exists()); | ||
| 1001 | + assert!(!work.join("01JD6Z8Q4XW3N5R7T9V2B4C6E8").exists()); | ||
| 1002 | + for kept in ["jobs", "oci", "notes", "check-7", ".cache"] { | ||
| 1003 | + assert!(work.join(kept).exists(), "{kept} was removed"); | ||
| 1004 | + } | ||
| 1005 | + } | ||
| 1006 | + | ||
| 852 | const SECRET: &str = "hunter2-SUPER-SECRET-value"; | 1007 | const SECRET: &str = "hunter2-SUPER-SECRET-value"; |
| 853 | 1008 | ||
| 854 | pub(crate) fn fixture_job(run: &str) -> JobAssignment { | 1009 | pub(crate) fn fixture_job(run: &str) -> JobAssignment { |
crates/forge-runner/src/lib.rsmodified+1 -0
| @@ -10,6 +10,7 @@ pub mod check; | |||
| 10 | pub mod cli; | 10 | pub mod cli; |
| 11 | pub mod client; | 11 | pub mod client; |
| 12 | pub mod config; | 12 | pub mod config; |
| 13 | +pub mod disk; | ||
| 13 | pub mod executor; | 14 | pub mod executor; |
| 14 | pub mod limiter; | 15 | pub mod limiter; |
| 15 | pub mod logs; | 16 | pub mod logs; |
crates/forge-runner/src/sandbox/helper.rsmodified+21 -4
| @@ -9,6 +9,8 @@ | |||
| 9 | //! 1. Enter a user namespace with the request's [`IdMap`](super::idmap::IdMap): root is the | 9 | //! 1. Enter a user namespace with the request's [`IdMap`](super::idmap::IdMap): root is the |
| 10 | //! runner's uid, and in subuid mode container ids `1..=n` are the subordinate range. The | 10 | //! runner's uid, and in subuid mode container ids `1..=n` are the subordinate range. The |
| 11 | //! overlay mount needs CAP_SYS_ADMIN in a user namespace that owns the mount namespace. | 11 | //! overlay mount needs CAP_SYS_ADMIN in a user namespace that owns the mount namespace. |
| 12 | +//! A job with network gets its own network namespace too, connected by pasta (see | ||
| 13 | +//! [`net`](super::net)). | ||
| 12 | //! 2. An overlay mount of the image rootfs. If that fails, the rootfs is copied instead. | 14 | //! 2. An overlay mount of the image rootfs. If that fails, the rootfs is copied instead. |
| 13 | //! 3. The OCI spec is written to `bundle/config.json` (0600) and libcontainer builds the | 15 | //! 3. The OCI spec is written to `bundle/config.json` (0600) and libcontainer builds the |
| 14 | //! container from it. The file is deleted right after `build()`, since libcontainer has | 16 | //! container from it. The file is deleted right after `build()`, since libcontainer has |
| @@ -44,6 +46,7 @@ use signal_hook::low_level::pipe; | |||
| 44 | 46 | ||
| 45 | use super::exec::FilteredExecutor; | 47 | use super::exec::FilteredExecutor; |
| 46 | use super::idmap::enter_mapped_userns; | 48 | use super::idmap::enter_mapped_userns; |
| 49 | +use super::net; | ||
| 47 | use super::seccomp::build_filter; | 50 | use super::seccomp::build_filter; |
| 48 | use super::spec::{HOSTNAME, build_spec}; | 51 | use super::spec::{HOSTNAME, build_spec}; |
| 49 | use super::{SandboxError, SandboxRequest}; | 52 | use super::{SandboxError, SandboxRequest}; |
| @@ -110,11 +113,21 @@ fn run() -> Result<i32, SandboxError> { | |||
| 110 | prepare_dirs(&layout)?; | 113 | prepare_dirs(&layout)?; |
| 111 | write_etc_files(&layout)?; | 114 | write_etc_files(&layout)?; |
| 112 | 115 | ||
| 116 | + // The job's own network, when it asked for one and pasta is installed. See `net`. | ||
| 117 | + let pasta_pid = net::pid_file(&layout.job_dir); | ||
| 118 | + let pending_net = match (&req.pasta, req.network) { | ||
| 119 | + (Some(pasta), true) => Some(net::prepare(pasta, &pasta_pid)?), | ||
| 120 | + _ => None, | ||
| 121 | + }; | ||
| 113 | enter_mapped_userns(&req.idmap).map_err(|e| SandboxError::Setup(e.to_string()))?; | 122 | enter_mapped_userns(&req.idmap).map_err(|e| SandboxError::Setup(e.to_string()))?; |
| 114 | - let rootfs = mount_rootfs(&req, &layout)?; | 123 | + let result = match pending_net { |
| 115 | - | 124 | + Some(pending) => pending.attach(), |
| 125 | + None => Ok(()), | ||
| 126 | + } | ||
| 127 | + .and_then(|()| mount_rootfs(&req, &layout)) | ||
| 116 | // Clean up on failure too: the state dir holds the job env. | 128 | // Clean up on failure too: the state dir holds the job env. |
| 117 | - let result = run_job(&req, &layout, &rootfs, &signals); | 129 | + .and_then(|rootfs| run_job(&req, &layout, &rootfs, &signals)); |
| 130 | + net::stop_pasta(&pasta_pid); | ||
| 118 | // The container is gone, so nothing writes to the workspace now. In subuid mode the job may | 131 | // The container is gone, so nothing writes to the workspace now. In subuid mode the job may |
| 119 | // have left files owned by subordinate ids, which the runner can't remove, so they go back | 132 | // have left files owned by subordinate ids, which the runner can't remove, so they go back |
| 120 | // to the runner. | 133 | // to the runner. |
| @@ -247,7 +260,11 @@ fn write_etc_files(layout: &Layout) -> Result<(), SandboxError> { | |||
| 247 | let hostname = layout.etc.join("hostname"); | 260 | let hostname = layout.etc.join("hostname"); |
| 248 | fs::write(&hostname, format!("{HOSTNAME}\n")) | 261 | fs::write(&hostname, format!("{HOSTNAME}\n")) |
| 249 | .map_err(SandboxError::io("cannot write hostname"))?; | 262 | .map_err(SandboxError::io("cannot write hostname"))?; |
| 250 | - for file in [&hosts, &hostname] { | 263 | + // Only bind mounted when the job has its own network (see `spec`). |
| 264 | + let resolv = layout.etc.join("resolv.conf"); | ||
| 265 | + fs::write(&resolv, format!("nameserver {}\n", net::DNS_ADDR)) | ||
| 266 | + .map_err(SandboxError::io("cannot write resolv.conf"))?; | ||
| 267 | + for file in [&hosts, &hostname, &resolv] { | ||
| 251 | fs::set_permissions(file, fs::Permissions::from_mode(0o644)) | 268 | fs::set_permissions(file, fs::Permissions::from_mode(0o644)) |
| 252 | .map_err(SandboxError::io(format!("cannot chmod {}", file.display())))?; | 269 | .map_err(SandboxError::io(format!("cannot chmod {}", file.display())))?; |
| 253 | } | 270 | } |
crates/forge-runner/src/sandbox/mod.rsmodified+8 -1
| @@ -8,6 +8,7 @@ | |||
| 8 | pub mod exec; | 8 | pub mod exec; |
| 9 | pub mod helper; | 9 | pub mod helper; |
| 10 | pub mod idmap; | 10 | pub mod idmap; |
| 11 | +pub mod net; | ||
| 11 | pub mod seccomp; | 12 | pub mod seccomp; |
| 12 | pub mod spec; | 13 | pub mod spec; |
| 13 | 14 | ||
| @@ -40,8 +41,14 @@ pub struct SandboxRequest { | |||
| 40 | pub env: Vec<(String, String)>, | 41 | pub env: Vec<(String, String)>, |
| 41 | /// The job's `run` script, executed as `sh -eu -c <run>`. | 42 | /// The job's `run` script, executed as `sh -eu -c <run>`. |
| 42 | pub run: String, | 43 | pub run: String, |
| 43 | - /// `false` gives the job an empty network namespace. `true` shares the host's. | 44 | + /// `false` gives the job an empty network namespace. `true` gives it the internet: through |
| 45 | + /// `pasta` in its own namespace when `pasta` is set (see `helper::isolate_network`), or the | ||
| 46 | + /// host's namespace when it is not. | ||
| 44 | pub network: bool, | 47 | pub network: bool, |
| 48 | + /// The `pasta` binary (from the passt package) that connects an isolated job network to the | ||
| 49 | + /// internet. `None` when it is not installed. | ||
| 50 | + #[serde(default)] | ||
| 51 | + pub pasta: Option<PathBuf>, | ||
| 45 | pub limits: Limits, | 52 | pub limits: Limits, |
| 46 | /// The id mapping the helper enters before anything else. Missing means single mode. | 53 | /// The id mapping the helper enters before anything else. Missing means single mode. |
| 47 | #[serde(default)] | 54 | #[serde(default)] |
crates/forge-runner/src/sandbox/net.rsadded+264 -0
| @@ -0,0 +1,264 @@ | |||
| 1 | +//! The network of a builtin job that asked for one. | ||
| 2 | +//! | ||
| 3 | +//! The job gets its own network namespace, and `pasta` (from the passt package) connects it to | ||
| 4 | +//! the internet through the runner's own sockets. Inside, the job sees `192.0.2.2/24` with the | ||
| 5 | +//! gateway at `192.0.2.1` and DNS at `192.0.2.3`. The host's loopback is not mapped, and | ||
| 6 | +//! blackhole routes send private, link-local (cloud metadata) and multicast ranges nowhere, so | ||
| 7 | +//! a job cannot reach the runner's own services or its LAN. There is no IPv6. | ||
| 8 | +//! | ||
| 9 | +//! pasta has to start in the host's namespaces and attach to the helper's new ones, so it can't | ||
| 10 | +//! be a child of the helper after the unshare. A `__sandbox-net` helper of this same binary is | ||
| 11 | +//! started before it, and blocks on stdin until the helper has unshared. It then runs pasta, | ||
| 12 | +//! which forks into the background once the namespace is set up and exits 0. pasta writes its | ||
| 13 | +//! pid to a file, and [`stop_pasta`] ends it after the job. | ||
| 14 | + | ||
| 15 | +use std::ffi::OsString; | ||
| 16 | +use std::fs; | ||
| 17 | +use std::io::{self, Read, Write}; | ||
| 18 | +use std::path::{Path, PathBuf}; | ||
| 19 | +use std::process::{Child, Command, Stdio}; | ||
| 20 | + | ||
| 21 | +use nix::sched::{CloneFlags, unshare}; | ||
| 22 | +use nix::sys::signal::{Signal, kill}; | ||
| 23 | +use nix::unistd::Pid; | ||
| 24 | + | ||
| 25 | +use super::SandboxError; | ||
| 26 | + | ||
| 27 | +/// The hidden subcommand that waits for the go byte and starts pasta. | ||
| 28 | +pub const NET_HELPER_CMD: &str = "__sandbox-net"; | ||
| 29 | +/// The job's resolver, which pasta forwards to the host's. | ||
| 30 | +pub const DNS_ADDR: &str = "192.0.2.3"; | ||
| 31 | +/// Where pasta is looked for, in order. | ||
| 32 | +const PASTA_PATHS: [&str; 3] = ["/usr/bin/pasta", "/usr/local/bin/pasta", "/bin/pasta"]; | ||
| 33 | +const IP_DIRS: [&str; 4] = ["/usr/sbin", "/usr/bin", "/sbin", "/bin"]; | ||
| 34 | +/// Ranges the job must not reach: "this network", private, carrier-grade NAT, link-local (cloud | ||
| 35 | +/// metadata), benchmarking, multicast and reserved. | ||
| 36 | +const BLOCKED: [&str; 9] = [ | ||
| 37 | + "0.0.0.0/8", | ||
| 38 | + "10.0.0.0/8", | ||
| 39 | + "100.64.0.0/10", | ||
| 40 | + "169.254.0.0/16", | ||
| 41 | + "172.16.0.0/12", | ||
| 42 | + "192.168.0.0/16", | ||
| 43 | + "198.18.0.0/15", | ||
| 44 | + "224.0.0.0/4", | ||
| 45 | + "240.0.0.0/4", | ||
| 46 | +]; | ||
| 47 | + | ||
| 48 | +/// Where pasta writes its pid: in the job dir itself, since libcontainer removes `state` with the | ||
| 49 | +/// container. | ||
| 50 | +pub fn pid_file(job_dir: &Path) -> PathBuf { | ||
| 51 | + job_dir.join("pasta.pid") | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// The installed pasta binary, if any. | ||
| 55 | +pub fn find_pasta() -> Option<PathBuf> { | ||
| 56 | + PASTA_PATHS.iter().map(PathBuf::from).find(|p| p.is_file()) | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// A started `__sandbox-net` helper that is waiting for its go byte. | ||
| 60 | +pub struct PendingNet { | ||
| 61 | + child: Child, | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// Starts the `__sandbox-net` helper. Call it before entering the user namespace, then call | ||
| 65 | +/// [`PendingNet::attach`] right after. | ||
| 66 | +pub fn prepare(pasta: &Path, pid_file: &Path) -> Result<PendingNet, SandboxError> { | ||
| 67 | + let exe = std::env::current_exe().map_err(SandboxError::io("cannot find the runner binary"))?; | ||
| 68 | + let child = Command::new(exe) | ||
| 69 | + .arg(NET_HELPER_CMD) | ||
| 70 | + .arg(pasta) | ||
| 71 | + .arg(std::process::id().to_string()) | ||
| 72 | + .arg(pid_file) | ||
| 73 | + .stdin(Stdio::piped()) | ||
| 74 | + .stdout(Stdio::null()) | ||
| 75 | + .stderr(Stdio::piped()) | ||
| 76 | + .spawn() | ||
| 77 | + .map_err(SandboxError::io("cannot start the network helper"))?; | ||
| 78 | + Ok(PendingNet { child }) | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +impl PendingNet { | ||
| 82 | + /// Moves this process into a new network namespace, has pasta connect it, and sets up the | ||
| 83 | + /// routes. Must run inside the job's user namespace, which owns the new network namespace. | ||
| 84 | + pub fn attach(mut self) -> Result<(), SandboxError> { | ||
| 85 | + let Some(mut go) = self.child.stdin.take() else { | ||
| 86 | + self.stop(); | ||
| 87 | + return Err(SandboxError::Setup( | ||
| 88 | + "no stdin for the network helper".into(), | ||
| 89 | + )); | ||
| 90 | + }; | ||
| 91 | + let signalled = unshare(CloneFlags::CLONE_NEWNET) | ||
| 92 | + .map_err(|e| SandboxError::Setup(format!("cannot create a network namespace: {e}"))) | ||
| 93 | + .and_then(|()| { | ||
| 94 | + go.write_all(b"1") | ||
| 95 | + .map_err(SandboxError::io("cannot signal the network helper")) | ||
| 96 | + }); | ||
| 97 | + // Closing stdin ends the helper's wait if the byte never landed. | ||
| 98 | + drop(go); | ||
| 99 | + if let Err(e) = signalled { | ||
| 100 | + self.stop(); | ||
| 101 | + return Err(e); | ||
| 102 | + } | ||
| 103 | + let output = self | ||
| 104 | + .child | ||
| 105 | + .wait_with_output() | ||
| 106 | + .map_err(SandboxError::io("waiting for the network helper"))?; | ||
| 107 | + if !output.status.success() { | ||
| 108 | + let stderr = String::from_utf8_lossy(&output.stderr); | ||
| 109 | + let detail = match stderr.trim() { | ||
| 110 | + "" => output.status.to_string(), | ||
| 111 | + text => text.to_owned(), | ||
| 112 | + }; | ||
| 113 | + return Err(SandboxError::Setup(format!("cannot start pasta: {detail}"))); | ||
| 114 | + } | ||
| 115 | + configure_routes() | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + fn stop(&mut self) { | ||
| 119 | + let _ = self.child.kill(); | ||
| 120 | + let _ = self.child.wait(); | ||
| 121 | + } | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// Brings loopback up and blackholes [`BLOCKED`]. pasta has already added the address and the | ||
| 125 | +/// default route. | ||
| 126 | +fn configure_routes() -> Result<(), SandboxError> { | ||
| 127 | + let ip = IP_DIRS | ||
| 128 | + .iter() | ||
| 129 | + .map(|dir| Path::new(dir).join("ip")) | ||
| 130 | + .find(|p| p.is_file()) | ||
| 131 | + .ok_or_else(|| SandboxError::Setup("`ip` (iproute2) is not installed".into()))?; | ||
| 132 | + let mut script = String::from("link set lo up\n"); | ||
| 133 | + for range in BLOCKED { | ||
| 134 | + script.push_str(&format!("route add blackhole {range}\n")); | ||
| 135 | + } | ||
| 136 | + let mut child = Command::new(ip) | ||
| 137 | + .args(["-batch", "-"]) | ||
| 138 | + .stdin(Stdio::piped()) | ||
| 139 | + .stdout(Stdio::null()) | ||
| 140 | + .stderr(Stdio::piped()) | ||
| 141 | + .spawn() | ||
| 142 | + .map_err(SandboxError::io("cannot run ip"))?; | ||
| 143 | + if let Some(mut stdin) = child.stdin.take() { | ||
| 144 | + stdin | ||
| 145 | + .write_all(script.as_bytes()) | ||
| 146 | + .map_err(SandboxError::io("cannot write to ip"))?; | ||
| 147 | + } | ||
| 148 | + let output = child | ||
| 149 | + .wait_with_output() | ||
| 150 | + .map_err(SandboxError::io("waiting for ip"))?; | ||
| 151 | + if output.status.success() { | ||
| 152 | + Ok(()) | ||
| 153 | + } else { | ||
| 154 | + Err(SandboxError::Setup(format!( | ||
| 155 | + "cannot set up the job's routes: {}", | ||
| 156 | + String::from_utf8_lossy(&output.stderr).trim() | ||
| 157 | + ))) | ||
| 158 | + } | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +/// Ends the pasta whose pid is in `pid_file`, if it is still running. The pid is only signalled | ||
| 162 | +/// when it still names a pasta process, so a reused pid is left alone. | ||
| 163 | +pub fn stop_pasta(pid_file: &Path) { | ||
| 164 | + let Ok(text) = fs::read_to_string(pid_file) else { | ||
| 165 | + return; | ||
| 166 | + }; | ||
| 167 | + let Ok(pid) = text.trim().parse::<i32>() else { | ||
| 168 | + return; | ||
| 169 | + }; | ||
| 170 | + if pid <= 1 { | ||
| 171 | + return; | ||
| 172 | + } | ||
| 173 | + let comm = fs::read_to_string(format!("/proc/{pid}/comm")).unwrap_or_default(); | ||
| 174 | + if matches!(comm.trim(), "pasta" | "passt" | "pasta.avx2" | "passt.avx2") { | ||
| 175 | + let _ = kill(Pid::from_raw(pid), Signal::SIGTERM); | ||
| 176 | + } | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +/// `<exe> __sandbox-net <pasta> <parent> <pid_file>`, with the go byte on stdin. Exit 0 once | ||
| 180 | +/// pasta has connected the parent's network namespace, or 125 with a `forge-sandbox:` line. | ||
| 181 | +pub fn net_helper_main(args: &[OsString]) -> i32 { | ||
| 182 | + match net_helper(args) { | ||
| 183 | + Ok(()) => 0, | ||
| 184 | + Err(message) => { | ||
| 185 | + eprintln!("forge-sandbox: {message}"); | ||
| 186 | + 125 | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +fn net_helper(args: &[OsString]) -> Result<(), String> { | ||
| 192 | + let [pasta, parent, pid_file] = args else { | ||
| 193 | + return Err("usage: __sandbox-net <pasta> <parent> <pid_file>".into()); | ||
| 194 | + }; | ||
| 195 | + let parent: u32 = parent | ||
| 196 | + .to_str() | ||
| 197 | + .and_then(|s| s.parse().ok()) | ||
| 198 | + .filter(|&p| p > 1) | ||
| 199 | + .ok_or("parent must be a pid")?; | ||
| 200 | + let mut byte = [0u8; 1]; | ||
| 201 | + loop { | ||
| 202 | + match io::stdin().lock().read(&mut byte) { | ||
| 203 | + Ok(1) => break, | ||
| 204 | + Ok(_) => return Err("network setup was cancelled".into()), | ||
| 205 | + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, | ||
| 206 | + Err(e) => return Err(format!("cannot read from the parent: {e}")), | ||
| 207 | + } | ||
| 208 | + } | ||
| 209 | + let output = Command::new(pasta) | ||
| 210 | + .args(pasta_args(parent, Path::new(pid_file))) | ||
| 211 | + .stdin(Stdio::null()) | ||
| 212 | + .stdout(Stdio::null()) | ||
| 213 | + .stderr(Stdio::piped()) | ||
| 214 | + .output() | ||
| 215 | + .map_err(|e| format!("cannot run pasta: {e}"))?; | ||
| 216 | + if output.status.success() { | ||
| 217 | + Ok(()) | ||
| 218 | + } else { | ||
| 219 | + Err(format!( | ||
| 220 | + "pasta failed ({}): {}", | ||
| 221 | + output.status, | ||
| 222 | + String::from_utf8_lossy(&output.stderr).trim() | ||
| 223 | + )) | ||
| 224 | + } | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +/// No ports are forwarded in either direction, the gateway does not map to the host's loopback, | ||
| 228 | +/// and pasta does not watch the namespace (that needs a netns dir SELinux may deny), so it is | ||
| 229 | +/// stopped through its pid file. | ||
| 230 | +fn pasta_args(parent: u32, pid_file: &Path) -> Vec<OsString> { | ||
| 231 | + let mut args: Vec<OsString> = [ | ||
| 232 | + "-q", | ||
| 233 | + "--config-net", | ||
| 234 | + "-4", | ||
| 235 | + "-a", | ||
| 236 | + "192.0.2.2", | ||
| 237 | + "-n", | ||
| 238 | + "24", | ||
| 239 | + "-g", | ||
| 240 | + "192.0.2.1", | ||
| 241 | + "--no-map-gw", | ||
| 242 | + "--dns-forward", | ||
| 243 | + DNS_ADDR, | ||
| 244 | + "-t", | ||
| 245 | + "none", | ||
| 246 | + "-u", | ||
| 247 | + "none", | ||
| 248 | + "-T", | ||
| 249 | + "none", | ||
| 250 | + "-U", | ||
| 251 | + "none", | ||
| 252 | + "--no-netns-quit", | ||
| 253 | + "--pid", | ||
| 254 | + ] | ||
| 255 | + .into_iter() | ||
| 256 | + .map(OsString::from) | ||
| 257 | + .collect(); | ||
| 258 | + args.push(pid_file.into()); | ||
| 259 | + args.push("--userns".into()); | ||
| 260 | + args.push(format!("/proc/{parent}/ns/user").into()); | ||
| 261 | + args.push("--netns".into()); | ||
| 262 | + args.push(format!("/proc/{parent}/ns/net").into()); | ||
| 263 | + args | ||
| 264 | +} | ||
crates/forge-runner/src/sandbox/spec.rsmodified+19 -6
| @@ -377,12 +377,23 @@ fn build_mounts(req: &SandboxRequest) -> Result<Vec<Mount>, SandboxError> { | |||
| 377 | "/sys", | 377 | "/sys", |
| 378 | &["rbind", "nosuid", "noexec", "nodev", "ro"], | 378 | &["rbind", "nosuid", "noexec", "nodev", "ro"], |
| 379 | )?); | 379 | )?); |
| 380 | - mounts.push(mount( | 380 | + // An isolated network asks pasta's DNS forwarder; the host's resolver may be on its |
| 381 | - "/etc/resolv.conf", | 381 | + // loopback, which the job cannot reach. |
| 382 | - "bind", | 382 | + if req.pasta.is_some() { |
| 383 | - "/etc/resolv.conf", | 383 | + mounts.push(mount_path( |
| 384 | - &["bind", "ro"], | 384 | + "/etc/resolv.conf", |
| 385 | - )?); | 385 | + "bind", |
| 386 | + &req.job_dir.join("etc/resolv.conf"), | ||
| 387 | + &["bind", "ro"], | ||
| 388 | + )?); | ||
| 389 | + } else { | ||
| 390 | + mounts.push(mount( | ||
| 391 | + "/etc/resolv.conf", | ||
| 392 | + "bind", | ||
| 393 | + "/etc/resolv.conf", | ||
| 394 | + &["bind", "ro"], | ||
| 395 | + )?); | ||
| 396 | + } | ||
| 386 | } else { | 397 | } else { |
| 387 | mounts.push(mount( | 398 | mounts.push(mount( |
| 388 | "/sys", | 399 | "/sys", |
| @@ -462,11 +473,13 @@ mod tests { | |||
| 462 | ], | 473 | ], |
| 463 | run: "echo hi".to_owned(), | 474 | run: "echo hi".to_owned(), |
| 464 | network, | 475 | network, |
| 476 | + pasta: None, | ||
| 465 | limits: Limits { | 477 | limits: Limits { |
| 466 | memory: "2g".to_owned(), | 478 | memory: "2g".to_owned(), |
| 467 | cpus: "1.5".to_owned(), | 479 | cpus: "1.5".to_owned(), |
| 468 | pids: 512, | 480 | pids: 512, |
| 469 | image_max_gb: 20, | 481 | image_max_gb: 20, |
| 482 | + job_disk_gb: 20, | ||
| 470 | ..Limits::default() | 483 | ..Limits::default() |
| 471 | }, | 484 | }, |
| 472 | idmap: IdMap::single(), | 485 | idmap: IdMap::single(), |
crates/forge-runner/tests/integration/builtin.rsmodified+27 -0
| @@ -323,3 +323,30 @@ async fn sigkilled_helper_leaves_no_process_behind() { | |||
| 323 | } | 323 | } |
| 324 | assert!(!dir.path().join("jobs").join(job_id).exists(), "job dir was kept"); | 324 | assert!(!dir.path().join("jobs").join(job_id).exists(), "job dir was kept"); |
| 325 | } | 325 | } |
| 326 | + | ||
| 327 | +#[tokio::test] | ||
| 328 | +async fn network_job_gets_its_own_network_without_private_ranges() { | ||
| 329 | + let _serial = serial().await; | ||
| 330 | + if !can_run() || forge_runner::sandbox::net::find_pasta().is_none() { | ||
| 331 | + eprintln!("skipping: needs user namespaces and pasta"); | ||
| 332 | + return; | ||
| 333 | + } | ||
| 334 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 335 | + let (exec, workspace) = executor(dir.path()); | ||
| 336 | + let mut job = job("read -r l < /etc/resolv.conf; echo \"dns=$l\"; \ | ||
| 337 | + if (echo > /dev/tcp/169.254.169.254/80) 2>/dev/null; then echo meta=open; \ | ||
| 338 | + else echo meta=blocked; fi"); | ||
| 339 | + job.network = true; | ||
| 340 | + let (result, logs) = run_job(&exec, &job, &workspace, CancellationToken::new()).await; | ||
| 341 | + | ||
| 342 | + assert_eq!(result.outcome, Outcome::Success, "{result:?}\n{logs}"); | ||
| 343 | + assert!(logs.contains("dns=nameserver 192.0.2.3"), "{logs}"); | ||
| 344 | + assert!(logs.contains("meta=blocked"), "{logs}"); | ||
| 345 | + assert!(!logs.contains("pasta is not installed"), "{logs}"); | ||
| 346 | + let pid_file = dir.path().join("jobs/job_01/pasta.pid"); | ||
| 347 | + let leftover = fs::read_dir("/proc").expect("read /proc").flatten().any(|entry| { | ||
| 348 | + fs::read(entry.path().join("cmdline")) | ||
| 349 | + .is_ok_and(|cmd| String::from_utf8_lossy(&cmd).contains(&*pid_file.to_string_lossy())) | ||
| 350 | + }); | ||
| 351 | + assert!(!leftover, "pasta outlived the job"); | ||
| 352 | +} | ||
crates/forge-runner/tests/integration/sandbox.rsmodified+1 -0
| @@ -102,6 +102,7 @@ fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxReques | |||
| 102 | env: vec![("FORGE_TEST".to_owned(), "yes".to_owned())], | 102 | env: vec![("FORGE_TEST".to_owned(), "yes".to_owned())], |
| 103 | run: run.to_owned(), | 103 | run: run.to_owned(), |
| 104 | network, | 104 | network, |
| 105 | + pasta: None, | ||
| 105 | limits: Limits::default(), | 106 | limits: Limits::default(), |
| 106 | idmap: IdMap::single(), | 107 | idmap: IdMap::single(), |
| 107 | } | 108 | } |
crates/forge-web/src/pages/admin_runners.rsmodified+10 -0
| @@ -810,6 +810,7 @@ const TABS: [(&str, &[&str]); 5] = [ | |||
| 810 | &[ | 810 | &[ |
| 811 | "work_dir", | 811 | "work_dir", |
| 812 | "limits.image_max_gb", | 812 | "limits.image_max_gb", |
| 813 | + "limits.job_disk_gb", | ||
| 813 | "images.keep_days", | 814 | "images.keep_days", |
| 814 | "cache_max_gib", | 815 | "cache_max_gib", |
| 815 | ], | 816 | ], |
| @@ -936,6 +937,14 @@ fn field_text(lang: Lang, key: &str) -> (&'static str, &'static str) { | |||
| 936 | "Saklanan kapsayıcı kalıpları için üst sınır.", | 937 | "Saklanan kapsayıcı kalıpları için üst sınır.", |
| 937 | ), | 938 | ), |
| 938 | ), | 939 | ), |
| 940 | + "limits.job_disk_gb" => ( | ||
| 941 | + s(lang, "Disk per job (GB)", "İş başına disk (GB)"), | ||
| 942 | + s( | ||
| 943 | + lang, | ||
| 944 | + "A job that fills more than this (workspace, /tmp and its writes over the image) is stopped. 0 means no cap.", | ||
| 945 | + "Bundan fazlasını (çalışma alanı, /tmp ve kalıbın üstüne yazdıkları) dolduran iş durdurulur. 0 sınır yok demektir.", | ||
| 946 | + ), | ||
| 947 | + ), | ||
| 939 | "images.keep_days" => ( | 948 | "images.keep_days" => ( |
| 940 | s(lang, "Keep images (days)", "Kalıpları sakla (gün)"), | 949 | s(lang, "Keep images (days)", "Kalıpları sakla (gün)"), |
| 941 | s( | 950 | s( |
| @@ -1032,6 +1041,7 @@ fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec<DetailField> | |||
| 1032 | f.key, | 1041 | f.key, |
| 1033 | "limits.pids" | 1042 | "limits.pids" |
| 1034 | | "limits.image_max_gb" | 1043 | | "limits.image_max_gb" |
| 1044 | + | "limits.job_disk_gb" | ||
| 1035 | | "images.keep_days" | 1045 | | "images.keep_days" |
| 1036 | | "cache_max_gib" | 1046 | | "cache_max_gib" |
| 1037 | | "concurrency" | 1047 | | "concurrency" |
docs/ci.mdmodified+17 -6
| @@ -58,7 +58,7 @@ There must be at least one job, and at most 20. | |||
| 58 | | `timeout_minutes` | integer | `60` | Range 1 to 360. | | 58 | | `timeout_minutes` | integer | `60` | Range 1 to 360. | |
| 59 | | `memory` | string | none | The job's expected peak memory, such as `4g` or `512m`. 64m to 1024g. See [Memory](#memory). | | 59 | | `memory` | string | none | The job's expected peak memory, such as `4g` or `512m`. 64m to 1024g. See [Memory](#memory). | |
| 60 | | `matrix` | table | none | Expands the job into one job per combination. See [Matrix builds](#matrix-builds). | | 60 | | `matrix` | table | none | Expands the job into one job per combination. See [Matrix builds](#matrix-builds). | |
| 61 | -| `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` shares the runner host's network namespace. Read [the caveats](#builtin-executor-caveats). | | 61 | +| `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` gives it internet access, isolated through `pasta` when it is installed. Read [the caveats](#builtin-executor-caveats). | |
| 62 | 62 | ||
| 63 | Job names match `^[a-z0-9][a-z0-9_-]{0,39}$`. | 63 | Job names match `^[a-z0-9][a-z0-9_-]{0,39}$`. |
| 64 | 64 | ||
| @@ -580,6 +580,7 @@ budget_swap_percent = 0 # in auto mode: percent of swap that counts toward the b | |||
| 580 | cpus = "2" # the job cgroup's cpu.max, or podman --cpus | 580 | cpus = "2" # the job cgroup's cpu.max, or podman --cpus |
| 581 | pids = 4096 # the job cgroup's pids.max, or podman --pids-limit | 581 | pids = 4096 # the job cgroup's pids.max, or podman --pids-limit |
| 582 | image_max_gb = 20 # cap on the unpacked size of one image (builtin) | 582 | image_max_gb = 20 # cap on the unpacked size of one image (builtin) |
| 583 | +job_disk_gb = 20 # disk one job may fill: workspace, /tmp, writes over the image; 0 = no cap (builtin) | ||
| 583 | 584 | ||
| 584 | [images] | 585 | [images] |
| 585 | keep_days = 7 # images unused for this many days are deleted (builtin) | 586 | keep_days = 7 # images unused for this many days are deleted (builtin) |
| @@ -647,10 +648,20 @@ Image garbage collection runs at startup and then daily. Unpacked images are kep | |||
| 647 | 648 | ||
| 648 | Read these before you run untrusted or sensitive jobs on a runner: | 649 | Read these before you run untrusted or sensitive jobs on a runner: |
| 649 | 650 | ||
| 650 | -- **`network = true` shares the host's network namespace.** The builtin executor does not set up | 651 | +- **`network = true` needs `pasta` to be isolated.** With `pasta` installed (the `passt` |
| 651 | - a separate network, so a job with `network = true` can reach every service that the runner host | 652 | + package: `dnf install passt`, `apt install passt`), a job with `network = true` gets its own |
| 652 | - can reach, including services bound to the host's `localhost`. Use `network = false` for any job | 653 | + network namespace with internet access through `pasta`. The runner host's `localhost`, private |
| 653 | - that does not need the network. It gets only a loopback interface. | 654 | + ranges (10/8, 172.16/12, 192.168/16, 100.64/10) and link-local addresses such as cloud |
| 655 | + metadata are blocked, and there is no IPv6. Without `pasta` the job shares the runner host's | ||
| 656 | + network namespace and can reach everything the host can, including its `localhost`; the job | ||
| 657 | + log then says so. Use `network = false` for any job that does not need the network. It gets | ||
| 658 | + only a loopback interface. | ||
| 659 | +- **Disk is capped per job** by `limits.job_disk_gb` (default 20): the workspace, `/tmp` and what | ||
| 660 | + the job writes over the image. The runner measures it every few seconds and stops a job past | ||
| 661 | + the cap, so a fast writer can overshoot a little. | ||
| 662 | +- **Leftovers are cleaned at startup.** After a crash the runner removes leftover job dirs, job | ||
| 663 | + cgroups, `pasta` processes and workspaces (dirs in `work_dir` named like a job id) before it | ||
| 664 | + takes a job. | ||
| 654 | - **Subordinate ids are mapped in subuid mode.** Container ids `1` to `n` map to your subordinate | 665 | - **Subordinate ids are mapped in subuid mode.** Container ids `1` to `n` map to your subordinate |
| 655 | range, so a command can change file ownership to another user or group, as `apt` and `useradd` | 666 | range, so a command can change file ownership to another user or group, as `apt` and `useradd` |
| 656 | do. This needs the setup in [Subordinate ids](#subordinate-ids). Without it, the runner falls | 667 | do. This needs the setup in [Subordinate ids](#subordinate-ids). Without it, the runner falls |
| @@ -659,7 +670,7 @@ Read these before you run untrusted or sensitive jobs on a runner: | |||
| 659 | have the ownership a job sees. A file that is owner `1000` inside a job is owned by | 670 | have the ownership a job sees. A file that is owner `1000` inside a job is owned by |
| 660 | `start + 999` on the host, for example `525287` with the range `524288`. `ls -ln` shows the | 671 | `start + 999` on the host, for example `525287` with the range `524288`. `ls -ln` shows the |
| 661 | numbers. The runner removes these files through a helper, so it can still clean them up. | 672 | numbers. The runner removes these files through a helper, so it can still clean them up. |
| 662 | -- **With `network = true`, `/sys` is the host's `/sys`,** bind-mounted read-only. The job can read | 673 | +- **With `network = true`, `/sys` may be the host's `/sys`,** bind-mounted read-only. The job can read |
| 663 | host hardware and kernel details from it. | 674 | host hardware and kernel details from it. |
| 664 | - **The job cgroup is placed in the parent slice.** It is named `forge-job-<job id>-<helper pid>` | 675 | - **The job cgroup is placed in the parent slice.** It is named `forge-job-<job id>-<helper pid>` |
| 665 | and sits next to the runner's own cgroup, not under it. The runner's cgroup is never used for a | 676 | and sits next to the runner's own cgroup, not under it. The runner's cgroup is never used for a |