garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/hosted.rs

raw

//! Repositories the hub hosts itself, in place of Forgejo, for new projects
//! (docs/git-hosting.md, step 1). Each is a bare repository in the state
//! directory, `git/<owner>/<name>.git`, described in `hosted.json` beside it:
//! its visibility, its description, who made it, and its project's landing
//! settings, which `conf::hub` adds to hub.conf's `repos` and `projects` so
//! every reader of those sees a hosted project as any other.
//!
//! Git goes over the hub's ssh login (`midas hub git --key <name>`), by key.
//! A key is the person's (`person`: everything) or an agent's (`agent`: every
//! branch but main, and main only from a landing: the turn to land held, a
//! fast-forward, the gate's pass on record for the new head — what the land
//! script did by convention, here the server's rule). Nodes fetch as they
//! fetch a mirror. Public repositories are also read without a login over HTTPS
//! (`hub::public_git`); private ones never.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};
use serde_json::{json, Map, Value};

use crate::{registry, store};

pub fn root() -> PathBuf {
    registry::root().join("git")
}

fn file() -> PathBuf {
    registry::root().join("hosted.json")
}

/// `owner/name` (no `.git`): the key every list in hub.conf uses.
fn key(repo: &str) -> String {
    repo.trim_end_matches(".git").to_string()
}

/// The bare repository of `repo` (`owner/name` or `owner/name.git`).
pub fn path(repo: &str) -> PathBuf {
    root().join(format!("{}.git", key(repo)))
}

fn read() -> Value {
    store::read::<Value>(&file()).unwrap_or_else(|| json!({}))
}

/// Every hosted repository, `owner/name` → its record.
pub fn repos() -> Map<String, Value> {
    read()["repos"].as_object().cloned().unwrap_or_default()
}

pub fn get(repo: &str) -> Option<Value> {
    repos().get(&key(repo)).cloned()
}

pub fn is_hosted(repo: &str) -> bool {
    get(repo).is_some()
}

pub fn is_public(repo: &str) -> bool {
    get(repo).is_some_and(|r| r["visibility"] == "public")
}

fn update<R>(f: impl FnOnce(&mut Value) -> Result<R>) -> Result<R> {
    store::update(file(), |v: &mut Value| {
        store::objects(v, &["repos", "keys"]);
        f(v)
    })
}

fn git(dir: &Path, args: &[&str]) -> Result<String> {
    let out = Command::new("git").arg("-C").arg(dir).args(args)
        .env("GIT_AUTHOR_NAME", "midas").env("GIT_AUTHOR_EMAIL", "midas@localhost")
        .env("GIT_COMMITTER_NAME", "midas").env("GIT_COMMITTER_EMAIL", "midas@localhost")
        .output().with_context(|| format!("running git {}", args.join(" ")))?;
    if !out.status.success() {
        bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

fn git_in(dir: &Path, args: &[&str], stdin: &str) -> Result<String> {
    use std::io::Write;
    let mut child = Command::new("git").arg("-C").arg(dir).args(args)
        .stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped())
        .spawn()?;
    child.stdin.take().unwrap().write_all(stdin.as_bytes())?;
    let out = child.wait_with_output()?;
    if !out.status.success() {
        bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// What a new project says of itself.
pub struct New<'a> {
    pub owner: &'a str,
    pub name: &'a str,
    pub description: &'a str,
    pub public: bool,
    pub gate: Option<&'a str>,
    pub gate_nodes: Option<&'a str>,
    pub by: &'a str,
}

/// Make a repository and its project: a bare repository with a first commit on
/// `main` (a README of its name and description, so a session's worktree has a
/// main to branch from), the hooks that guard and report pushes, and its record.
/// A name hub.conf already has (a Forgejo project) is refused.
pub fn create(n: &New) -> Result<Value> {
    let repo = crate::mirror::repo_name(&format!("{}/{}", n.owner, n.name))?;
    let k = key(&repo);
    if crate::conf::read(Path::new(&conf_path()))?.unwrap_or_default().repos.iter().any(|r| key(r) == k) {
        bail!("{k} is already a project of the workspace, on Forgejo");
    }
    let dir = path(&repo);
    if dir.exists() || is_hosted(&k) {
        bail!("{k} is already hosted here");
    }
    fs::create_dir_all(dir.parent().unwrap())?;
    let made = (|| -> Result<()> {
        init_bare(&dir)?;
        let readme = format!("# {}\n\n{}\n", n.name, n.description.trim());
        let blob = git_in(&dir, &["hash-object", "-w", "--stdin"], &readme)?;
        let tree = git_in(&dir, &["mktree"], &format!("100644 blob {blob}\tREADME.md\n"))?;
        let commit = git(&dir, &["commit-tree", &tree, "-m", &format!("Start {}", n.name)])?;
        git(&dir, &["update-ref", "refs/heads/main", &commit])?;
        Ok(())
    })();
    if let Err(e) = made {
        let _ = fs::remove_dir_all(&dir);
        return Err(e);
    }
    let mut project = json!({});
    if let Some(g) = n.gate.filter(|g| !g.trim().is_empty()) {
        project["gate"] = json!(g);
    }
    if let Some(g) = n.gate_nodes.filter(|g| !g.trim().is_empty()) {
        project["gate_nodes"] = json!(g);
    }
    let record = json!({
        "visibility": if n.public { "public" } else { "private" },
        "description": n.description.trim(),
        "created_by": n.by, "created_at": registry::now(),
        "project": project,
    });
    update(|v| {
        v["repos"][&k] = record.clone();
        // An old name of a renamed project, taken for a new one: it leads here now.
        if let Some(r) = v["renamed"].as_object_mut() {
            r.remove(&k);
        }
        Ok(())
    })?;
    crate::events::emit("repo_created", json!({"repo": k, "actor": n.by, "visibility": record["visibility"]}));
    Ok(json!({"repo": k, "url": url(&k), "visibility": record["visibility"]}))
}

/// An empty bare repository with the settings and hooks every hosted one has.
fn init_bare(dir: &Path) -> Result<()> {
    // Not "." (git -C runs there first): `sudo -u midas midas hub import` starts in
    // the caller's home, which the hub's user cannot enter.
    git(Path::new("/"), &["init", "--quiet", "--bare", "--initial-branch=main", &dir.to_string_lossy()])?;
    for (k, v) in [("receive.advertisePushOptions", "true"), ("uploadpack.allowFilter", "true"),
                   ("receive.fsckObjects", "true"), ("core.logAllRefUpdates", "true")] {
        git(dir, &["config", k, v])?;
    }
    install_hooks(dir)
}

/// Where an import takes a repository from, when not Forgejo over ssh.
#[derive(Default)]
pub struct Source<'a> {
    /// A URL or path git fetches: Forgejo's own copy on disk, staged where the
    /// hub's user can read it, for a repository the mirror's key does not open.
    pub git: Option<&'a str>,
    /// A directory of LFS objects laid out as Forgejo keeps them (`ab/cd/ef…`).
    pub lfs: Option<&'a Path>,
}

/// Take a project over from Forgejo (docs/git-hosting.md, step 2), on the hub as
/// its user (`midas hub import`): its branches and tags, fetched fresh from
/// Forgejo with the mirror's key (or from `from.git`); every LFS object any of
/// them names, into the store, from Forgejo (or `from.lfs`) where the store
/// lacks it; and its landing as hub.conf has it, which from then on is the
/// hub's to keep (a hosted record's landing outranks hub.conf's; its deploys
/// stay hub.conf's). A repository hub.conf does not name comes without a
/// landing. Forgejo's copy is left as it was: closing it to pushes is a step of
/// the move of its own (docs/hub.md).
///
/// Objects that cannot be had are named in the answer, not a failure: an old
/// branch can point at one that was never uploaded.
pub fn import(repo: &str, public: bool, description: &str, from: &Source, by: &str) -> Result<Value> {
    let repo = crate::mirror::repo_name(repo)?;
    let k = key(&repo);
    let conf: Value = fs::read_to_string(conf_path()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(json!({}));
    let dir = path(&repo);
    if dir.exists() || is_hosted(&k) {
        bail!("{k} is already hosted here");
    }
    let source = from.git.map(str::to_string).unwrap_or_else(|| format!("{}/{repo}", crate::mirror::forgejo_ssh()));
    fs::create_dir_all(dir.parent().unwrap())?;
    let made = (|| -> Result<(usize, Vec<String>)> {
        init_bare(&dir)?;
        let out = Command::new("git").arg("-C").arg(&dir)
            .args(["fetch", "--quiet", "--no-tags", &source, "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"])
            .env("GIT_SSH_COMMAND", crate::mirror::git_ssh()).output()?;
        if !out.status.success() {
            bail!("fetching {k} from {source}: {}", String::from_utf8_lossy(&out.stderr).trim());
        }
        let objects = lfs_pointers(&dir)?;
        let missing = match from.lfs {
            Some(store) => objects.iter().filter(|(oid, size)| {
                if crate::mirror::cached_object(oid).is_some() {
                    return false;
                }
                let f = store.join(&oid[0..2]).join(&oid[2..4]).join(&oid[4..]);
                !fs::File::open(f).is_ok_and(|mut f| crate::mirror::store_object(oid, &mut f, *size).is_ok())
            }).map(|(oid, _)| oid.clone()).collect(),
            None => crate::mirror::ensure_cached(&repo, &objects)?,
        };
        Ok((objects.len(), missing))
    })();
    let (lfs, missing) = match made {
        Ok(m) => m,
        Err(e) => {
            let _ = fs::remove_dir_all(&dir);
            return Err(e);
        }
    };
    let head = git(&dir, &["rev-parse", "--verify", "--quiet", "refs/heads/main"]).unwrap_or_default();
    // Its landing comes along; its deploys stay in hub.conf, root's to trust (conf::hub).
    let mut project = conf["projects"].get(&k).filter(|p| p.is_object()).cloned().unwrap_or(json!({}));
    project.as_object_mut().map(|p| p.remove("deploy"));
    let record = json!({
        "visibility": if public { "public" } else { "private" },
        "description": description.trim(),
        "created_by": by, "created_at": registry::now(),
        "imported_from": source,
        "project": project,
    });
    update(|v| {
        v["repos"][&k] = record.clone();
        Ok(())
    })?;
    crate::events::emit("repo_imported", json!({"repo": k, "actor": by, "visibility": record["visibility"],
                                                 "lfs": lfs, "lfs_missing": missing.len()}));
    Ok(json!({"repo": k, "url": url(&k), "visibility": record["visibility"], "main": head,
              "branches": git(&dir, &["for-each-ref", "--format=%(refname)", "refs/heads"])?.lines().count(),
              "lfs_objects": lfs, "lfs_missing": missing}))
}

/// Every LFS object a branch or tag of `dir` names: the blobs small enough to
/// be a pointer that read as one.
pub(crate) fn lfs_pointers(dir: &Path) -> Result<Vec<(String, u64)>> {
    use std::io::{BufRead, Read};
    use std::process::Stdio;
    // %(rest): without it, the path rev-list prints after a blob is read as part of its name.
    let mut list = Command::new("sh").arg("-c")
        .arg("git rev-list --all --objects | git cat-file --batch-check='%(objecttype) %(objectsize) %(objectname) %(rest)'")
        .current_dir(dir).stdout(Stdio::piped()).spawn()?;
    let small: Vec<String> = std::io::BufReader::new(list.stdout.take().unwrap()).lines().map_while(|l| l.ok())
        .filter_map(|l| {
            let mut w = l.split_whitespace();
            (w.next()? == "blob" && w.next()?.parse::<u64>().ok()? < 1024).then(|| w.next().map(str::to_string)).flatten()
        }).collect();
    if !list.wait()?.success() {
        bail!("listing the objects of {}", dir.display());
    }
    let mut cat = Command::new("git").arg("-C").arg(dir).args(["cat-file", "--batch"])
        .stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?;
    let mut input = cat.stdin.take().unwrap();
    let feeder = std::thread::spawn(move || {
        use std::io::Write;
        for o in small {
            let _ = writeln!(input, "{o}");
        }
    });
    let mut out = std::io::BufReader::new(cat.stdout.take().unwrap());
    let mut found = std::collections::BTreeMap::new();
    let mut head = String::new();
    while out.read_line(&mut head)? > 0 {
        let size: usize = head.split_whitespace().nth(2).and_then(|s| s.parse().ok()).unwrap_or(0);
        let mut body = vec![0u8; size + 1];
        out.read_exact(&mut body)?;
        head.clear();
        let text = String::from_utf8_lossy(&body);
        if !text.starts_with("version https://git-lfs") {
            continue;
        }
        let oid = text.lines().find_map(|l| l.strip_prefix("oid sha256:")).map(str::trim);
        let len = text.lines().find_map(|l| l.strip_prefix("size ")).and_then(|s| s.trim().parse().ok());
        if let (Some(o), Some(n)) = (oid, len) {
            found.insert(o.to_string(), n);
        }
    }
    let _ = feeder.join();
    cat.wait()?;
    Ok(found.into_iter().collect())
}

fn conf_path() -> String {
    std::env::var("MIDAS_HUB_CONF").ok().filter(|p| !p.is_empty()).unwrap_or_else(|| crate::conf::HUB_CONF.to_string())
}

/// The hooks every hosted repository runs: they hand over to this binary.
fn install_hooks(dir: &Path) -> Result<()> {
    // The hub's own binary (/usr/local/bin/midas on the hub; a scratch hub's own in tests/e2e).
    let bin = std::env::current_exe().ok()
        .map_or_else(|| crate::hubsetup::BIN.to_string(), |p| p.display().to_string());
    for hook in ["pre-receive", "post-receive"] {
        let f = dir.join("hooks").join(hook);
        fs::write(&f, format!("#!/bin/sh\n# midas: {hook} for a repository the hub hosts (src/hosted.rs).\nexec {bin} hub {hook}\n"))?;
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&f, fs::Permissions::from_mode(0o755))?;
    }
    Ok(())
}

/// Where clients in the workspace push and fetch: the hub's ssh login, by key.
pub fn url(repo: &str) -> String {
    format!("midas@{}:{}.git", crate::conf::hub().ip(), key(repo))
}

/// Change a project's landing settings or description. `public` changes its
/// visibility, which only the person may make public (`by_person`): publishing
/// a private repository is outward-facing and not undone by turning it back.
pub fn set(repo: &str, fields: &Value, by: &str, by_person: bool) -> Result<Value> {
    let k = key(repo);
    let out = update(|v| {
        let Some(r) = v["repos"].get_mut(&k) else { bail!("{k} is not hosted here") };
        for f in ["gate", "gate_nodes", "pre_land", "main"] {
            match fields.get(f) {
                Some(Value::String(s)) if !s.trim().is_empty() => r["project"][f] = json!(s),
                Some(Value::String(_)) | Some(Value::Null) => {
                    if let Some(o) = r["project"].as_object_mut() {
                        o.remove(f);
                    }
                }
                _ => {}
            }
        }
        if let Some(d) = fields["description"].as_str() {
            r["description"] = json!(d.trim());
        }
        if let Some(p) = fields["public"].as_bool() {
            if p && r["visibility"] != "public" && !by_person {
                bail!("making {k} public is the person's to do: ask them, and they make it public on the page");
            }
            r["visibility"] = json!(if p { "public" } else { "private" });
        }
        Ok(r.clone())
    })?;
    crate::events::emit("repo_changed", json!({"repo": k, "actor": by, "fields": fields}));
    Ok(out)
}

// ── Renaming and deleting ────────────────────────────────────────────────────

/// The name `repo` goes by now: itself, or the project it was renamed to
/// (hosted.json `renamed`, old → new), so a clone, a worktree's origin or a
/// node's checkout made under the old name keeps fetching and pushing. A
/// project hosted under the name outranks an old name of another. `.git` is
/// kept as given.
pub fn current(repo: &str) -> String {
    let k = key(repo);
    let v = read();
    if v["repos"].get(&k).is_some() {
        return repo.to_string();
    }
    match v["renamed"][&k].as_str() {
        Some(now) if repo.ends_with(".git") => format!("{now}.git"),
        Some(now) => now.to_string(),
        None => repo.to_string(),
    }
}

/// Every old name that still leads somewhere: (old, new).
pub fn renames() -> Vec<(String, String)> {
    read()["renamed"].as_object().into_iter().flatten()
        .filter_map(|(o, n)| Some((o.clone(), n.as_str()?.to_string()))).collect()
}

/// A name hub.conf itself gives `k` (a project from its Forgejo days, or one
/// with deploys): hub.conf is root's, which the hub's user does not write.
fn named_by_hub_conf(k: &str) -> Result<bool> {
    let c = crate::conf::read(Path::new(&conf_path()))?.unwrap_or_default();
    Ok(c.repos.iter().any(|r| key(r) == k) || c.projects.keys().any(|r| key(r) == k))
}

/// `repo` under the name `to` (`name`, or `owner/name` for another owner):
/// its bare repository moved, its record and landing with it, and every
/// session, goal and note set that names it changed to say the new name. The
/// old name stays an alias (`current`), so what was cloned from it goes on
/// working; runners move their checkouts to the new name at their next poll
/// (sessions.rs `follow_renames`). A project hub.conf names is refused: its
/// entries are root's to change.
pub fn rename(repo: &str, to: &str, by: &str) -> Result<Value> {
    let from = key(&crate::mirror::repo_name(repo)?);
    let owner = from.split('/').next().unwrap_or_default();
    let to = to.trim();
    let new = key(&crate::mirror::repo_name(&if to.contains('/') { to.to_string() } else { format!("{owner}/{to}") })?);
    if !is_hosted(&from) {
        bail!("{from} is not hosted here");
    }
    if new == from {
        bail!("{from} is called that already");
    }
    if is_hosted(&new) || path(&new).exists() {
        bail!("{new} is a project already");
    }
    for k in [&from, &new] {
        if named_by_hub_conf(k)? {
            bail!("hub.conf names {k}, which only root changes: rename it there first (sudo on the hub), then here");
        }
    }
    fs::create_dir_all(path(&new).parent().unwrap())?;
    fs::rename(path(&from), path(&new)).with_context(|| format!("moving {} to {}", path(&from).display(), path(&new).display()))?;
    let moved = update(|v| {
        store::objects(v, &["renamed"]);
        let Some(mut r) = v["repos"].as_object_mut().and_then(|m| m.remove(&from)) else { bail!("{from} is not hosted here") };
        let mut was: Vec<Value> = r["renamed_from"].as_array().cloned().unwrap_or_default();
        was.push(json!({"name": from, "at": registry::now(), "by": by}));
        r["renamed_from"] = json!(was);
        v["repos"][&new] = r;
        let renamed = v["renamed"].as_object_mut().expect("an object");
        // The new name was this one's before (a rename undone): it is no alias any more.
        renamed.remove(&new);
        for n in renamed.values_mut() {
            if n == from.as_str() {
                *n = json!(new);
            }
        }
        renamed.insert(from.clone(), json!(new));
        Ok(())
    });
    if let Err(e) = moved {
        let _ = fs::rename(path(&new), path(&from));
        return Err(e);
    }
    let sessions = crate::sessions::repo_renamed(&from, Some(&new))?;
    crate::tree::repo_renamed(&from, Some(&new))?;
    crate::memory::rename_set(&from, &new)?;
    crate::events::emit("repo_renamed", json!({"repo": new, "from": from, "actor": by, "sessions": sessions}));
    Ok(json!({"repo": new, "from": from, "url": url(&new), "sessions": sessions, "public": is_public(&new)}))
}

/// Delete `repo`, which only the person does (`by_person`): it loses every
/// branch nobody else has. Its bare repository is moved aside, out of every
/// listing and serving (`deleted-git/<owner>/<name>-<when>.git` in the state
/// directory), where the hub's user can put it back or remove it for good;
/// its record goes to hosted.json `deleted`, and sessions and goals stop
/// naming it. Its LFS objects stay in the store, which repositories share.
pub fn delete(repo: &str, by: &str, by_person: bool) -> Result<Value> {
    let k = key(&crate::mirror::repo_name(repo)?);
    if !by_person {
        bail!("deleting {k} loses what is only there: it is the person's to do. Ask them; they delete it on the page \
               (Map ▸ {} ▸ Settings ▸ Delete)", k.rsplit('/').next().unwrap_or(&k));
    }
    if !is_hosted(&k) {
        bail!("{k} is not hosted here");
    }
    if named_by_hub_conf(&k)? {
        bail!("hub.conf names {k}, which only root changes: take it out there first (sudo on the hub), then delete it here");
    }
    let at = registry::now();
    let kept = registry::root().join("deleted-git").join(format!("{k}-{at}.git"));
    fs::create_dir_all(kept.parent().unwrap())?;
    fs::rename(path(&k), &kept).with_context(|| format!("moving {} aside", path(&k).display()))?;
    let head = git(&kept, &["rev-parse", "--verify", "--quiet", "HEAD"]).unwrap_or_default();
    let moved = update(|v| {
        store::objects(v, &["renamed", "deleted"]);
        let Some(r) = v["repos"].as_object_mut().and_then(|m| m.remove(&k)) else { bail!("{k} is not hosted here") };
        v["renamed"].as_object_mut().expect("an object").retain(|_, n| n != k.as_str());
        v["deleted"][format!("{k}@{at}")] = json!({"repo": k, "at": at, "by": by, "kept": kept, "head": head, "record": r});
        Ok(())
    });
    if let Err(e) = moved {
        let _ = fs::rename(&kept, path(&k));
        return Err(e);
    }
    let sessions = crate::sessions::repo_renamed(&k, None)?;
    crate::tree::repo_renamed(&k, None)?;
    crate::events::emit("repo_deleted", json!({"repo": k, "actor": by, "kept": kept, "head": head, "sessions": sessions}));
    Ok(json!({"repo": k, "deleted": true, "kept": kept, "head": head, "sessions": sessions}))
}

/// `from` as `to` (or gone, with `None`) in a record of the hub's: every
/// `repo` that names it, and every `repos` list. A deleted project's `repo`
/// stays, as history of what a session worked in; it leaves the lists that
/// say what one works in now. Whether anything changed.
pub(crate) fn rename_in(v: &mut Value, from: &str, to: Option<&str>) -> bool {
    let mut changed = false;
    match v {
        Value::Object(o) => {
            for (k, x) in o.iter_mut() {
                match (k.as_str(), &mut *x, to) {
                    ("repo", Value::String(s), Some(to)) if s == from => {
                        *s = to.to_string();
                        changed = true;
                    }
                    ("repos", Value::Array(a), _) if a.iter().any(|r| r == from) => {
                        match to {
                            Some(to) => a.iter_mut().filter(|r| *r == from).for_each(|r| *r = json!(to)),
                            None => a.retain(|r| r != from),
                        }
                        // Renamed onto one it had already: once.
                        let mut seen = std::collections::HashSet::new();
                        a.retain(|r| seen.insert(r.to_string()));
                        changed = true;
                    }
                    _ => changed |= rename_in(x, from, to),
                }
            }
        }
        Value::Array(a) => for x in a {
            changed |= rename_in(x, from, to);
        },
        _ => {}
    }
    changed
}

// ── Keys ─────────────────────────────────────────────────────────────────────

pub fn keys() -> Map<String, Value> {
    read()["keys"].as_object().cloned().unwrap_or_default()
}

pub fn role_of(name: &str) -> Option<String> {
    keys().get(name).and_then(|k| k["role"].as_str()).map(str::to_string)
}

/// Let a key push and fetch hosted repositories: `role` is `person` or `agent`.
/// Run on the hub (`midas hub git-key add`); the hub's `authorized_keys` is
/// rewritten from the list.
pub fn add_key(name: &str, role: &str, key: &str, by: &str) -> Result<()> {
    if !matches!(role, "person" | "agent") {
        bail!("a key is a person's or an agent's, not {role:?}");
    }
    if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || "-_".contains(c)) {
        bail!("a key's name is letters, digits, - and _: {name:?}");
    }
    let key = key.trim();
    let parts: Vec<&str> = key.split_whitespace().collect();
    if parts.len() < 2 || !parts[0].starts_with("ssh-") && !parts[0].starts_with("ecdsa-") || key.contains(['"', '\n']) {
        bail!("not an ssh public key: {key:?}");
    }
    let line = format!("{} {}", parts[0], parts[1]);
    update(|v| {
        v["keys"][name] = json!({"key": line, "role": role, "by": by, "at": registry::now()});
        Ok(())
    })?;
    crate::events::emit("git_key_added", json!({"name": name, "role": role, "actor": by}));
    Ok(())
}

pub fn remove_key(name: &str, by: &str) -> Result<bool> {
    let had = update(|v| Ok(v["keys"].as_object_mut().and_then(|k| k.remove(name)).is_some()))?;
    if had {
        crate::events::emit("git_key_removed", json!({"name": name, "actor": by}));
    }
    Ok(had)
}

/// The `authorized_keys` lines for the keys: each may run git, and nothing else.
pub fn authorized_lines(bin: &str) -> String {
    keys().iter().filter_map(|(name, k)| {
        Some(format!("restrict,command=\"{bin} hub git --key {name}\" {} midas-key-{name}\n", k["key"].as_str()?))
    }).collect()
}

// ── Pushes ───────────────────────────────────────────────────────────────────

const ZERO: &str = "0000000000000000000000000000000000000000";

/// One ref a push moves.
pub struct Update<'a> {
    pub old: &'a str,
    pub new: &'a str,
    pub refname: &'a str,
}

/// May `role` make these updates to `repo`? `owner` is the session the push
/// says it lands for (`git push -o midas-owner=<session>`). The person may do
/// anything. An agent may move any branch but main, and main only forward,
/// from the session holding the turn to land, to a head the gate passed.
pub fn may_push(role: &str, owner: Option<&str>, repo: &str, updates: &[Update]) -> std::result::Result<(), String> {
    if role == "person" {
        return Ok(());
    }
    if role != "agent" {
        return Err(format!("a {role:?} key does not push"));
    }
    let main = crate::conf::hub().project(&key(repo)).and_then(|p| p["main"].as_str().map(str::to_string))
        .unwrap_or_else(|| "main".into());
    let main_ref = format!("refs/heads/{main}");
    for u in updates {
        if u.refname != main_ref {
            continue;
        }
        if u.new == ZERO {
            return Err(format!("{main} is never deleted by an agent"));
        }
        if u.old == ZERO {
            return Err(format!("{main} exists already; an agent moves it only forward"));
        }
        let dir = path(repo);
        let forward = Command::new("git").arg("-C").arg(&dir).args(["merge-base", "--is-ancestor", u.old, u.new])
            .status().is_ok_and(|s| s.success());
        if !forward {
            return Err(format!("{main} moves only forward: {} is not on top of {}", &u.new[..8], &u.old[..8]));
        }
        let Some(owner) = owner else {
            return Err(format!("{main} is moved by a landing: land with the finish-branch skill, which says whose it is"));
        };
        let holder = registry::land_holder();
        if holder.as_deref() != Some(owner) {
            return Err(format!("{owner} does not hold the turn to land (`midas land status`); {main} moves only for the landing that does"));
        }
        if crate::deploy::verification(u.new).is_none() {
            return Err(format!("no gate pass is on record for {}: run the gate (land --verify-only), then land", &u.new[..8]));
        }
    }
    Ok(())
}

/// `midas hub pre-receive`, in a hosted repository: git hands it the updates
/// on stdin; the key's role comes from `hub git --key` in the environment.
pub fn pre_receive() -> Result<i32> {
    use std::io::Read;
    let mut text = String::new();
    std::io::stdin().read_to_string(&mut text)?;
    let role = std::env::var("MIDAS_GIT_ROLE").unwrap_or_default();
    let name = std::env::var("MIDAS_GIT_KEY").unwrap_or_default();
    let options: Vec<String> = (0..std::env::var("GIT_PUSH_OPTION_COUNT").ok().and_then(|n| n.parse().ok()).unwrap_or(0))
        .filter_map(|i| std::env::var(format!("GIT_PUSH_OPTION_{i}")).ok()).collect();
    let owner = options.iter().find_map(|o| o.strip_prefix("midas-owner=")).map(str::to_string);
    let repo = repo_of_cwd()?;
    let updates: Vec<Update> = text.lines().filter_map(|l| {
        let mut w = l.split_whitespace();
        Some(Update { old: w.next()?, new: w.next()?, refname: w.next()? })
    }).collect();
    match may_push(&role, owner.as_deref(), &repo, &updates) {
        Ok(()) => Ok(0),
        Err(why) => {
            crate::mirror::log("git_refused", json!({"repo": repo, "key": name, "why": why}));
            eprintln!("midas: {why}");
            Ok(1)
        }
    }
}

/// `midas hub post-receive`: tell the hub what moved, as Forgejo's hook did.
pub fn post_receive() -> Result<i32> {
    use std::io::Read;
    let mut text = String::new();
    std::io::stdin().read_to_string(&mut text)?;
    let repo = repo_of_cwd()?;
    let refs: Vec<Value> = text.lines().filter_map(|l| {
        let mut w = l.split_whitespace();
        Some(json!({"old": w.next()?, "new": w.next()?, "ref": w.next()?}))
    }).collect();
    let _ = crate::hub::request(&crate::conf::hub().url(), "POST", "/v1/pushed",
        Some(&json!({"repo": format!("{repo}.git"), "refs": refs}).to_string()));
    Ok(0)
}

/// `owner/name` of the bare repository a hook runs in.
fn repo_of_cwd() -> Result<String> {
    let dir = std::env::current_dir()?;
    let rel = dir.strip_prefix(root()).with_context(|| format!("{} is not a hosted repository", dir.display()))?;
    Ok(key(&rel.to_string_lossy()))
}

// ── Reading ──────────────────────────────────────────────────────────────────

/// A file's or a directory's contents at `rev` (default the main branch): a
/// directory as its entries, a file as text (or a note that it is binary).
pub fn show(repo: &str, rev: Option<&str>, file: &str) -> Result<Value> {
    let dir = path(repo);
    let rev = rev.filter(|r| !r.is_empty()).unwrap_or("HEAD");
    if rev.starts_with('-') || file.starts_with('-') || file.contains("..") {
        bail!("not a revision or a path");
    }
    let file = file.trim_matches('/');
    let spec = format!("{rev}:{file}");
    let kind = git(&dir, &["cat-file", "-t", &spec]).with_context(|| format!("{file:?} is not at {rev}"))?;
    let commit = git(&dir, &["rev-parse", &format!("{rev}^{{commit}}")])?;
    if kind == "tree" {
        let entries: Vec<Value> = git(&dir, &["ls-tree", "-l", &spec])?.lines().filter_map(|l| {
            let (meta, name) = l.split_once('\t')?;
            let m: Vec<&str> = meta.split_whitespace().collect();
            Some(json!({"name": name, "kind": if m.get(1) == Some(&"tree") { "dir" } else { "file" },
                        "size": m.get(3).and_then(|s| s.parse::<u64>().ok())}))
        }).collect();
        return Ok(json!({"repo": key(repo), "commit": commit, "path": file, "kind": "dir", "entries": entries}));
    }
    let out = Command::new("git").arg("-C").arg(&dir).args(["cat-file", "blob", &spec]).output()?;
    let bytes = out.stdout;
    let text = (bytes.len() <= 1 << 20).then(|| String::from_utf8(bytes.clone()).ok()).flatten();
    Ok(json!({"repo": key(repo), "commit": commit, "path": file, "kind": "file", "size": bytes.len(),
              "text": text, "binary": text.is_none()}))
}

/// A file's bytes at `rev` (default the main branch), whatever its size.
pub fn blob(repo: &str, rev: Option<&str>, file: &str) -> Result<Vec<u8>> {
    let rev = rev.filter(|r| !r.is_empty()).unwrap_or("HEAD");
    if rev.starts_with('-') || file.starts_with('-') || file.contains("..") {
        bail!("not a revision or a path");
    }
    let out = Command::new("git").arg("-C").arg(path(repo))
        .args(["cat-file", "blob", &format!("{rev}:{}", file.trim_matches('/'))]).output()?;
    if !out.status.success() {
        bail!("{file:?} is not a file at {rev}");
    }
    Ok(out.stdout)
}

/// The last `n` commits on `rev`, newest first.
pub fn log(repo: &str, rev: Option<&str>, n: usize) -> Result<Vec<Value>> {
    let rev = rev.filter(|r| !r.is_empty()).unwrap_or("HEAD");
    if rev.starts_with('-') {
        bail!("not a revision");
    }
    let out = git(&path(repo), &["log", &format!("-{}", n.min(200)), "--format=%H%x1f%an%x1f%aI%x1f%s", rev, "--"])?;
    Ok(out.lines().filter_map(|l| {
        let f: Vec<&str> = l.split('\x1f').collect();
        Some(json!({"sha": f.first()?, "author": f.get(1)?, "at": f.get(2)?, "subject": f.get(3)?}))
    }).collect())
}

/// The branches, with their heads.
pub fn branches(repo: &str) -> Result<Vec<Value>> {
    let out = git(&path(repo), &["for-each-ref", "--format=%(refname:short)%1f%(objectname)%1f%(committerdate:iso-strict)", "refs/heads"])?;
    Ok(out.lines().filter_map(|l| {
        let f: Vec<&str> = l.split('\x1f').collect();
        Some(json!({"name": f.first()?, "sha": f.get(1)?, "at": f.get(2)?}))
    }).collect())
}

/// One commit: its message and its diff (cut at 200 kB).
pub fn commit(repo: &str, sha: &str) -> Result<Value> {
    if sha.starts_with('-') {
        bail!("not a revision");
    }
    let dir = path(repo);
    let head = git(&dir, &["show", "-s", "--format=%H%x1f%an%x1f%aI%x1f%B", sha])?;
    let f: Vec<&str> = head.splitn(4, '\x1f').collect();
    let mut diff = git(&dir, &["show", "--format=", "--stat", "--patch", sha])?;
    if diff.len() > 200_000 {
        let mut cut = 200_000;
        while !diff.is_char_boundary(cut) {
            cut -= 1;
        }
        diff.truncate(cut);
        diff.push_str("\n… (cut)");
    }
    Ok(json!({"sha": f.first(), "author": f.get(1), "at": f.get(2), "message": f.get(3), "diff": diff}))
}