worklyn / zukapublic
Agent-first git hosting. One Rust binary: git over HTTP and SSH, a REST API, MCP, CI, and multi-tenant isolation.
Get a copy:
git clone https://zuka.worklyn.com/worklyn/zuka.git
| 1 | // Executing a run. |
| 2 | // |
| 3 | // What this actually provides, stated plainly because the gap between claimed and |
| 4 | // real isolation is where people get hurt: |
| 5 | // |
| 6 | // * a scrubbed environment — the child inherits nothing but an allowlist, so the |
| 7 | // service's credentials are not readable from `/proc/self/environ`; |
| 8 | // * rlimits on CPU, address space, file size and open files (process count is |
| 9 | // opt-in: `RLIMIT_NPROC` is per-UID and means nothing without a runner uid); |
| 10 | // * a wall-clock timeout that kills the whole process GROUP, because a step's |
| 11 | // children are grandchildren of ours and killing the shell orphans them; |
| 12 | // * a bounded log, so output cannot fill the disk; |
| 13 | // * a workspace that is deleted afterwards. |
| 14 | // |
| 15 | // What it does NOT provide, in standalone mode: a container, a network namespace, or |
| 16 | // a separate uid unless the operator configured one. **Standalone CI is not a |
| 17 | // security boundary** — anyone who can push can run code as the service user. It is |
| 18 | // off by default and the README says this in the same words. |
| 19 | // |
| 20 | // A step allowlist was considered and rejected: `sh -c` defeats it in one character. |
| 21 | // Enforcement is at the OS or it is not enforcement. |
| 22 | |
| 23 | use crate::brand; |
| 24 | use crate::ci::run::{Run, RunStore, Status}; |
| 25 | use crate::ci::spec::Spec; |
| 26 | use crate::config::Config; |
| 27 | use crate::git::validate::Name; |
| 28 | use std::path::Path; |
| 29 | use std::process::Stdio; |
| 30 | use std::time::Duration; |
| 31 | use tokio::io::AsyncReadExt; |
| 32 | use tokio::process::Command; |
| 33 | |
| 34 | /// Environment variables the child is allowed to see, beyond the ones we set. |
| 35 | const INHERITED: &[&str] = &["PATH", "HOME", "LANG", "TZ"]; |
| 36 | |
| 37 | /// Everything a step needs that does not change between steps. |
| 38 | struct Context<'a> { |
| 39 | config: &'a Config, |
| 40 | runs: &'a RunStore, |
| 41 | account: &'a Name, |
| 42 | repo: &'a Name, |
| 43 | run: &'a Run, |
| 44 | workspace: &'a Path, |
| 45 | } |
| 46 | |
| 47 | impl Context<'_> { |
| 48 | fn log(&self, text: &str) { |
| 49 | let _ = self.runs.append_log( |
| 50 | self.account, |
| 51 | self.repo, |
| 52 | &self.run.id, |
| 53 | text.as_bytes(), |
| 54 | self.config.ci_log_bytes, |
| 55 | ); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub struct Outcome { |
| 60 | pub status: Status, |
| 61 | pub exit_code: Option<i32>, |
| 62 | pub detail: Option<String>, |
| 63 | } |
| 64 | |
| 65 | /// Check out a revision and run its steps. |
| 66 | pub async fn execute( |
| 67 | config: &Config, |
| 68 | runs: &RunStore, |
| 69 | account: &Name, |
| 70 | repo: &Name, |
| 71 | run: &Run, |
| 72 | git_dir: &Path, |
| 73 | ) -> Outcome { |
| 74 | let workspace = config |
| 75 | .data_dir |
| 76 | .join("tmp") |
| 77 | .join("work") |
| 78 | .join(format!("{}-{}", run.id, run.created_at)); |
| 79 | |
| 80 | let outcome = execute_in(config, runs, account, repo, run, git_dir, &workspace).await; |
| 81 | |
| 82 | // The workspace is scratch and may contain anything the run wrote. |
| 83 | if let Err(e) = std::fs::remove_dir_all(&workspace) { |
| 84 | if e.kind() != std::io::ErrorKind::NotFound { |
| 85 | eprintln!("[ci] could not clean {}: {e}", workspace.display()); |
| 86 | } |
| 87 | } |
| 88 | outcome |
| 89 | } |
| 90 | |
| 91 | async fn execute_in( |
| 92 | config: &Config, |
| 93 | runs: &RunStore, |
| 94 | account: &Name, |
| 95 | repo: &Name, |
| 96 | run: &Run, |
| 97 | git_dir: &Path, |
| 98 | workspace: &Path, |
| 99 | ) -> Outcome { |
| 100 | let ctx = Context { |
| 101 | config, |
| 102 | runs, |
| 103 | account, |
| 104 | repo, |
| 105 | run, |
| 106 | workspace, |
| 107 | }; |
| 108 | |
| 109 | if let Err(e) = std::fs::create_dir_all(workspace) { |
| 110 | return internal(format!("could not create a workspace: {e}")); |
| 111 | } |
| 112 | |
| 113 | // Check out into the workspace without a clone: the object database is right |
| 114 | // there, and `--no-checkout` plus `checkout-index` avoids a second copy of it. |
| 115 | ctx.log(&format!("$ checkout {}\n", run.sha)); |
| 116 | if let Err(e) = checkout(git_dir, &run.sha, workspace).await { |
| 117 | ctx.log(&format!("{e}\n")); |
| 118 | return Outcome { |
| 119 | status: Status::Failed, |
| 120 | exit_code: None, |
| 121 | detail: Some("checkout failed".into()), |
| 122 | }; |
| 123 | } |
| 124 | |
| 125 | let spec_path = workspace.join(brand::ci_filename()); |
| 126 | let source = match std::fs::read_to_string(&spec_path) { |
| 127 | Ok(source) => source, |
| 128 | Err(_) => { |
| 129 | ctx.log(&format!( |
| 130 | "no {} in this revision; nothing to run\n", |
| 131 | brand::ci_filename() |
| 132 | )); |
| 133 | return Outcome { |
| 134 | status: Status::Succeeded, |
| 135 | exit_code: Some(0), |
| 136 | detail: Some("no spec".into()), |
| 137 | }; |
| 138 | } |
| 139 | }; |
| 140 | |
| 141 | let spec = match Spec::parse(&source) { |
| 142 | Ok(spec) => spec, |
| 143 | Err(e) => { |
| 144 | ctx.log(&format!("{}\n", e.detail_for_user())); |
| 145 | return Outcome { |
| 146 | status: Status::Failed, |
| 147 | exit_code: None, |
| 148 | detail: Some("invalid spec".into()), |
| 149 | }; |
| 150 | } |
| 151 | }; |
| 152 | |
| 153 | if !spec.runs_for(&run.git_ref) { |
| 154 | ctx.log(&format!( |
| 155 | "{} is not in run.branches; skipped\n", |
| 156 | run.git_ref |
| 157 | )); |
| 158 | return Outcome { |
| 159 | status: Status::Succeeded, |
| 160 | exit_code: Some(0), |
| 161 | detail: Some("skipped".into()), |
| 162 | }; |
| 163 | } |
| 164 | |
| 165 | let deadline = spec.timeout(config.ci_timeout); |
| 166 | |
| 167 | // Say so when the host ceiling overrides what the repository asked for. Silently |
| 168 | // clamping is how a repository ends up reporting "timed out after 600s" when its |
| 169 | // spec plainly says 2400, and the only way to find out is to read the source. |
| 170 | let requested = Duration::from_secs(spec.run.timeout_secs); |
| 171 | if requested > deadline { |
| 172 | ctx.log(&format!( |
| 173 | "note: {} asks for a {}s timeout; this host allows at most {}s\n", |
| 174 | brand::ci_filename(), |
| 175 | requested.as_secs(), |
| 176 | deadline.as_secs(), |
| 177 | )); |
| 178 | } |
| 179 | |
| 180 | let started = std::time::Instant::now(); |
| 181 | |
| 182 | for step in &spec.run.steps { |
| 183 | let remaining = deadline.saturating_sub(started.elapsed()); |
| 184 | if remaining.is_zero() { |
| 185 | return timed_out(&ctx, deadline); |
| 186 | } |
| 187 | |
| 188 | ctx.log(&format!("$ {step}\n")); |
| 189 | match run_step(&ctx, step, remaining).await { |
| 190 | StepResult::Ok => {} |
| 191 | StepResult::Failed(code) => { |
| 192 | ctx.log(&format!("step failed with exit code {code}\n")); |
| 193 | return Outcome { |
| 194 | status: Status::Failed, |
| 195 | exit_code: Some(code), |
| 196 | detail: Some(format!("step failed: {step}")), |
| 197 | }; |
| 198 | } |
| 199 | StepResult::TimedOut => return timed_out(&ctx, deadline), |
| 200 | StepResult::Internal(detail) => { |
| 201 | ctx.log(&format!("{detail}\n")); |
| 202 | return internal(detail); |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | ctx.log("all steps succeeded\n"); |
| 208 | Outcome { |
| 209 | status: Status::Succeeded, |
| 210 | exit_code: Some(0), |
| 211 | detail: None, |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | enum StepResult { |
| 216 | Ok, |
| 217 | Failed(i32), |
| 218 | TimedOut, |
| 219 | Internal(String), |
| 220 | } |
| 221 | |
| 222 | async fn run_step(ctx: &Context<'_>, step: &str, remaining: Duration) -> StepResult { |
| 223 | let (config, runs, run) = (ctx.config, ctx.runs, ctx.run); |
| 224 | let (account, repo) = (ctx.account, ctx.repo); |
| 225 | |
| 226 | let mut command = Command::new("/bin/sh"); |
| 227 | command |
| 228 | .arg("-c") |
| 229 | .arg(step) |
| 230 | .current_dir(ctx.workspace) |
| 231 | .env_clear() |
| 232 | .env("CI", "1") |
| 233 | .env(brand::env_name("CI"), "1") |
| 234 | .env(brand::env_name("RUN_ID"), &run.id) |
| 235 | .env(brand::env_name("SHA"), &run.sha) |
| 236 | .env(brand::env_name("REF"), &run.git_ref) |
| 237 | .stdin(Stdio::null()) |
| 238 | .stdout(Stdio::piped()) |
| 239 | .stderr(Stdio::piped()) |
| 240 | .kill_on_drop(true); |
| 241 | |
| 242 | for key in INHERITED { |
| 243 | if let Ok(value) = std::env::var(key) { |
| 244 | command.env(key, value); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | #[cfg(unix)] |
| 249 | { |
| 250 | command.process_group(0); |
| 251 | apply_limits(&mut command, config); |
| 252 | } |
| 253 | |
| 254 | let mut child = match command.spawn() { |
| 255 | Ok(child) => child, |
| 256 | Err(e) => return StepResult::Internal(format!("could not start the step: {e}")), |
| 257 | }; |
| 258 | let pid = child.id(); |
| 259 | |
| 260 | let mut stdout = child.stdout.take().expect("stdout is piped"); |
| 261 | let mut stderr = child.stderr.take().expect("stderr is piped"); |
| 262 | let cap = config.ci_log_bytes; |
| 263 | |
| 264 | // Both pipes drain concurrently. A step that fills stderr while we read only |
| 265 | // stdout blocks forever on a 64 KiB pipe. |
| 266 | let pump = async { |
| 267 | let mut out = [0u8; 8192]; |
| 268 | let mut err = [0u8; 8192]; |
| 269 | loop { |
| 270 | tokio::select! { |
| 271 | read = stdout.read(&mut out) => match read { |
| 272 | Ok(0) | Err(_) => break, |
| 273 | Ok(n) => { let _ = runs.append_log(account, repo, &run.id, &out[..n], cap); } |
| 274 | }, |
| 275 | read = stderr.read(&mut err) => match read { |
| 276 | Ok(0) | Err(_) => break, |
| 277 | Ok(n) => { let _ = runs.append_log(account, repo, &run.id, &err[..n], cap); } |
| 278 | }, |
| 279 | } |
| 280 | } |
| 281 | // Whichever pipe closed first, drain the other. |
| 282 | let mut rest = Vec::new(); |
| 283 | let _ = stdout.read_to_end(&mut rest).await; |
| 284 | let _ = runs.append_log(account, repo, &run.id, &rest, cap); |
| 285 | rest.clear(); |
| 286 | let _ = stderr.read_to_end(&mut rest).await; |
| 287 | let _ = runs.append_log(account, repo, &run.id, &rest, cap); |
| 288 | }; |
| 289 | |
| 290 | let waited = tokio::time::timeout(remaining, async { |
| 291 | pump.await; |
| 292 | child.wait().await |
| 293 | }) |
| 294 | .await; |
| 295 | |
| 296 | match waited { |
| 297 | Err(_) => { |
| 298 | kill_group(pid); |
| 299 | StepResult::TimedOut |
| 300 | } |
| 301 | Ok(Err(e)) => StepResult::Internal(format!("could not wait for the step: {e}")), |
| 302 | Ok(Ok(status)) if status.success() => StepResult::Ok, |
| 303 | Ok(Ok(status)) => StepResult::Failed(status.code().unwrap_or(-1)), |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | /// Apply resource limits in the child, between fork and exec. |
| 308 | #[cfg(unix)] |
| 309 | fn apply_limits(command: &mut Command, config: &Config) { |
| 310 | let cpu = config.ci_timeout.as_secs().max(1); |
| 311 | let memory = config.ci_memory_bytes; |
| 312 | let file_size = config.ci_file_bytes; |
| 313 | let processes = config.ci_max_processes; |
| 314 | |
| 315 | // SAFETY: only async-signal-safe calls between fork and exec. `setrlimit` is. |
| 316 | unsafe { |
| 317 | command.pre_exec(move || { |
| 318 | set_limit(libc::RLIMIT_CPU, cpu); |
| 319 | // Independent of the memory limit. This was once derived from it, and |
| 320 | // turning the memory limit off therefore shrank the file limit to a few |
| 321 | // megabytes — which surfaced as the linker being killed by SIGXFSZ while |
| 322 | // writing a test binary, an error that names neither limit. |
| 323 | if file_size > 0 { |
| 324 | set_limit(libc::RLIMIT_FSIZE, file_size); |
| 325 | } |
| 326 | set_limit(libc::RLIMIT_NOFILE, 1024); |
| 327 | // RLIMIT_AS caps the address space a process may map, which is not the |
| 328 | // same thing as the memory it uses. V8, the JVM and the Go runtime all |
| 329 | // reserve multi-gigabyte regions up front and touch almost none of it, |
| 330 | // so a limit set to a sensible working-set size kills them on startup |
| 331 | // with an out-of-memory message that has nothing to do with memory. |
| 332 | // Anything running a JavaScript or Java toolchain in CI needs this set |
| 333 | // far above the real requirement, or set to 0 and bounded by a cgroup |
| 334 | // instead — which is the control that actually measures usage. |
| 335 | if memory > 0 { |
| 336 | set_limit(libc::RLIMIT_AS, memory); |
| 337 | } |
| 338 | // Off unless the operator asked for it. RLIMIT_NPROC is per-UID: with |
| 339 | // the runner sharing a uid with the service it counts processes we do |
| 340 | // not control, so a useful-looking value makes `fork` fail on the first |
| 341 | // step. It becomes meaningful — and the fork-bomb protection it looks |
| 342 | // like — only alongside a dedicated runner uid. |
| 343 | if processes > 0 { |
| 344 | set_limit(libc::RLIMIT_NPROC, processes); |
| 345 | } |
| 346 | Ok(()) |
| 347 | }); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | /// Type of the `resource` argument to `setrlimit`. |
| 352 | /// |
| 353 | /// glibc declares it `__rlimit_resource_t` (u32); musl and the BSDs use `c_int`. |
| 354 | /// The discriminator is the C library, not the OS — keying on `target_os` compiles |
| 355 | /// on linux-gnu and fails on linux-musl, which is the target that produces the |
| 356 | /// static binary this service ships as. |
| 357 | #[cfg(all(unix, target_os = "linux", target_env = "gnu"))] |
| 358 | type RlimitResource = u32; |
| 359 | #[cfg(all(unix, not(all(target_os = "linux", target_env = "gnu"))))] |
| 360 | type RlimitResource = libc::c_int; |
| 361 | |
| 362 | #[cfg(unix)] |
| 363 | fn set_limit(resource: RlimitResource, value: u64) { |
| 364 | let limit = libc::rlimit { |
| 365 | rlim_cur: value as libc::rlim_t, |
| 366 | rlim_max: value as libc::rlim_t, |
| 367 | }; |
| 368 | // SAFETY: `limit` is a valid, fully initialised rlimit for `resource`. |
| 369 | unsafe { |
| 370 | libc::setrlimit(resource, &limit); |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | fn kill_group(pid: Option<u32>) { |
| 375 | #[cfg(unix)] |
| 376 | if let Some(pid) = pid { |
| 377 | // SAFETY: spawned with `process_group(0)`, so the pgid is the child's own |
| 378 | // pid and no unrelated process shares it. |
| 379 | unsafe { |
| 380 | libc::killpg(pid as libc::pid_t, libc::SIGKILL); |
| 381 | } |
| 382 | } |
| 383 | let _ = pid; |
| 384 | } |
| 385 | |
| 386 | /// Materialise a revision into a workspace. |
| 387 | /// |
| 388 | /// A temporary index plus `checkout-index`, not a clone and not `archive | tar`: |
| 389 | /// the object database is already on this disk, so cloning would copy all of it to |
| 390 | /// read one tree, and piping through `tar` would add an external dependency and a |
| 391 | /// second process to supervise. This is pure git and writes only under |
| 392 | /// `GIT_WORK_TREE`. |
| 393 | async fn checkout(git_dir: &Path, sha: &str, workspace: &Path) -> std::result::Result<(), String> { |
| 394 | let index = workspace.with_extension("index"); |
| 395 | |
| 396 | let run = |args: Vec<String>| { |
| 397 | let index = index.clone(); |
| 398 | async move { |
| 399 | let output = Command::new("git") |
| 400 | .env_clear() |
| 401 | .env( |
| 402 | "PATH", |
| 403 | std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".into()), |
| 404 | ) |
| 405 | .env("GIT_CONFIG_NOSYSTEM", "1") |
| 406 | .env("GIT_DIR", git_dir) |
| 407 | .env("GIT_WORK_TREE", workspace) |
| 408 | .env("GIT_INDEX_FILE", &index) |
| 409 | .args(&args) |
| 410 | .output() |
| 411 | .await |
| 412 | .map_err(|e| format!("spawn git: {e}"))?; |
| 413 | |
| 414 | if output.status.success() { |
| 415 | Ok(()) |
| 416 | } else { |
| 417 | Err(format!( |
| 418 | "git {} failed: {}", |
| 419 | args.first().cloned().unwrap_or_default(), |
| 420 | String::from_utf8_lossy(&output.stderr).trim() |
| 421 | )) |
| 422 | } |
| 423 | } |
| 424 | }; |
| 425 | |
| 426 | let outcome = async { |
| 427 | run(vec!["read-tree".into(), sha.to_string()]).await?; |
| 428 | run(vec![ |
| 429 | "checkout-index".into(), |
| 430 | "--all".into(), |
| 431 | "--force".into(), |
| 432 | ]) |
| 433 | .await |
| 434 | } |
| 435 | .await; |
| 436 | |
| 437 | // The index is scratch and must not outlive the checkout. |
| 438 | let _ = std::fs::remove_file(&index); |
| 439 | outcome |
| 440 | } |
| 441 | |
| 442 | fn timed_out(ctx: &Context<'_>, deadline: Duration) -> Outcome { |
| 443 | ctx.log(&format!("run exceeded its {deadline:?} timeout\n")); |
| 444 | Outcome { |
| 445 | status: Status::TimedOut, |
| 446 | exit_code: None, |
| 447 | detail: Some(format!("timed out after {deadline:?}")), |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | fn internal(detail: String) -> Outcome { |
| 452 | Outcome { |
| 453 | status: Status::Failed, |
| 454 | exit_code: None, |
| 455 | detail: Some(detail), |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | #[cfg(test)] |
| 460 | mod tests { |
| 461 | use super::*; |
| 462 | |
| 463 | #[test] |
| 464 | fn the_inherited_environment_is_an_allowlist_not_a_passthrough() { |
| 465 | // The service's own secrets must not be readable from a step. |
| 466 | for dangerous in [ |
| 467 | "KV_URL", |
| 468 | "DENO_KV_ACCESS_TOKEN", |
| 469 | "AWS_SECRET_ACCESS_KEY", |
| 470 | "LD_PRELOAD", |
| 471 | "GIT_CONFIG_GLOBAL", |
| 472 | ] { |
| 473 | assert!( |
| 474 | !INHERITED.contains(&dangerous), |
| 475 | "{dangerous} must not be inherited by a CI step" |
| 476 | ); |
| 477 | } |
| 478 | assert!( |
| 479 | INHERITED.contains(&"PATH"), |
| 480 | "a step needs to find its tools" |
| 481 | ); |
| 482 | } |
| 483 | } |