//! Git and LFS for nodes, through the hub. Nodes hold no Forgejo credential. //! //! A node's `origin` is `midas@:/.git`. The hub's sshd runs //! every node login through `midas hub git` (an `authorized_keys` command, one //! key per node), which answers three requests and nothing else: //! //! * `git-upload-pack ''` — refresh the mirror from Forgejo if it is more //! than [`FRESH_SECS`] old, then hand the session to `git upload-pack` on it. //! * `git-lfs-authenticate '' download` — a short-lived token for the hub's //! LFS endpoint (`hub serve`), which fetches missing objects from Forgejo, //! caches them, and serves them. //! * `git-lfs-transfer …` — refused, so git-lfs falls back to the above. //! //! The mirror is fetched with a read-only deploy key (`/etc/midas`), which only //! the `midas` user and root can read. Pushes are refused: nodes do not push in //! this version (DESIGN.md §8). use std::fs; use std::io::Write; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::Command; use std::time::{Duration, SystemTime}; use anyhow::{bail, Context, Result}; use serde_json::{json, Value}; use crate::events; /// A mirror younger than this is served as it is. pub const FRESH_SECS: u64 = 20; /// How long an LFS token lasts: one checkout's smudge, with room. pub const TOKEN_SECS: u64 = 30 * 60; pub fn base() -> PathBuf { PathBuf::from(crate::hubsetup::HOME) } /// The read-only deploy key the mirror is fetched with (`midas hub setup` makes it). pub const DEPLOY_KEY: &str = "/etc/midas/mirror_ed25519"; pub fn forgejo_ssh() -> String { crate::conf::hub().forgejo_ssh } pub fn deploy_key() -> String { DEPLOY_KEY.into() } /// With time limits: a forge that takes the connection and then says nothing held the fetch, and /// the hub thread under it (the heartbeat watch's, through a deploy's), with no end. pub(crate) fn git_ssh() -> String { format!( "ssh -i {} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=accept-new \ -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=4 \ -o UserKnownHostsFile={}/known_hosts", deploy_key(), base().display() ) } /// `owner/repo.git` from whatever the client sent: quotes, a leading slash, a /// missing `.git`. Anything that is not two plain path segments is refused, so a /// request cannot walk out of the mirror directory. pub fn repo_name(raw: &str) -> Result { let r = raw.trim().trim_matches('\'').trim_matches('"').trim_start_matches('/'); let r = r.strip_suffix(".git").unwrap_or(r); let parts: Vec<&str> = r.split('/').collect(); let ok = parts.len() == 2 && parts.iter().all(|p| { !p.is_empty() && !p.starts_with('.') && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) }); if !ok { bail!("not a repository name: {raw:?}"); } Ok(format!("{}/{}.git", parts[0], parts[1])) } fn allowed(repo: &str) -> bool { crate::conf::hub().allows(repo) } /// A hosted repository is its own mirror (hosted.rs): nothing to fetch. pub fn mirror_path(repo: &str) -> PathBuf { if crate::hosted::is_hosted(repo) { return crate::hosted::path(repo); } base().join("mirrors").join(repo) } /// Fetch now, however recently it was fetched: a deploy is asked for seconds /// after the push it publishes. pub fn fetch_now(repo: &str) -> Result<()> { if crate::hosted::is_hosted(repo) { return Ok(()); } let _ = fs::remove_file(mirror_path(repo).join("midas-fetched")); refresh(repo) } /// Bring the mirror up to date with Forgejo, creating it the first time. pub fn refresh(repo: &str) -> Result<()> { if crate::hosted::is_hosted(repo) { return Ok(()); } let path = mirror_path(repo); let stamp = path.join("midas-fetched"); let age = fs::metadata(&stamp) .and_then(|m| m.modified()) .ok() .and_then(|m| SystemTime::now().duration_since(m).ok()) .unwrap_or(Duration::MAX); if age < Duration::from_secs(FRESH_SECS) { return Ok(()); } let url = format!("{}/{repo}", forgejo_ssh()); let started = std::time::Instant::now(); let out = if path.join("HEAD").exists() { Command::new("git") .args(["-C", &path.to_string_lossy(), "fetch", "--prune", "--quiet", "origin"]) .env("GIT_SSH_COMMAND", git_ssh()) .output()? } else { fs::create_dir_all(path.parent().unwrap())?; Command::new("git") .args(["clone", "--mirror", "--quiet", &url, &path.to_string_lossy()]) .env("GIT_SSH_COMMAND", git_ssh()) .output()? }; if !out.status.success() { let err = String::from_utf8_lossy(&out.stderr); let tail: String = err.lines().rev().take(3).collect::>().join(" | "); log("git_fetch", json!({"repo": repo, "ok": false, "stderr": tail})); bail!("fetching {repo} from Forgejo failed: {tail}"); } fs::write(&stamp, b"")?; log("git_fetch", json!({ "repo": repo, "ok": true, "duration_ms": started.elapsed().as_millis() as u64, })); Ok(()) } /// What a node's git key asked the hub's sshd for (`SSH_ORIGINAL_COMMAND`). #[derive(Debug, PartialEq)] enum GitAsk { /// A fetch of this repository. Fetch(String), /// An LFS token for this repository and operation (only `download` is given). Lfs(String, String), /// git-lfs-transfer: refused, so git-lfs falls back to the HTTP endpoint. Transfer, Push, /// Anything else, with the command as it came. Other(String), } /// Read the command a node's key sent. A repository name that is not two /// plain path segments is an error (`repo_name`): it must not walk out of the /// mirror directory. fn git_ask(cmd: &str) -> Result { let (verb, rest) = cmd.split_once(' ').unwrap_or((cmd, "")); Ok(match verb { "git-upload-pack" => GitAsk::Fetch(named(rest)?), "git-lfs-authenticate" => { let mut words = rest.split_whitespace(); let repo = named(words.next().unwrap_or(""))?; GitAsk::Lfs(repo, words.next().unwrap_or("download").to_string()) } "git-lfs-transfer" => GitAsk::Transfer, "git-receive-pack" => GitAsk::Push, _ => GitAsk::Other(cmd.to_string()), }) } /// The repository `raw` names, by the name it goes by now: a renamed project's /// old name leads to it (hosted.rs `current`), for what was cloned before. fn named(raw: &str) -> Result { Ok(crate::hosted::current(&repo_name(raw)?)) } /// The hub's `authorized_keys` command for nodes. pub fn serve_git(node: &str) -> Result { let cmd = std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default(); match git_ask(&cmd)? { GitAsk::Fetch(repo) => { if !allowed(&repo) { log("git_refused", json!({"node": node, "repo": repo, "why": "not mirrored"})); bail!("{repo} is not mirrored for nodes"); } refresh(&repo)?; log("git_serve", json!({"node": node, "repo": repo})); let err = Command::new("git").args(["upload-pack", &mirror_path(&repo).to_string_lossy()]).exec(); bail!("could not start git upload-pack: {err}") } GitAsk::Lfs(repo, op) => { if op != "download" || !allowed(&repo) { log("git_refused", json!({"node": node, "repo": repo, "why": format!("lfs {op}")})); bail!("only LFS downloads of mirrored repositories"); } let token = issue_token(&repo, node)?; // At the address this node reaches the hub at, which it told the hub. let href = format!("{}/lfs/{repo}/info/lfs", crate::registry::hub_url_of(node).unwrap_or_else(hub_url)); let reply = json!({ "href": href, "header": {"Authorization": format!("Bearer {token}")}, "expires_in": TOKEN_SECS, }); println!("{reply}"); Ok(0) } GitAsk::Transfer => { // Refused on purpose: git-lfs then falls back to git-lfs-authenticate // and the HTTP endpoint, which is the path that caches. eprintln!("git-lfs-transfer is not offered; use git-lfs-authenticate"); Ok(1) } GitAsk::Push => { log("git_refused", json!({"node": node, "why": "push"})); bail!("nodes do not push in this version of midas") } GitAsk::Other(cmd) => { log("git_refused", json!({"node": node, "command": cmd.chars().take(120).collect::()})); bail!("this key may only fetch git and LFS objects") } } } /// The hub's `authorized_keys` command for a person's or an agent's key /// (`hosted::add_key`): fetch any repository the hub serves, push those it /// hosts — main guarded by the repository's pre-receive hook (`hosted::may_push`). pub fn serve_key(name: &str) -> Result { let Some(role) = crate::hosted::role_of(name) else { log("git_refused", json!({"key": name, "why": "no such key"})); bail!("this key is no longer let in"); }; let cmd = std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default(); match git_ask(&cmd)? { GitAsk::Fetch(repo) => { if !allowed(&repo) { bail!("{repo} is not a repository of the workspace"); } refresh(&repo)?; let err = Command::new("git").args(["upload-pack", &mirror_path(&repo).to_string_lossy()]).exec(); bail!("could not start git upload-pack: {err}") } GitAsk::Push => { let (_, rest) = cmd.split_once(' ').unwrap_or((&cmd, "")); let repo = named(rest)?; if !crate::hosted::is_hosted(&repo) { bail!("{repo} is on Forgejo: push it there (only repositories the hub hosts take pushes here)"); } log("git_push", json!({"key": name, "repo": repo})); let err = Command::new("git").args(["receive-pack", &crate::hosted::path(&repo).to_string_lossy()]) .env("MIDAS_GIT_KEY", name).env("MIDAS_GIT_ROLE", &role).exec(); bail!("could not start git receive-pack: {err}") } GitAsk::Lfs(repo, op) => { if !allowed(&repo) || op == "upload" && !crate::hosted::is_hosted(&repo) { bail!("LFS {op} of {repo} is not offered here"); } let token = issue_token_for(&repo, name, &op)?; println!("{}", json!({ "href": format!("{}/lfs/{repo}/info/lfs", hub_url()), "header": {"Authorization": format!("Bearer {token}")}, "expires_in": TOKEN_SECS, })); Ok(0) } GitAsk::Transfer => { eprintln!("git-lfs-transfer is not offered; use git-lfs-authenticate"); Ok(1) } GitAsk::Other(cmd) => { log("git_refused", json!({"key": name, "command": cmd.chars().take(120).collect::()})); bail!("this key may only fetch and push git and LFS objects") } } } fn hub_url() -> String { crate::conf::hub().url() } /// Record an event in the workspace's log. `midas hub git` runs as the `midas` user, /// which cannot write the log on the agent volume (root-only from the host), so /// it goes through the hub's event endpoint as nodes do; `hub serve` (root) falls /// back to writing directly if the endpoint is not answering. pub fn log(kind: &str, mut fields: Value) { fields["kind"] = json!(kind); let posted = crate::hub::request(&hub_url(), "POST", "/v1/events", Some(&fields.to_string())) .map(|(code, _)| code == 204) .unwrap_or(false); if !posted { if let Some(o) = fields.as_object_mut() { o.remove("kind"); } events::emit(kind, fields); } } fn tokens_dir() -> PathBuf { base().join("tokens") } pub fn random_hex(n: usize) -> Result { let mut buf = vec![0u8; n]; let mut f = fs::File::open("/dev/urandom")?; std::io::Read::read_exact(&mut f, &mut buf)?; Ok(buf.iter().map(|b| format!("{b:02x}")).collect()) } fn issue_token(repo: &str, node: &str) -> Result { let t = random_hex(24)?; fs::create_dir_all(tokens_dir())?; let mut f = fs::File::create(tokens_dir().join(&t))?; writeln!(f, "{}", json!({"repo": repo, "node": node}))?; Ok(t) } /// A token for an LFS `op` (`download`, or `upload` to a hosted repository) by /// a person's or an agent's key. fn issue_token_for(repo: &str, key: &str, op: &str) -> Result { let t = random_hex(24)?; fs::create_dir_all(tokens_dir())?; let mut f = fs::File::create(tokens_dir().join(&t))?; writeln!(f, "{}", json!({"repo": repo, "key": key, "op": op}))?; Ok(t) } /// The repository and operation a valid, unexpired token was issued for (a /// node's tokens are downloads). pub fn check_token_op(token: &str) -> Option<(String, String)> { if token.is_empty() || !token.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } let p = tokens_dir().join(token); let age = SystemTime::now().duration_since(fs::metadata(&p).ok()?.modified().ok()?).ok()?; if age > Duration::from_secs(TOKEN_SECS) { let _ = fs::remove_file(&p); return None; } let v: Value = serde_json::from_str(fs::read_to_string(&p).ok()?.trim()).ok()?; Some((v["repo"].as_str()?.to_string(), v["op"].as_str().unwrap_or("download").to_string())) } /// Keep an uploaded LFS object of a hosted repository: `len` bytes from /// `from`, kept only when they hash to `oid`. The cache is the store for those. pub fn store_object(oid: &str, from: &mut impl std::io::Read, len: u64) -> Result<()> { use sha2::{Digest, Sha256}; if !valid_oid(oid) { bail!("not an LFS object id"); } let dest = lfs_cache(oid); fs::create_dir_all(dest.parent().unwrap())?; let tmp = dest.with_extension(format!("part-{}", std::process::id())); let mut f = fs::File::create(&tmp)?; let mut hash = Sha256::new(); let mut left = len; let mut buf = vec![0u8; 1 << 16]; while left > 0 { let want = left.min(buf.len() as u64) as usize; let n = from.read(&mut buf[..want])?; if n == 0 { break; } hash.update(&buf[..n]); f.write_all(&buf[..n])?; left -= n as u64; } let got = data_encoding::HEXLOWER.encode(&hash.finalize()); if left > 0 || got != oid { let _ = fs::remove_file(&tmp); bail!("the upload is not object {oid}"); } f.sync_all()?; fs::rename(&tmp, &dest)?; Ok(()) } /// The repository a valid, unexpired token was issued for. pub fn check_token(token: &str) -> Option { if token.is_empty() || !token.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } let p = tokens_dir().join(token); let age = SystemTime::now().duration_since(fs::metadata(&p).ok()?.modified().ok()?).ok()?; if age > Duration::from_secs(TOKEN_SECS) { let _ = fs::remove_file(&p); return None; } let v: Value = serde_json::from_str(fs::read_to_string(&p).ok()?.trim()).ok()?; v["repo"].as_str().map(str::to_string) } // ─── LFS: the hub's side ───────────────────────────────────────────────────── fn lfs_cache(oid: &str) -> PathBuf { base().join("lfs").join(&oid[0..2]).join(&oid[2..4]).join(oid) } fn valid_oid(oid: &str) -> bool { oid.len() == 64 && oid.bytes().all(|b| b.is_ascii_hexdigit()) } /// Forgejo's LFS endpoint and a header for it, from the deploy key. fn forgejo_lfs(repo: &str) -> Result<(String, String)> { let url = forgejo_ssh(); let hostport = url.trim_start_matches("ssh://"); let (userhost, port) = hostport.rsplit_once(':').unwrap_or((hostport, "22")); let out = Command::new("ssh") .args(["-i", &deploy_key(), "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-o", &format!("UserKnownHostsFile={}/known_hosts", base().display()), "-p", port, userhost, "git-lfs-authenticate", repo, "download"]) .output().context("running ssh to Forgejo for git-lfs-authenticate")?; if !out.status.success() { bail!("git-lfs-authenticate at Forgejo failed: {}", String::from_utf8_lossy(&out.stderr).trim()); } let v: Value = serde_json::from_slice(&out.stdout).context("Forgejo's lfs-authenticate reply")?; let href = v["href"].as_str().context("no href from Forgejo")?.to_string(); let auth = v["header"]["Authorization"].as_str().unwrap_or("").to_string(); Ok((href, auth)) } /// Make sure these objects are in the cache, fetching what is missing from /// Forgejo in one batch. Returns the oids that could not be had. pub fn ensure_cached(repo: &str, objects: &[(String, u64)]) -> Result> { let missing: Vec<&(String, u64)> = objects.iter().filter(|(o, _)| !lfs_cache(o).exists()).collect(); // A hosted repository's objects are uploaded here: what is not, is not anywhere. if crate::hosted::is_hosted(repo) { return Ok(missing.iter().map(|(o, _)| o.clone()).collect()); } if missing.is_empty() { return Ok(vec![]); } let (href, auth) = forgejo_lfs(repo).context("asking Forgejo for LFS access (git-lfs-authenticate)")?; let req = json!({ "operation": "download", "transfers": ["basic"], "objects": missing.iter().map(|(o, s)| json!({"oid": o, "size": s})).collect::>(), }); // The headers on stdin: the token in them would show in `ps` on the command line. let out = crate::util::curl( &["Accept: application/vnd.git-lfs+json".into(), "Content-Type: application/vnd.git-lfs+json".into(), format!("Authorization: {auth}")], &["-sS", "--fail", "-X", "POST", &format!("{href}/objects/batch"), "--data-binary", &req.to_string()], ).context("running curl for the Forgejo LFS batch")?; if !out.status.success() { bail!("Forgejo LFS batch failed: {}", String::from_utf8_lossy(&out.stderr).trim()); } let resp: Value = serde_json::from_slice(&out.stdout)?; let mut failed = Vec::new(); for o in resp["objects"].as_array().into_iter().flatten() { let oid = o["oid"].as_str().unwrap_or("").to_string(); let Some(dl) = o["actions"]["download"].as_object() else { failed.push(oid); continue; }; let url = dl.get("href").and_then(|h| h.as_str()).unwrap_or(""); // The download's own headers carry a token too. let headers: Vec = dl.get("header").and_then(|h| h.as_object()).into_iter().flatten() .map(|(k, v)| format!("{k}: {}", v.as_str().unwrap_or(""))).collect(); let dest = lfs_cache(&oid); fs::create_dir_all(dest.parent().unwrap()).with_context(|| format!("creating {}", dest.parent().unwrap().display()))?; let tmp = dest.with_extension("part"); let ok = crate::util::curl(&headers, &["-sS", "--fail", "-L", url, "-o", &tmp.to_string_lossy()]) .is_ok_and(|o| o.status.success()); if ok && sha256_matches(&tmp, &oid) { fs::rename(&tmp, &dest).with_context(|| format!("moving {} into the cache", tmp.display()))?; } else { let _ = fs::remove_file(&tmp); failed.push(oid); } } log("lfs", json!({ "repo": repo, "fetched": missing.len() - failed.len(), "failed": failed.len(), })); Ok(failed) } fn sha256_matches(path: &Path, oid: &str) -> bool { Command::new("sha256sum") .arg(path) .output() .ok() .map(|o| String::from_utf8_lossy(&o.stdout).split_whitespace().next() == Some(oid)) .unwrap_or(false) } /// Serve a cached object, or `None` if it is not (and could not be) cached. pub fn cached_object(oid: &str) -> Option { if !valid_oid(oid) { return None; } let p = lfs_cache(oid); p.exists().then_some(p) } /// The batch response nodes get: every object they can have points at the hub, /// at the address the request came to (`host`), which is the one the node can reach. pub fn batch(repo: &str, body: &Value, token: &str, host: &str) -> Result { if body["operation"] == "upload" { return batch_upload(repo, body, token, host); } if body["operation"] != "download" { bail!("only downloads"); } let objects: Vec<(String, u64)> = body["objects"] .as_array() .into_iter() .flatten() .filter_map(|o| { let oid = o["oid"].as_str()?; valid_oid(oid).then(|| (oid.to_string(), o["size"].as_u64().unwrap_or(0))) }) .collect(); let failed = ensure_cached(repo, &objects)?; let hub = crate::registry::hub_url_at(host).unwrap_or_else(hub_url); Ok(json!({ "transfer": "basic", "objects": objects.iter().map(|(oid, size)| { if failed.contains(oid) { json!({"oid": oid, "size": size, "error": {"code": 404, "message": "not available from Forgejo"}}) } else { json!({"oid": oid, "size": size, "authenticated": true, "actions": {"download": { "href": format!("{hub}/lfs/objects/{oid}"), "header": {"Authorization": format!("Bearer {token}")}, "expires_in": TOKEN_SECS, }}}) } }).collect::>(), })) } /// An upload to a hosted repository, with a token issued for one: each object /// the store lacks gets a PUT to the hub; one it has, none. fn batch_upload(repo: &str, body: &Value, token: &str, host: &str) -> Result { if !crate::hosted::is_hosted(repo) || check_token_op(token).map(|(_, op)| op).as_deref() != Some("upload") { bail!("uploads go only to a repository the hub hosts, with an upload token"); } let hub = crate::registry::hub_url_at(host).unwrap_or_else(hub_url); let objects: Vec = body["objects"].as_array().into_iter().flatten().filter_map(|o| { let oid = o["oid"].as_str().filter(|o| valid_oid(o))?; let size = o["size"].as_u64().unwrap_or(0); Some(if lfs_cache(oid).exists() { json!({"oid": oid, "size": size, "authenticated": true}) } else { json!({"oid": oid, "size": size, "authenticated": true, "actions": {"upload": { "href": format!("{hub}/lfs/objects/{oid}"), "header": {"Authorization": format!("Bearer {token}")}, "expires_in": TOKEN_SECS, }}}) }) }).collect(); Ok(json!({"transfer": "basic", "objects": objects})) } #[cfg(test)] mod tests { use super::*; #[test] fn a_repository_name_is_two_plain_segments_and_nothing_that_walks_out() { for (raw, want) in [ ("acme/cartopolis", Some("acme/cartopolis.git")), ("acme/cartopolis.git", Some("acme/cartopolis.git")), ("'/acme/cartopolis.git'", Some("acme/cartopolis.git")), ("\"acme/carto_polis-2\"", Some("acme/carto_polis-2.git")), (" a/b ", Some("a/b.git")), ("sam", None), ("a/b/c", None), ("../b", None), ("a/..", None), ("a/.git", None), ("a/.hidden", None), ("a//b", None), ("a/b c", None), ("a/b;rm", None), ("", None), ] { assert_eq!(repo_name(raw).ok().as_deref(), want, "{raw:?}"); } } #[test] fn a_nodes_key_may_fetch_and_ask_for_lfs_and_nothing_else() { let fetch = |r: &str| Ok::<_, ()>(GitAsk::Fetch(r.into())); for (cmd, want) in [ ("git-upload-pack 'acme/cartopolis.git'", fetch("acme/cartopolis.git")), ("git-upload-pack '/acme/cartopolis'", fetch("acme/cartopolis.git")), ("git-lfs-authenticate acme/cartopolis.git download", Ok(GitAsk::Lfs("acme/cartopolis.git".into(), "download".into()))), ("git-lfs-authenticate acme/cartopolis.git upload", Ok(GitAsk::Lfs("acme/cartopolis.git".into(), "upload".into()))), ("git-lfs-authenticate acme/cartopolis.git", Ok(GitAsk::Lfs("acme/cartopolis.git".into(), "download".into()))), ("git-lfs-transfer acme/cartopolis.git download", Ok(GitAsk::Transfer)), ("git-receive-pack 'acme/cartopolis.git'", Ok(GitAsk::Push)), ("sh -c id", Ok(GitAsk::Other("sh -c id".into()))), ("", Ok(GitAsk::Other(String::new()))), ("git-upload-pack '../../etc'", Err(())), ("git-upload-pack 'a/b/../../c'", Err(())), ("git-lfs-authenticate ../x download", Err(())), ] { assert_eq!(git_ask(cmd).map_err(|_| ()), want, "{cmd:?}"); } } }