git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-28T12:17:58Z
feat(hosted): Forgejo's paths and a front page, and moving a project over The hub is to be the workspace's forge at garage44.eu, in place of Forgejo (docs/git-hosting.md, step 2). For that its public face has to answer what Forgejo answered: - A hosted repository is at /<owner>/<name>, as on Forgejo: its pages, a clone at <name>.git, archives, raw files (an LFS file's own bytes), and LFS downloads over HTTPS for public repositories, which a public clone of cartopolis needs. Forgejo's src/, raw/, media/ and commits/ links are sent to the new pages. /git/<owner>/<name> still clones and sends its pages on. - A visitor who is not logged in gets a front page at /: the public projects and a link to log in. A person logged in gets the hub's page. The page itself now says noindex; the repositories' pages do not. - `midas hub import <repo>` takes a project over from Forgejo: every branch and tag, every LFS object they name, and its landing from hub.conf, which the hub's record then outranks. --from and --lfs-from read Forgejo's own copy for the three repositories the mirror's key does not open. A hosted project's deploy targets now come only from hub.conf, never from hosted.json: root publishes them, and the hub's user can write that file.
docs/development.md | 2 +-
docs/git-hosting.md | 7 ++-
docs/hub.md | 50 +++++++++++++---
src/cli.rs | 39 ++++++++++---
src/codeview.rs | 144 +++++++++++++++++++++++++++++++++++++---------
src/conf.rs | 8 ++-
src/hosted.rs | 162 ++++++++++++++++++++++++++++++++++++++++++++++++++--
src/hub.rs | 100 ++++++++++++++++++++++++++++++--
src/main.rs | 23 ++++++++
src/mirror.rs | 2 +-
src/tests.rs | 86 ++++++++++++++++++++++++++--
tests/e2e/hosted.sh | 32 ++++++++---
12 files changed, 579 insertions(+), 76 deletions(-)
diff --git a/docs/development.md b/docs/development.md
index 3a182fc..09019e1 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -114,7 +114,7 @@ Beside the code:
binary; each machine's session-start hook installs its midas's into
`~/.claude` ([usage.md](usage.md#the-shared-skills)).
- **The page's routes**: a proxy in front of the hub that lists paths (Caddy,
- for midas.cartopolis.org) needs any new `/v1/` path the page calls, or the page
+ for garage44.eu) needs any new `/v1/` path the page calls, or the page
gets a bare 404.
`midas check` and `midas status` show which build each machine runs.
diff --git a/docs/git-hosting.md b/docs/git-hosting.md
index 53fd913..b117780 100644
--- a/docs/git-hosting.md
+++ b/docs/git-hosting.md
@@ -2,8 +2,11 @@
Status: **step 1 built** (2026-11-27, session s874): new projects are hosted by
the hub (`midas project create`, docs/hub.md "Projects the hub hosts"), with the
-landing rule on main, LFS uploads, and public pages, clones and archives. The
-existing projects are still on Forgejo. The rest is a proposal.
+landing rule on main, LFS uploads, and public pages, clones and archives.
+**Step 2 under way** (2026-11-28, s885): the public pages, clones, archives and
+LFS are at Forgejo's own paths (`/<owner>/<name>`), with a front page of the
+public projects at `/`, served at garage44.eu; `midas hub import` moves a
+Forgejo project over. The rest is a proposal.
midas hosts the workspace's repositories itself, and Forgejo goes. midas does not
become a forge. It keeps what agents and the one person steering them use, and
diff --git a/docs/hub.md b/docs/hub.md
index 459ad47..d6af962 100644
--- a/docs/hub.md
+++ b/docs/hub.md
@@ -281,15 +281,47 @@ LFS objects are uploaded to the hub, which keeps them in `/srv/midas/lfs`. That
directory is the store for a hosted repository, not a cache.
**A public project** (`--public`; making a private one public later takes the
-person's admin login) is readable by anyone at `/git/<owner>/<name>`:
+person's admin login) is readable by anyone at `/<owner>/<name>`, the paths
+Forgejo had, so old links, `Cargo.toml`'s `git =` and `package.json`'s tarballs
+keep working once the host name points here:
+
+- pages for files, README, log and commits, and `raw/<path>` (an LFS file's own
+ bytes, when the store has them); Forgejo's `src/branch/…`, `raw/…`, `media/…`
+ and `commits/…` are sent to them;
+- `git clone https://<host>/<owner>/<name>.git`, LFS downloads included;
+- `/<owner>/<name>/archive/<rev>.tar.gz`.
+
+A private project answers 404 there, as one that does not exist. Only a hosted
+repository's `<owner>/<name>` matches, so the page's own places never do.
+`/git/<owner>/<name>`, where they were first, still clones, and sends a page
+to its new path. A visitor who is not logged in gets the **front page** at
+`/`: the public projects, and a link to log in; a person logged in gets the
+hub's page there, as before. Caddy passes the GETs with the page; the clone's
+`POST <name>.git/git-upload-pack` and the LFS batch's
+`POST <name>.git/info/lfs/objects/batch` need routes of their own.
+
+**A project on Forgejo moves here** with `midas hub import` (git-hosting.md,
+step 2), on the hub as its user:
-- pages for files, README, log and commits;
-- `git clone https://<host>/git/<owner>/<name>.git`;
-- `/git/<owner>/<name>/archive/<rev>.tar.gz`.
+```bash
+sudo -u midas midas hub import jeroen/fien --public --description "…"
+# a repository the mirror's key does not open: Forgejo's copy, staged readable
+sudo -u midas midas hub import jeroen/mithril --public --from /srv/midas/import/mithril.git \
+ --lfs-from /srv/midas/import/lfs
+```
+
+It brings every branch and tag, every LFS object they name, and the landing
+hub.conf has (gate, gate nodes, pre-land, main), which the hub keeps from
+then on; the deploy targets stay in hub.conf, since root publishes them. It
+leaves Forgejo's copy as it was. The move around it, in order:
-A private project answers 404 there, as one that does not exist. Caddy passes
-`GET /git/*` with the page; the clone's `POST /git/*/git-upload-pack` needs a
-route of its own.
+1. Close the Forgejo repository to pushes, so none lands there after the copy:
+ a `pre-receive.d/midas-moved` hook that prints where it went and exits 1,
+ beside the post-receive one (section 6).
+2. `midas hub import`. It names the LFS objects it could not find; a checkout
+ of a commit that names one lacks that file.
+3. Point checkouts' `origin` at `midas@<hub>:<owner>/<name>.git` until port
+ 2222 is the hub's (git-hosting.md, step 3), when the old URL works again.
## 6. Hear about pushes
@@ -324,7 +356,7 @@ the page when `web/dist/` was built before it (`bun` in `web/`, as above); one
built without says how to build it.
The page is reachable on the WireGuard network, and wherever a reverse proxy
-publishes it (this workspace: `midas.cartopolis.org`, Caddy). Through the proxy
+publishes it (this workspace: `garage44.eu`, Caddy; `midas.cartopolis.org` until 2026-11-28). Through the proxy
it takes a **login**, for reading too — the reads include every node's address
and readings — and a person's login is the only thing that counts there: the
hub knows a proxied request by the `X-Forwarded-*` headers Caddy adds, and
@@ -1221,7 +1253,7 @@ midas account reset ana # lost phone, leaked password: a new s
midas account remove ana
```
-The link is `MIDAS_WEB_URL` (hub.env, e.g. `https://midas.cartopolis.org`) or
+The link is `MIDAS_WEB_URL` (hub.env, e.g. `https://garage44.eu`) or
the hub's address, then `/setup/<token>`. There the person chooses a password
(twelve characters or more), adds the one-time-code secret to an authenticator
app from a QR code, proves it with a first code, and is shown ten recovery
diff --git a/src/cli.rs b/src/cli.rs
index 6156456..58d2f8b 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -902,18 +902,41 @@ pub fn project_act(a: crate::ProjectCmd, owner: &str) -> Result<i32> {
/// `midas hub git-key …`, on the hub as its user: the key list and the
/// `authorized_keys` written from it must stay the hub user's files.
+/// Refuse to change the hub's files as anyone but the hub's user, so they stay its own.
+fn as_hub_user(what: &str) -> Result<()> {
+ let me = std::env::var("USER").unwrap_or_default();
+ let hub_user = std::fs::metadata(crate::hosted::root().parent().unwrap_or(std::path::Path::new("/")))
+ .map(|m| std::os::unix::fs::MetadataExt::uid(&m)).ok();
+ // SAFETY: getuid has no preconditions.
+ if hub_user.is_some_and(|u| u != unsafe { libc::getuid() }) {
+ bail!("run it as the hub's user, so its files stay the hub's: sudo -u midas midas hub {what} … (you are {me:?})");
+ }
+ Ok(())
+}
+
+fn hub_actor() -> String {
+ format!("hub:{}", std::env::var("SUDO_USER").or_else(|_| std::env::var("USER")).unwrap_or_default())
+}
+
+/// `midas hub import`: a Forgejo project into the hub (hosted::import).
+pub fn hub_import(repo: &str, public: bool, description: &str, from: &crate::hosted::Source) -> Result<i32> {
+ as_hub_user("import")?;
+ let v = crate::hosted::import(repo, public, description, from, &hub_actor())?;
+ println!("{}", serde_json::to_string_pretty(&v)?);
+ let missing = v["lfs_missing"].as_array().map_or(0, Vec::len);
+ if missing > 0 {
+ eprintln!("{missing} LFS object(s) Forgejo could not give: a checkout of a commit that names one lacks that file");
+ }
+ eprintln!("next: close it to pushes at Forgejo, and point checkouts' origin at {} (docs/hub.md)", v["url"].as_str().unwrap_or(""));
+ Ok(0)
+}
+
pub fn git_key(c: crate::GitKeyCmd) -> Result<i32> {
use crate::GitKeyCmd as K;
if !matches!(c, K::List) {
- let me = std::env::var("USER").unwrap_or_default();
- let hub_user = std::fs::metadata(crate::hosted::root().parent().unwrap_or(std::path::Path::new("/")))
- .map(|m| std::os::unix::fs::MetadataExt::uid(&m)).ok();
- // SAFETY: getuid has no preconditions.
- if hub_user.is_some_and(|u| u != unsafe { libc::getuid() }) {
- bail!("run it as the hub's user, so its files stay the hub's: sudo -u midas midas hub git-key … (you are {me:?})");
- }
+ as_hub_user("git-key")?;
}
- let by = format!("hub:{}", std::env::var("SUDO_USER").or_else(|_| std::env::var("USER")).unwrap_or_default());
+ let by = hub_actor();
match c {
K::Add { name, role, key } => {
crate::hosted::add_key(&name, &role, &key, &by)?;
diff --git a/src/codeview.rs b/src/codeview.rs
index ecdf76d..dbbcca0 100644
--- a/src/codeview.rs
+++ b/src/codeview.rs
@@ -1,18 +1,33 @@
-//! The pages a public hosted repository is read by, at
-//! `/git/<owner>/<name>/…` (hub.rs `public_git`): files, the README, the log
-//! and one commit. Plain HTML from the server, with no script and no login, so a
-//! reader and a search engine see the same thing. Private repositories never
-//! reach here.
+//! The pages a public hosted repository is read by, at `/<owner>/<name>/…`
+//! (hub.rs `public_git`), the paths Forgejo had, so a link to the old forge
+//! still lands: files, the README, the log and one commit. Plain HTML from the
+//! server, with no script and no login, so a reader and a search engine see the
+//! same thing. Private repositories never reach here. `/git/<owner>/<name>/…`,
+//! where they were first, is sent here.
//!
-//! - `/git/o/n` — the root directory and the README;
-//! - `/git/o/n/tree/<path>?rev=<rev>` — a directory or a file;
-//! - `/git/o/n/log?rev=<rev>` — the last 50 commits;
-//! - `/git/o/n/commit/<sha>` — one commit and its diff.
+//! - `/o/n` — the root directory and the README;
+//! - `/o/n/tree/<path>?rev=<rev>` — a directory or a file;
+//! - `/o/n/raw/<path>?rev=<rev>` — a file's bytes (an LFS file's own, when the hub has them);
+//! - `/o/n/log?rev=<rev>` — the last 50 commits;
+//! - `/o/n/commit/<sha>` — one commit and its diff;
+//! - Forgejo's `src/`, `raw/`, `media/` and `commits/` paths — sent to the above.
+//!
+//! [`front`] is the site's own front page: the public repositories, for a
+//! visitor who is not logged in to the hub.
use anyhow::Result;
use crate::hosted;
+/// What a path answers with.
+pub enum Page {
+ Html(String),
+ /// Somewhere else on the site (a Forgejo path, said the new way).
+ Moved(String),
+ /// A file's bytes.
+ Raw(Vec<u8>),
+}
+
fn esc(s: &str) -> String {
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
}
@@ -22,41 +37,113 @@ fn link(s: &str) -> String {
crate::hub::pct_encode(s).replace("%2F", "/")
}
+const STYLE: &str = "body{font:15px/1.5 system-ui,sans-serif;margin:0 auto;max-width:60rem;padding:1rem;color:#222}\
+ a{color:#1a5fb4;text-decoration:none}a:hover{text-decoration:underline}\
+ header{display:flex;gap:1rem;align-items:baseline;flex-wrap:wrap;border-bottom:1px solid #ddd;margin-bottom:1rem}\
+ header h1{font-size:1.2rem;margin:.4rem 0}pre{background:#f6f6f6;padding:.8rem;overflow:auto;font-size:13px}\
+ table{border-collapse:collapse;width:100%}td{padding:.2rem .5rem;border-bottom:1px solid #eee}\
+ code{background:#f6f6f6;padding:0 .3rem;white-space:nowrap}header code{white-space:normal;overflow-wrap:anywhere}.muted{color:#777}td.muted{white-space:nowrap}\
+ header .end{margin-left:auto}";
+
fn frame(repo: &str, host: &str, title: &str, body: &str) -> String {
let key = repo.trim_end_matches(".git");
format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
- <title>{t} · {k}</title><style>\
- body{{font:15px/1.5 system-ui,sans-serif;margin:0 auto;max-width:60rem;padding:1rem;color:#222}}\
- a{{color:#1a5fb4;text-decoration:none}}a:hover{{text-decoration:underline}}\
- header{{display:flex;gap:1rem;align-items:baseline;flex-wrap:wrap;border-bottom:1px solid #ddd;margin-bottom:1rem}}\
- header h1{{font-size:1.2rem;margin:.4rem 0}}pre{{background:#f6f6f6;padding:.8rem;overflow:auto;font-size:13px}}\
- table{{border-collapse:collapse;width:100%}}td{{padding:.2rem .5rem;border-bottom:1px solid #eee}}\
- code{{background:#f6f6f6;padding:0 .3rem;white-space:nowrap}}header code{{white-space:normal;overflow-wrap:anywhere}}.muted{{color:#777}}td.muted{{white-space:nowrap}}\
- </style></head><body><header><h1><a href=\"/git/{k}\">{k}</a></h1>\
- <a href=\"/git/{k}/log\">log</a><span class=\"muted\">clone: <code>git clone https://{h}/git/{k}.git</code></span></header>\
+ <title>{t} · {k}</title><style>{STYLE}</style></head><body><header><h1><a href=\"/\">{h}</a> / <a href=\"/{k}\">{k}</a></h1>\
+ <a href=\"/{k}/log\">log</a><span class=\"muted\">clone: <code>git clone https://{h}/{k}.git</code></span></header>\
{body}</body></html>",
t = esc(title), k = esc(key), h = esc(host), body = body,
)
}
+/// The front page: every public repository, newest change first, and the way
+/// in to the hub for its people.
+pub fn front(host: &str) -> String {
+ let mut rows: Vec<(String, String, String)> = hosted::repos().into_iter()
+ .filter(|(_, r)| r["visibility"] == "public")
+ .map(|(k, r)| {
+ let at = hosted::log(&k, None, 1).ok().and_then(|l| l.first().and_then(|c| c["at"].as_str().map(str::to_string)))
+ .unwrap_or_default();
+ (k, r["description"].as_str().unwrap_or("").to_string(), at)
+ })
+ .collect();
+ rows.sort_by(|a, b| b.2.cmp(&a.2).then(a.0.cmp(&b.0)));
+ let mut body = "<table>".to_string();
+ for (k, d, at) in &rows {
+ body += &format!("<tr><td><a href=\"/{k}\">{k}</a></td><td>{d}</td><td class=\"muted\">{at}</td></tr>",
+ k = esc(k), d = esc(d), at = esc(at.get(..10).unwrap_or("")));
+ }
+ body += "</table>";
+ if rows.is_empty() {
+ body = "<p class=\"muted\">No public projects yet.</p>".into();
+ }
+ format!(
+ "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
+ <title>{h}</title><style>{STYLE}</style></head><body><header><h1><a href=\"/\">{h}</a></h1>\
+ <span class=\"muted\">projects</span><a class=\"end\" href=\"/login\">log in</a></header>{body}</body></html>",
+ h = esc(host),
+ )
+}
+
fn query(q: &str, k: &str) -> Option<String> {
q.split('&').find_map(|p| p.strip_prefix(&format!("{k}="))).map(crate::hub::pct_decode)
}
-/// The page for `tail` (what follows `/git/<owner>/<name>/`), or none for a
+/// Forgejo's paths, said the new way: `src/branch/<b>/<p>` (and `commit`,
+/// `tag`), `raw/…` and `media/…` likewise, and `commits/branch/<b>`. A branch
+/// name with a `/` in it is read as its first segment, the rest as the path.
+fn forgejo(key: &str, tail: &str) -> Option<String> {
+ let (kind, rest) = tail.split_once('/')?;
+ let to = match kind {
+ "src" => "tree",
+ "raw" | "media" => "raw",
+ "commits" => "log",
+ _ => return None,
+ };
+ let (_, rest) = rest.split_once('/').filter(|(how, _)| matches!(*how, "branch" | "commit" | "tag"))?;
+ let (rev, path) = rest.split_once('/').unwrap_or((rest, ""));
+ if rev.is_empty() {
+ return None;
+ }
+ let path = if to == "log" { String::new() } else { format!("/{path}") };
+ Some(format!("/{key}/{to}{}?rev={rev}", path.trim_end_matches('/')))
+}
+
+/// A file's bytes at `rev`: an LFS pointer is answered with its object, when the
+/// hub's store has it.
+fn raw(repo: &str, rev: Option<&str>, path: &str) -> Result<Option<Vec<u8>>> {
+ let v = hosted::show(repo, rev, path)?;
+ if v["kind"] != "file" {
+ return Ok(None);
+ }
+ let bytes = hosted::blob(repo, rev, path)?;
+ let oid = std::str::from_utf8(&bytes).ok().filter(|t| t.starts_with("version https://git-lfs"))
+ .and_then(|t| t.lines().find_map(|l| l.strip_prefix("oid sha256:")).map(str::trim));
+ if let Some(stored) = oid.and_then(crate::mirror::cached_object) {
+ return Ok(Some(std::fs::read(stored)?));
+ }
+ Ok(Some(bytes))
+}
+
+/// The page for `tail` (what follows `/<owner>/<name>/`), or none for a
/// path that is not one.
-pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<String>> {
+pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<Page>> {
let key = repo.trim_end_matches(".git");
let rev = query(q, "rev");
let revq = rev.as_deref().map(|r| format!("?rev={}", link(r))).unwrap_or_default();
+ if let Some(to) = forgejo(key, tail) {
+ return Ok(Some(Page::Moved(to)));
+ }
+ if let Some(path) = tail.strip_prefix("raw/") {
+ return Ok(raw(repo, rev.as_deref(), &crate::hub::pct_decode(path))?.map(Page::Raw));
+ }
if tail.is_empty() || tail == "tree" || tail.starts_with("tree/") {
let path = crate::hub::pct_decode(tail.strip_prefix("tree").unwrap_or("").trim_start_matches('/'));
let v = hosted::show(repo, rev.as_deref(), &path)?;
let mut body = String::new();
if !path.is_empty() {
let up = path.rsplit_once('/').map(|(u, _)| u).unwrap_or("");
- body += &format!("<p><a href=\"/git/{}/tree/{}{}\">..</a> <span class=\"muted\">/{}</span></p>", esc(key), link(up), revq, esc(&path));
+ body += &format!("<p><a href=\"/{}/tree/{}{}\">..</a> <span class=\"muted\">/{}</span></p>", esc(key), link(up), revq, esc(&path));
}
if v["kind"] == "dir" {
body += "<table>";
@@ -64,7 +151,7 @@ pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<String
let n = e["name"].as_str().unwrap_or("");
let full = if path.is_empty() { n.to_string() } else { format!("{path}/{n}") };
let dir = e["kind"] == "dir";
- body += &format!("<tr><td><a href=\"/git/{}/tree/{}{}\">{}{}</a></td><td class=\"muted\">{}</td></tr>",
+ body += &format!("<tr><td><a href=\"/{}/tree/{}{}\">{}{}</a></td><td class=\"muted\">{}</td></tr>",
esc(key), link(&full), revq, esc(n), if dir { "/" } else { "" },
e["size"].as_u64().map(|s| format!("{s} B")).unwrap_or_default());
}
@@ -78,23 +165,24 @@ pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<String
}
}
} else if let Some(t) = v["text"].as_str() {
- body += &format!("<pre>{}</pre>", esc(t));
+ body += &format!("<p class=\"muted\"><a href=\"/{}/raw/{}{}\">raw</a></p><pre>{}</pre>", esc(key), link(&path), revq, esc(t));
} else {
- body += &format!("<p class=\"muted\">A binary file of {} bytes.</p>", v["size"]);
+ body += &format!("<p class=\"muted\">A binary file of {} bytes: <a href=\"/{}/raw/{}{}\">download</a>.</p>",
+ v["size"], esc(key), link(&path), revq);
}
let title = if path.is_empty() { key.to_string() } else { path.clone() };
- return Ok(Some(frame(repo, host, &title, &body)));
+ return Ok(Some(Page::Html(frame(repo, host, &title, &body))));
}
if tail == "log" {
let mut body = "<table>".to_string();
for c in hosted::log(repo, rev.as_deref(), 50)? {
let sha = c["sha"].as_str().unwrap_or("");
- body += &format!("<tr><td><a href=\"/git/{}/commit/{}\"><code>{}</code></a></td><td>{}</td><td class=\"muted\">{}</td></tr>",
+ body += &format!("<tr><td><a href=\"/{}/commit/{}\"><code>{}</code></a></td><td>{}</td><td class=\"muted\">{}</td></tr>",
esc(key), esc(sha), esc(sha.get(..10).unwrap_or(sha)), esc(c["subject"].as_str().unwrap_or("")),
esc(c["at"].as_str().unwrap_or("").get(..10).unwrap_or("")));
}
body += "</table>";
- return Ok(Some(frame(repo, host, "log", &body)));
+ return Ok(Some(Page::Html(frame(repo, host, "log", &body))));
}
if let Some(sha) = tail.strip_prefix("commit/") {
if !sha.chars().all(|c| c.is_ascii_hexdigit()) {
@@ -104,7 +192,7 @@ pub fn page(repo: &str, host: &str, tail: &str, q: &str) -> Result<Option<String
let body = format!("<p class=\"muted\">{} · {}</p><pre>{}</pre><pre>{}</pre>",
esc(c["author"].as_str().unwrap_or("")), esc(c["at"].as_str().unwrap_or("")),
esc(c["message"].as_str().unwrap_or("")), esc(c["diff"].as_str().unwrap_or("")));
- return Ok(Some(frame(repo, host, sha, &body)));
+ return Ok(Some(Page::Html(frame(repo, host, sha, &body))));
}
Ok(None)
}
diff --git a/src/conf.rs b/src/conf.rs
index 0666916..aa9c03d 100644
--- a/src/conf.rs
+++ b/src/conf.rs
@@ -293,14 +293,18 @@ pub fn hub() -> HubConf {
let path = std::env::var("MIDAS_HUB_CONF").ok().filter(|p| !p.is_empty()).unwrap_or_else(|| HUB_CONF.to_string());
let mut c = read(Path::new(&path)).ok().flatten().unwrap_or_default();
// The repositories the hub hosts itself are projects like any other
- // (hosted.rs): their settings are the hub's to write, not this file's.
+ // (hosted.rs): their landing is the hub's to write, not this file's — an
+ // imported one's too, which this file may still name from its Forgejo days.
+ // Their deploys are this file's alone: root publishes them, and root trusts
+ // nothing the hub's user can write (docs/development.md, Security).
if crate::registry::is_hub() {
for (repo, r) in crate::hosted::repos() {
if !c.repos.iter().any(|x| x.trim_end_matches(".git") == repo) {
c.repos.push(repo.clone());
}
if let Ok(p) = serde_json::from_value::<Project>(r["project"].clone()) {
- c.projects.entry(repo).or_insert(p);
+ let e = c.projects.entry(repo).or_default();
+ (e.gate, e.gate_nodes, e.pre_land, e.main) = (p.gate, p.gate_nodes, p.pre_land, p.main);
}
}
}
diff --git a/src/hosted.rs b/src/hosted.rs
index 73381f1..11c86f4 100644
--- a/src/hosted.rs
+++ b/src/hosted.rs
@@ -119,12 +119,7 @@ pub fn create(n: &New) -> Result<Value> {
}
fs::create_dir_all(dir.parent().unwrap())?;
let made = (|| -> Result<()> {
- 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)?;
+ 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"))?;
@@ -157,6 +152,147 @@ pub fn create(n: &New) -> Result<Value> {
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<()> {
+ 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())
}
@@ -395,6 +531,20 @@ pub fn show(repo: &str, rev: Option<&str>, file: &str) -> Result<Value> {
"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");
diff --git a/src/hub.rs b/src/hub.rs
index 6700643..30032ef 100644
--- a/src/hub.rs
+++ b/src/hub.rs
@@ -280,13 +280,28 @@ pub(crate) fn handle(mut stream: TcpStream, peer: &str) -> Result<()> {
return crate::device::serve_link(stream, reader, &ws_key, &id);
}
// A public repository the hub hosts, to anyone (hosted.rs): clone, archive,
- // and pages to read it by. A private one is not found, as one that is not there.
- if let Some(rest) = target.strip_prefix("/git/") {
+ // LFS and pages to read it by, at `/<owner>/<name>…` as Forgejo had them, so
+ // its old links and `Cargo.toml`s still land. A private one is not found, as
+ // one that is not there. `/git/…`, where they were first, still clones; a
+ // page there is sent to its new path.
+ let at_git = target.strip_prefix("/git/");
+ if let Some(rest) = at_git.or_else(|| hosted_path(&target)) {
+ let repo_seg = rest.split(['/', '?']).nth(1).unwrap_or("");
+ if at_git.is_some() && method == "GET" && !repo_seg.ends_with(".git") {
+ write!(stream, "HTTP/1.1 301 Moved Permanently\r\nLocation: /{rest}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")?;
+ return Ok(());
+ }
let shown_host = if fwd_host.is_empty() { host.clone() } else { fwd_host.clone() };
let g = PublicGit { method: &method, rest, len, content_type: &content_type, git_protocol: &git_protocol, host: &shown_host,
- content_encoding: &content_encoding, peer };
+ content_encoding: &content_encoding, peer, https: who.https };
return public_git(&mut stream, &mut reader, &g);
}
+ // The site's front page, for a visitor the hub does not know: the public
+ // repositories, and the way in. A person logged in, and the tunnel, get the page.
+ if method == "GET" && target == "/" && who.web && who.principal.is_none() {
+ let shown_host = if fwd_host.is_empty() { host.clone() } else { fwd_host.clone() };
+ return respond(&mut stream, 200, "text/html; charset=utf-8", crate::codeview::front(&shown_host).as_bytes());
+ }
// Machines' paths are never a person's: not through the web proxy.
if who.web && (target.starts_with("/lfs/") || target.starts_with("/v1/forgejo")) {
return respond(&mut stream, 403, "text/plain", b"not through the web");
@@ -430,7 +445,8 @@ pub(crate) fn handle(mut stream: TcpStream, peer: &str) -> Result<()> {
};
write!(
stream,
- "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nContent-Length: {}\r\n{encoding}ETag: {}\r\nCache-Control: no-cache\r\nVary: Accept-Encoding\r\nConnection: close\r\n\r\n",
+ // Not for search engines: the public repositories' pages are, and they share the host.
+ "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nContent-Length: {}\r\n{encoding}ETag: {}\r\nCache-Control: no-cache\r\nVary: Accept-Encoding\r\nX-Robots-Tag: noindex, nofollow\r\nConnection: close\r\n\r\n",
a.ctype,
body.len(),
a.etag
@@ -1575,6 +1591,63 @@ struct PublicGit<'a> {
content_encoding: &'a str,
host: &'a str,
peer: &'a str,
+ /// Reached over HTTPS at the proxy: the scheme of the LFS links it is given.
+ https: bool,
+}
+
+/// `owner/name…` of a request for a repository the hub hosts, public or not, at
+/// the site's root (`/<owner>/<name>`, `.git` or not): what goes to
+/// `public_git`, which answers a private one as not there. Only a hosted
+/// repository's two segments match, so the page's own places (`/sessions/s3`)
+/// never do.
+fn hosted_path(target: &str) -> Option<&str> {
+ let rest = target.strip_prefix('/')?;
+ let mut seg = rest.split(['/', '?']);
+ let (owner, name) = (seg.next()?, seg.next()?);
+ let name = name.trim_end_matches(".git");
+ if owner.is_empty() || name.is_empty() || owner.starts_with('.') || name.starts_with('.') {
+ return None;
+ }
+ crate::hosted::is_hosted(&format!("{owner}/{name}")).then_some(rest)
+}
+
+/// LFS for a public repository, without a login (`<name>.git/info/lfs/…`):
+/// the batch, downloads only, points each object the store has at the
+/// object's own path, which serves it. The store is shared by every hosted
+/// repository, and an object is asked for by its sha256 — which only someone
+/// who has its repository's pointer files knows.
+fn public_lfs(stream: &mut TcpStream, reader: &mut BufReader<TcpStream>, g: &PublicGit, repo: &str, tail: &str) -> Result<()> {
+ const LFS_JSON: &str = "application/vnd.git-lfs+json";
+ if let Some(oid) = tail.strip_prefix("objects/").filter(|o| *o != "batch" && !o.contains('/')) {
+ let Some(path) = crate::mirror::cached_object(oid).filter(|_| g.method == "GET") else {
+ return respond(stream, 404, LFS_JSON, br#"{"message":"no such object"}"#);
+ };
+ let mut f = std::fs::File::open(&path)?;
+ let size = f.metadata()?.len();
+ write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {size}\r\nConnection: close\r\n\r\n")?;
+ std::io::copy(&mut f, stream)?;
+ return Ok(());
+ }
+ if tail != "objects/batch" || g.method != "POST" || g.len > 4 << 20 {
+ return respond(stream, 404, LFS_JSON, br#"{"message":"no such LFS endpoint"}"#);
+ }
+ let mut buf = vec![0u8; g.len];
+ reader.read_exact(&mut buf)?;
+ let body: Value = serde_json::from_slice(&buf).unwrap_or(Value::Null);
+ if body["operation"] != "download" {
+ return respond(stream, 403, LFS_JSON, br#"{"message":"read-only: downloads"}"#);
+ }
+ let base = format!("{}://{}/{}.git/info/lfs/objects", if g.https { "https" } else { "http" }, g.host, repo.trim_end_matches(".git"));
+ let objects: Vec<Value> = body["objects"].as_array().into_iter().flatten().filter_map(|o| {
+ let oid = o["oid"].as_str()?;
+ let size = o["size"].as_u64().unwrap_or(0);
+ Some(match crate::mirror::cached_object(oid) {
+ Some(_) => json!({"oid": oid, "size": size, "actions": {"download": {"href": format!("{base}/{oid}")}}}),
+ None => json!({"oid": oid, "size": size, "error": {"code": 404, "message": "not stored here"}}),
+ })
+ }).collect();
+ events::emit("lfs_public", json!({"repo": repo, "objects": objects.len(), "peer": g.peer}));
+ respond(stream, 200, LFS_JSON, json!({"transfer": "basic", "objects": objects}).to_string().as_bytes())
}
/// `/git/<owner>/<name>…` for a public hosted repository, with no login:
@@ -1592,6 +1665,11 @@ fn public_git(stream: &mut TcpStream, reader: &mut BufReader<TcpStream>, g: &Pub
if !crate::hosted::is_public(&repo) {
return not_found(stream);
}
+ if git_suffix {
+ if let Some(t) = tail.strip_prefix("info/lfs/") {
+ return public_lfs(stream, reader, g, &repo, t);
+ }
+ }
// Smart HTTP, for clones (Cargo's `git =`, anybody's `git clone`).
if git_suffix {
let fetch = matches!((g.method, tail), ("GET", "info/refs") | ("POST", "git-upload-pack"))
@@ -1651,8 +1729,20 @@ fn public_git(stream: &mut TcpStream, reader: &mut BufReader<TcpStream>, g: &Pub
stream.write_all(&out.stdout)?;
return Ok(());
}
+ use crate::codeview::Page;
match crate::codeview::page(&repo, g.host, tail, query) {
- Ok(Some(html)) => respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()),
+ Ok(Some(Page::Html(html))) => respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()),
+ // Text as text, never as HTML: a repository's page must not run on the hub's origin.
+ Ok(Some(Page::Raw(bytes))) => {
+ let ctype = if std::str::from_utf8(&bytes).is_ok() { "text/plain; charset=utf-8" } else { "application/octet-stream" };
+ write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: {ctype}\r\nX-Content-Type-Options: nosniff\r\nContent-Security-Policy: sandbox\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", bytes.len())?;
+ stream.write_all(&bytes)?;
+ Ok(())
+ }
+ Ok(Some(Page::Moved(to))) => {
+ write!(stream, "HTTP/1.1 301 Moved Permanently\r\nLocation: {to}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")?;
+ Ok(())
+ }
Ok(None) | Err(_) => not_found(stream),
}
}
diff --git a/src/main.rs b/src/main.rs
index 046a52b..758a88a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1063,6 +1063,27 @@ enum HubCmd {
/// hub as its user: `sudo -u midas midas hub git-key …`.
#[command(subcommand)]
GitKey(GitKeyCmd),
+ /// Take a project over from Forgejo (docs/git-hosting.md, step 2): its
+ /// branches, tags and LFS objects, and its landing. Run on the hub as its
+ /// user: `sudo -u midas midas hub import jeroen/x --public`.
+ Import {
+ /// `owner/name`, as hub.conf's `repos` has it.
+ repo: String,
+ /// Readable by anyone at `/<owner>/<name>`, as it was on Forgejo.
+ #[arg(long)]
+ public: bool,
+ #[arg(long, default_value = "")]
+ description: String,
+ /// Fetch it from here (a path or URL) instead of Forgejo over ssh: for
+ /// a repository the mirror's key does not open, Forgejo's copy staged
+ /// where the hub's user can read it.
+ #[arg(long)]
+ from: Option<String>,
+ /// Take missing LFS objects from this directory, laid out as Forgejo's
+ /// (`data/lfs`), instead of asking Forgejo.
+ #[arg(long)]
+ lfs_from: Option<std::path::PathBuf>,
+ },
/// Warm every free node that is cold, over its ceiling or stale (a timer runs it),
/// then mail any node problem that has lasted an hour.
Warm {
@@ -1705,6 +1726,8 @@ fn run(cmd: Cmd, owner: Option<String>) -> anyhow::Result<i32> {
Cmd::Hub(HubCmd::PreReceive) => hosted::pre_receive(),
Cmd::Hub(HubCmd::PostReceive) => hosted::post_receive(),
Cmd::Hub(HubCmd::GitKey(c)) => cli::git_key(c),
+ Cmd::Hub(HubCmd::Import { repo, public, description, from, lfs_from }) =>
+ cli::hub_import(&repo, public, &description, &crate::hosted::Source { git: from.as_deref(), lfs: lfs_from.as_deref() }),
Cmd::Hub(HubCmd::Warm { node, dry_run }) => warm::warm(node.as_deref(), dry_run),
Cmd::Hub(HubCmd::Backup) => hubsetup::backup(),
Cmd::Hub(HubCmd::DeployBuild) => deploy::build_pending(),
diff --git a/src/mirror.rs b/src/mirror.rs
index 5109f6e..7a7eeda 100644
--- a/src/mirror.rs
+++ b/src/mirror.rs
@@ -49,7 +49,7 @@ pub fn deploy_key() -> String {
/// 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.
-fn git_ssh() -> String {
+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 \
diff --git a/src/tests.rs b/src/tests.rs
index 7a6d617..cb837f4 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -2977,11 +2977,85 @@ fn a_public_repository_has_pages_and_a_private_one_none() {
let _g = SERIAL.lock().unwrap();
scratch("hosted-view");
new_project("open", true);
- let home = crate::codeview::page("acme/open.git", "midas.example", "", "").unwrap().unwrap();
- assert!(home.contains("README.md") && home.contains("A test project") && home.contains("git clone https://midas.example/git/acme/open.git"));
- let log = crate::codeview::page("acme/open.git", "h", "log", "").unwrap().unwrap();
- assert!(log.contains("Start open"));
- assert!(crate::codeview::page("acme/open.git", "h", "nowhere", "").unwrap().is_none());
- let file = crate::codeview::page("acme/open.git", "h", "tree/README.md", "").unwrap().unwrap();
+ use crate::codeview::Page;
+ let page = |tail: &str, q: &str| crate::codeview::page("acme/open.git", "midas.example", tail, q).unwrap();
+ let html = |tail: &str| match page(tail, "") {
+ Some(Page::Html(h)) => h,
+ _ => panic!("no page at {tail:?}"),
+ };
+ let home = html("");
+ assert!(home.contains("README.md") && home.contains("A test project") && home.contains("git clone https://midas.example/acme/open.git"));
+ assert!(home.contains("href=\"/acme/open/log\""), "links at the root, as Forgejo had them: {home}");
+ assert!(html("log").contains("Start open"));
+ assert!(page("nowhere", "").is_none());
+ let file = html("tree/README.md");
assert!(file.contains("<pre># open"), "{file}");
+ assert!(matches!(page("raw/README.md", ""), Some(Page::Raw(b)) if b.starts_with(b"# open")));
+ // Forgejo's paths, sent to ours.
+ for (old, new) in [("src/branch/main/README.md", "/acme/open/tree/README.md?rev=main"),
+ ("src/branch/main", "/acme/open/tree?rev=main"),
+ ("raw/commit/abc123/a/b.rs", "/acme/open/raw/a/b.rs?rev=abc123"),
+ ("media/branch/main/x.png", "/acme/open/raw/x.png?rev=main"),
+ ("commits/branch/main", "/acme/open/log?rev=main")] {
+ assert!(matches!(page(old, ""), Some(Page::Moved(ref to)) if to == new), "{old}");
+ }
+ // The front page lists the public one, not the private one.
+ new_project("shut", false);
+ let front = crate::codeview::front("garage44.example");
+ assert!(front.contains("href=\"/acme/open\"") && !front.contains("acme/shut") && front.contains("/login"), "{front}");
+}
+
+#[test]
+fn a_forgejo_project_is_imported_with_its_branches_and_its_landing_but_not_its_deploys() {
+ let _g = SERIAL.lock().unwrap();
+ scratch("hosted-import");
+ struct Conf;
+ impl Drop for Conf {
+ fn drop(&mut self) {
+ // SAFETY: tests hold SERIAL.
+ unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
+ }
+ }
+ // "Forgejo": a directory of bare repositories, which git fetches as it would the ssh URL.
+ let forge = crate::registry::root().join("forge");
+ let old = forge.join("acme/old.git");
+ let sh = |dir: &std::path::Path, c: &str| assert!(std::process::Command::new("sh").arg("-c").arg(c).current_dir(dir).status().unwrap().success(), "{c}");
+ std::fs::create_dir_all(&old).unwrap();
+ sh(&old, "git init -q --bare -b main . && blob=$(echo hello | git hash-object -w --stdin) \
+ && tree=$(printf '100644 blob %s\\tREADME\\n' $blob | git mktree) \
+ && c=$(git -c user.name=t -c user.email=t@t commit-tree $tree -m first) \
+ && git update-ref refs/heads/main $c && git update-ref refs/heads/session/s1 $c && git tag v1 $c");
+ // The LFS objects a repository names, on a branch's tree: an import takes each from Forgejo.
+ let art = forge.join("acme/art.git");
+ std::fs::create_dir_all(&art).unwrap();
+ sh(&art, "git init -q --bare -b main . && blob=$(echo hello | git hash-object -w --stdin) \
+ && lfs=$(printf 'version https://git-lfs.github.com/spec/v1\\noid sha256:%s\\nsize 5\\n' $(printf %064d 7) | git hash-object -w --stdin) \
+ && tree=$(printf '100644 blob %s\\tREADME\\n100644 blob %s\\tpic.png\\n' $blob $lfs | git mktree) \
+ && c=$(git -c user.name=t -c user.email=t@t commit-tree $tree -m first) && git update-ref refs/heads/side $c");
+ assert_eq!(crate::hosted::lfs_pointers(&art).unwrap(), vec![(format!("{:064}", 7), 5)]);
+ let conf = crate::registry::root().join("hub.conf");
+ std::fs::write(&conf, json!({"listen": "127.0.0.1:1", "forgejo_ssh": forge.to_string_lossy(), "forgejo_api": "",
+ "repos": ["acme/old"], "projects": {"acme/old": {"gate": "make test", "pre_land": "true"}}}).to_string()).unwrap();
+ // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
+ unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
+ let _conf = Conf;
+ let forgejo = crate::hosted::Source::default();
+ assert!(crate::hosted::import("acme/nope", true, "", &forgejo, "t").is_err(), "nothing to fetch");
+ assert!(!crate::hosted::path("acme/nope").exists(), "a failed import leaves nothing");
+ let v = crate::hosted::import("acme/old", true, "An old project", &forgejo, "t").unwrap();
+ assert_eq!(v["branches"], 2);
+ assert_eq!(v["lfs_objects"], 0);
+ assert!(crate::hosted::is_public("acme/old"));
+ let dir = crate::hosted::path("acme/old");
+ sh(&dir, "git rev-parse -q --verify refs/tags/v1 >/dev/null && test -x hooks/pre-receive");
+ let p = crate::conf::hub().project("acme/old").unwrap();
+ assert_eq!(p["gate"], "make test");
+ assert!(crate::hosted::get("acme/old").unwrap()["project"].get("deploy").is_none());
+ assert!(crate::hosted::import("acme/old", true, "", &forgejo, "t").is_err(), "not twice");
+ // One hub.conf does not name, from a path, with an LFS object nowhere to be had: no landing, and the object named.
+ let empty = crate::registry::root().join("no-lfs");
+ std::fs::create_dir_all(&empty).unwrap();
+ let v = crate::hosted::import("acme/art", false, "", &crate::hosted::Source { git: Some(&art.to_string_lossy()), lfs: Some(&empty) }, "t").unwrap();
+ assert_eq!(v["lfs_missing"], json!([format!("{:064}", 7)]));
+ assert!(!crate::hosted::is_public("acme/art") && crate::conf::hub().project("acme/art").unwrap()["gate"].is_null());
}
diff --git a/tests/e2e/hosted.sh b/tests/e2e/hosted.sh
index b62e866..0ebc12c 100755
--- a/tests/e2e/hosted.sh
+++ b/tests/e2e/hosted.sh
@@ -38,7 +38,7 @@ echo " $repo at $bare"
echo "== cloned over public HTTP, without a login"
git clone -q "$hub/git/$repo.git" "$e2e/clone" || fail "public clone"
grep -q "An e2e project" "$e2e/clone/README.md" || fail "README not cloned"
-if git clone -q "$hub/git/${repo%/*}/hidden.git" "$e2e/nope" 2>/dev/null; then fail "a private repository cloned"; fi
+if git clone -q "$hub/${repo%/*}/hidden.git" "$e2e/nope" 2>/dev/null; then fail "a private repository cloned"; fi
echo "== an agent pushes a branch"
cd "$e2e/clone"
@@ -58,13 +58,29 @@ MIDAS_HUB=$hub MIDAS_HUB_KEY=$key MIDAS_OWNER=s-e2e HOME=$e2e "$midas" verified
git push -q -o midas-owner=s-e2e "$bare" HEAD:refs/heads/main || fail "the landing's push refused"
[ "$(git -C "$bare" rev-parse main)" = "$head" ] || fail "main is not the landed head"
-echo "== read on its pages and as an archive"
-curl -fs "$hub/git/$repo" | grep -q "An e2e project" || fail "home page"
-curl -fs "$hub/git/$repo/log" | grep -q "more" || fail "log page"
-curl -fs "$hub/git/$repo/commit/$head" | grep -q "+more" || fail "commit page"
-curl -fs "$hub/git/$repo/archive/main.tar.gz" | tar tz | grep -q "demo/README.md" || fail "archive"
-code=$(curl -s -o /dev/null -w '%{http_code}' "$hub/git/${repo%/*}/hidden")
-[ "$code" = 404 ] || fail "a private repository's page answered $code"
+echo "== read on its pages and as an archive, at Forgejo's paths"
+curl -fs "$hub/$repo" | grep -q "An e2e project" || fail "home page"
+curl -fs "$hub/$repo/log" | grep -q "more" || fail "log page"
+curl -fs "$hub/$repo/commit/$head" | grep -q "+more" || fail "commit page"
+curl -fs "$hub/$repo/raw/README.md" | grep -q "^more" || fail "raw file"
+curl -fs "$hub/$repo/archive/main.tar.gz" | tar tz | grep -q "demo/README.md" || fail "archive"
+loc=$(curl -s -o /dev/null -w '%{redirect_url}' "$hub/$repo/src/branch/main/README.md")
+[ "$loc" = "$hub/$repo/tree/README.md?rev=main" ] || fail "a Forgejo path went to $loc"
+loc=$(curl -s -o /dev/null -w '%{redirect_url}' "$hub/git/$repo/log")
+[ "$loc" = "$hub/$repo/log" ] || fail "an old /git/ page went to $loc"
+git clone -q "$hub/$repo.git" "$e2e/clone2" || fail "a clone at the root path"
+for p in "$hub/${repo%/*}/hidden" "$hub/${repo%/*}/hidden.git/info/refs?service=git-upload-pack" "$hub/git/${repo%/*}/hidden"; do
+ code=$(curl -sL -o /dev/null -w '%{http_code}' "$p")
+ [ "$code" = 404 ] || fail "a private repository answered $code at $p"
+done
+code=$(curl -s -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/vnd.git-lfs+json' \
+ --data '{"operation":"upload","objects":[]}' "$hub/$repo.git/info/lfs/objects/batch")
+[ "$code" = 403 ] || fail "a public LFS upload answered $code"
+curl -fs -X POST -H 'Content-Type: application/vnd.git-lfs+json' --data '{"operation":"download","objects":[{"oid":"'"$(printf %064d 0)"'","size":1}]}' \
+ "$hub/$repo.git/info/lfs/objects/batch" | grep -q '"code":404' || fail "a public LFS batch"
+echo "== the front page, to a visitor through the proxy"
+curl -fs -H 'X-Forwarded-For: 203.0.113.9' -H 'X-Forwarded-Proto: https' "$hub/" | grep -q "href=\"/$repo\"" || fail "front page"
+if curl -fs -H 'X-Forwarded-For: 203.0.113.9' -H 'X-Forwarded-Proto: https' "$hub/" | grep -q hidden; then fail "a private one on the front page"; fi
MIDAS_HUB=$hub MIDAS_HUB_KEY=$key HOME=$e2e "$midas" project log "$repo" | grep -q "more" || fail "project log"
echo "hosted e2e: all passed"