Add integration tests for the SSH commands and web pages
Browse filestests/ssh.rs pushes and clones real repositories through a stand-in for ssh that runs gitv serve, covering help, create, list and delete, name rules, push-to-create, owner isolation, path rejection, default branch selection and the admin commands, including key validation. tests/web.rs builds a fixture repository (tags, a merge, a submodule, binary, oversized and glob-named files, a long branch) and checks every view of a running gitv-web over HTTP: rendering, escaping, links, redirects, raw content types, paging, diffs, security headers and the requests that must 404. gitv-web now prints the address it actually bound, so --port 0 works. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 11:22
- Commit
- c7a42bebd4a7
- Parent
- 450fc41
5 files changed +885−1
+8−0
| @@ -24,3 +24,11 @@ mkdir -p dev/repos | ||
| ```sh | ||
| GIT_SSH_COMMAND=$PWD/dev/fake-ssh git push git@x:um9i/myrepo.git main | ||
| ``` | ||
| ## Tests | ||
| ```sh | ||
| cargo test | ||
| ``` | ||
| `tests/ssh.rs` runs `gitv serve` the way a key does over SSH, pushing and cloning real repositories through a stand-in for ssh. `tests/web.rs` builds a fixture repository and checks every page of a running `gitv-web` over HTTP, including escaping and the requests it must refuse. Neither needs an SSH server or network access; both write only to `target/tmp`. | ||
| @@ -871,6 +871,8 @@ async fn main() { | ||
| blocking(move || route(&o, &n, Some(&v), &q)))) | ||
| .fallback(|| async { View::Missing }); | ||
| let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.expect("bind port"); | ||
| println!("gitv-web listening on http://127.0.0.1:{port} (repos: {})", repos_root().display()); | ||
| // Print the bound address (not the requested port), so `--port 0` works for tests. | ||
| let address = listener.local_addr().expect("local address"); | ||
| println!("gitv-web listening on http://{address} (repos: {})", repos_root().display()); | ||
| axum::serve(listener, app).await.expect("server"); | ||
| } | ||
tests/common/mod.rsAdded
+217−0
| @@ -0,0 +1,217 @@ | ||
| //! Shared helpers for the integration tests: isolated git, a stand-in for ssh that runs | ||
| //! `gitv serve`, and a minimal HTTP client. | ||
| #![allow(dead_code)] | ||
| use std::collections::HashMap; | ||
| use std::fs; | ||
| use std::io::{BufRead, BufReader, Read, Write}; | ||
| use std::net::TcpStream; | ||
| use std::os::unix::fs::PermissionsExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Child, Command, Output, Stdio}; | ||
| pub const GITV: &str = env!("CARGO_BIN_EXE_gitv"); | ||
| pub const GITV_WEB: &str = env!("CARGO_BIN_EXE_gitv-web"); | ||
| /// A fresh, empty directory under Cargo's per-target temporary directory. | ||
| pub fn scratch(name: &str) -> PathBuf { | ||
| let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| /// Git with no user or system config and a fixed identity and clock, so runs are repeatable. | ||
| pub fn git_cmd(dir: &Path) -> Command { | ||
| let mut command = Command::new("git"); | ||
| command | ||
| .current_dir(dir) | ||
| .env("HOME", dir) | ||
| .env("GIT_CONFIG_NOSYSTEM", "1") | ||
| .env("GIT_CONFIG_GLOBAL", "/dev/null") | ||
| .env("GIT_AUTHOR_NAME", "Ada Lovelace") | ||
| .env("GIT_AUTHOR_EMAIL", "ada@example.com") | ||
| .env("GIT_COMMITTER_NAME", "Ada Lovelace") | ||
| .env("GIT_COMMITTER_EMAIL", "ada@example.com") | ||
| .env("GIT_AUTHOR_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_COMMITTER_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_SSH_VARIANT", "simple") | ||
| .stdin(Stdio::null()); | ||
| command | ||
| } | ||
| /// Run git in `dir`, panic with its output on failure, and return trimmed stdout. | ||
| pub fn git(dir: &Path, args: &[&str]) -> String { | ||
| let output = git_cmd(dir).args(args).output().unwrap(); | ||
| assert!(output.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&output.stderr)); | ||
| String::from_utf8_lossy(&output.stdout).trim().to_string() | ||
| } | ||
| /// A GITv installation in a scratch directory: repositories, a keys file, and a fake `ssh` | ||
| /// that hands git's command to `gitv serve` as an owner's key would. | ||
| pub struct Host { | ||
| pub dir: PathBuf, | ||
| pub repos: PathBuf, | ||
| pub keys: PathBuf, | ||
| } | ||
| impl Host { | ||
| pub fn new(name: &str) -> Host { | ||
| let dir = scratch(name); | ||
| let repos = dir.join("repos"); | ||
| fs::create_dir_all(&repos).unwrap(); | ||
| let keys = dir.join("authorized_keys"); | ||
| let host = Host { dir, repos, keys }; | ||
| // With GIT_SSH_VARIANT=simple git runs: <ssh> <owner>@host <command>. | ||
| let script = format!( | ||
| "#!/bin/sh\nowner=${{1%%@*}}\nSSH_ORIGINAL_COMMAND=\"$2\" GITV_REPOS='{}' exec '{GITV}' serve \"$owner\"\n", | ||
| host.repos.display() | ||
| ); | ||
| let ssh = host.ssh_script(); | ||
| fs::write(&ssh, script).unwrap(); | ||
| fs::set_permissions(&ssh, fs::Permissions::from_mode(0o755)).unwrap(); | ||
| host | ||
| } | ||
| pub fn ssh_script(&self) -> PathBuf { | ||
| self.dir.join("fake-ssh") | ||
| } | ||
| /// `ssh git@host <command>` as `owner`'s key. | ||
| pub fn ssh(&self, owner: &str, command: &str) -> Output { | ||
| Command::new(GITV) | ||
| .args(["serve", owner]) | ||
| .env("SSH_ORIGINAL_COMMAND", command) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// `gitv <args>` as the administrator, pointed at this host. | ||
| pub fn admin(&self, args: &[&str]) -> Output { | ||
| Command::new(GITV) | ||
| .args(args) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .env("GITV_KEYS", &self.keys) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// Git in `dir`, with remotes reached through this host's fake ssh. | ||
| pub fn git(&self, dir: &Path, args: &[&str]) -> Output { | ||
| git_cmd(dir).env("GIT_SSH_COMMAND", self.ssh_script()).args(args).output().unwrap() | ||
| } | ||
| pub fn repo(&self, owner: &str, name: &str) -> PathBuf { | ||
| self.repos.join(owner).join(format!("{name}.git")) | ||
| } | ||
| } | ||
| pub fn stdout(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stdout).into_owned() | ||
| } | ||
| pub fn stderr(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stderr).into_owned() | ||
| } | ||
| /// A running `gitv-web`, stopped when dropped. | ||
| pub struct Server { | ||
| child: Child, | ||
| pub port: u16, | ||
| } | ||
| impl Server { | ||
| pub fn start(repos: &Path) -> Server { | ||
| let mut child = Command::new(GITV_WEB) | ||
| .args(["serve", "--port", "0"]) | ||
| .env("GITV_REPOS", repos) | ||
| .stdout(Stdio::piped()) | ||
| .stderr(Stdio::null()) | ||
| .spawn() | ||
| .unwrap(); | ||
| let mut line = String::new(); | ||
| BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap(); | ||
| let port = line | ||
| .split("http://127.0.0.1:") | ||
| .nth(1) | ||
| .and_then(|rest| rest.split_whitespace().next()) | ||
| .and_then(|p| p.parse().ok()) | ||
| .unwrap_or_else(|| panic!("unexpected startup line: {line}")); | ||
| Server { child, port } | ||
| } | ||
| pub fn get(&self, path: &str) -> Response { | ||
| get(self.port, path) | ||
| } | ||
| } | ||
| impl Drop for Server { | ||
| fn drop(&mut self) { | ||
| let _ = self.child.kill(); | ||
| let _ = self.child.wait(); | ||
| } | ||
| } | ||
| pub struct Response { | ||
| pub status: u16, | ||
| pub headers: HashMap<String, String>, | ||
| pub body: Vec<u8>, | ||
| } | ||
| impl Response { | ||
| pub fn text(&self) -> String { | ||
| String::from_utf8_lossy(&self.body).into_owned() | ||
| } | ||
| pub fn header(&self, name: &str) -> &str { | ||
| self.headers.get(name).map_or("", String::as_str) | ||
| } | ||
| } | ||
| /// A plain HTTP/1.1 GET, enough for testing a local server. | ||
| pub fn get(port: u16, path: &str) -> Response { | ||
| let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); | ||
| write!(stream, "GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap(); | ||
| let mut raw = Vec::new(); | ||
| stream.read_to_end(&mut raw).unwrap(); | ||
| let split = raw.windows(4).position(|w| w == b"\r\n\r\n").expect("no header end"); | ||
| let head = String::from_utf8_lossy(&raw[..split]).into_owned(); | ||
| let mut lines = head.lines(); | ||
| let status = lines.next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap(); | ||
| let headers: HashMap<String, String> = lines | ||
| .filter_map(|l| l.split_once(':')) | ||
| .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string())) | ||
| .collect(); | ||
| let mut body = raw[split + 4..].to_vec(); | ||
| if headers.get("transfer-encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked")) { | ||
| body = dechunk(&body); | ||
| } | ||
| Response { status, headers, body } | ||
| } | ||
| fn dechunk(mut data: &[u8]) -> Vec<u8> { | ||
| let mut out = Vec::new(); | ||
| while let Some(end) = data.windows(2).position(|w| w == b"\r\n") { | ||
| let size = usize::from_str_radix(String::from_utf8_lossy(&data[..end]).trim(), 16).unwrap_or(0); | ||
| if size == 0 { | ||
| break; | ||
| } | ||
| out.extend_from_slice(&data[end + 2..end + 2 + size]); | ||
| data = &data[end + 2 + size + 2..]; | ||
| } | ||
| out | ||
| } | ||
| /// A syntactically valid OpenSSH Ed25519 public key built from `seed`. | ||
| pub fn ed25519_key(seed: u8) -> String { | ||
| use base64::Engine; | ||
| let mut blob = 11u32.to_be_bytes().to_vec(); | ||
| blob.extend_from_slice(b"ssh-ed25519"); | ||
| blob.extend_from_slice(&32u32.to_be_bytes()); | ||
| blob.extend_from_slice(&[seed; 32]); | ||
| format!("ssh-ed25519 {} test@example\n", base64::engine::general_purpose::STANDARD.encode(blob)) | ||
| } | ||
tests/ssh.rsAdded
+209−0
| @@ -0,0 +1,209 @@ | ||
| //! `gitv serve` (what a key runs over SSH) and the administrator commands, exercised with real | ||
| //! git pushes and clones through a stand-in for ssh. | ||
| mod common; | ||
| use std::fs; | ||
| use common::{Host, ed25519_key, git, scratch, stderr, stdout}; | ||
| /// A working copy with one commit on `branch`. | ||
| fn work(name: &str, branch: &str) -> std::path::PathBuf { | ||
| let dir = scratch(name); | ||
| git(&dir, &["init", "-q", "-b", branch]); | ||
| fs::write(dir.join("hello.txt"), "hello\n").unwrap(); | ||
| git(&dir, &["add", "."]); | ||
| git(&dir, &["commit", "-qm", "First"]); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn help_lists_the_commands() { | ||
| let host = Host::new("ssh-help"); | ||
| for command in ["", "help"] { | ||
| let out = host.ssh("ada", command); | ||
| assert!(out.status.success()); | ||
| assert!(stdout(&out).contains("create <name>"), "{}", stdout(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn unknown_and_unreadable_commands_are_refused() { | ||
| let host = Host::new("ssh-unknown"); | ||
| for command in ["rm -rf /", "list extra", "create", "git-upload-pack", "create 'unterminated"] { | ||
| let out = host.ssh("ada", command); | ||
| assert!(!out.status.success(), "{command} should fail"); | ||
| assert!(stderr(&out).starts_with("gitv: "), "{command}: {}", stderr(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn create_list_and_delete() { | ||
| let host = Host::new("ssh-crud"); | ||
| let out = host.ssh("ada", "create notes"); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&out).trim(), "git@git.um9i.dev:ada/notes.git"); | ||
| assert!(host.repo("ada", "notes").join("HEAD").is_file()); | ||
| assert!(!host.ssh("ada", "create notes").status.success(), "duplicates are refused"); | ||
| host.ssh("ada", "create alpha"); | ||
| assert_eq!(stdout(&host.ssh("ada", "list")), "git@git.um9i.dev:ada/alpha.git\ngit@git.um9i.dev:ada/notes.git\n"); | ||
| assert_eq!(stdout(&host.ssh("bob", "list")), "", "owners only see their own repositories"); | ||
| let out = host.ssh("ada", "delete notes"); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("delete notes --yes"), "{}", stderr(&out)); | ||
| assert!(host.repo("ada", "notes").exists(), "nothing is deleted without --yes"); | ||
| assert!(host.ssh("ada", "delete notes --yes").status.success()); | ||
| assert!(!host.repo("ada", "notes").exists()); | ||
| assert!(!host.ssh("ada", "delete notes --yes").status.success(), "a missing repository can't be deleted"); | ||
| } | ||
| #[test] | ||
| fn names_are_validated() { | ||
| let host = Host::new("ssh-names"); | ||
| for name in ["Upper", "-dash", "has.dot", "a/b", "..", &"x".repeat(64)] { | ||
| let out = host.ssh("ada", &format!("create '{name}'")); | ||
| assert!(!out.status.success(), "{name} should be refused"); | ||
| } | ||
| assert!(fs::read_dir(&host.repos).unwrap().next().is_none(), "nothing was created"); | ||
| assert!(host.ssh("ada", "create ok_name-2").status.success()); | ||
| } | ||
| #[test] | ||
| fn push_creates_the_repository_and_clone_reads_it() { | ||
| let host = Host::new("ssh-push"); | ||
| let dir = work("ssh-push-work", "main"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/project.git", "main"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("gitv: created ada/project.git"), "{}", stderr(&out)); | ||
| let clone = scratch("ssh-push-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/project.git", "copy"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(fs::read_to_string(clone.join("copy/hello.txt")).unwrap(), "hello\n"); | ||
| // A second push updates the same repository. | ||
| fs::write(dir.join("hello.txt"), "hello again\n").unwrap(); | ||
| git(&dir, &["commit", "-qam", "Second"]); | ||
| assert!(host.git(&dir, &["push", "-q", "ada@x:ada/project.git", "main"]).status.success()); | ||
| let log = git(&host.repo("ada", "project"), &["log", "--format=%s", "main"]); | ||
| assert_eq!(log, "Second\nFirst"); | ||
| } | ||
| #[test] | ||
| fn fetching_a_missing_repository_fails_without_creating_it() { | ||
| let host = Host::new("ssh-missing"); | ||
| let clone = scratch("ssh-missing-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/nothing.git"]); | ||
| assert!(!out.status.success()); | ||
| assert!(!host.repo("ada", "nothing").exists()); | ||
| } | ||
| #[test] | ||
| fn keys_only_reach_their_owners_repositories() { | ||
| let host = Host::new("ssh-owner"); | ||
| let dir = work("ssh-owner-work", "main"); | ||
| assert!(host.git(&dir, &["push", "-q", "bob@x:bob/private.git", "main"]).status.success()); | ||
| let clone = scratch("ssh-owner-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:bob/private.git"]); | ||
| assert!(!out.status.success(), "ada read bob's repository"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:bob/other.git", "main"]); | ||
| assert!(!out.status.success(), "ada created a repository for bob"); | ||
| assert!(!host.repo("bob", "other").exists()); | ||
| for path in ["'../bob/private.git'", "'ada/../bob/private.git'", "'/etc/passwd'", "'ada/x'"] { | ||
| let out = host.ssh("ada", &format!("git-upload-pack {path}")); | ||
| assert!(!out.status.success(), "{path} was served"); | ||
| assert!(stderr(&out).contains("repository unavailable"), "{path}: {}", stderr(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn pushing_master_alone_makes_it_the_default_branch() { | ||
| let host = Host::new("ssh-head"); | ||
| let dir = work("ssh-head-work", "master"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/legacy.git", "master"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("default branch is now master"), "{}", stderr(&out)); | ||
| assert_eq!(git(&host.repo("ada", "legacy"), &["symbolic-ref", "HEAD"]), "refs/heads/master"); | ||
| // A clone now checks out master without being told to. | ||
| let clone = scratch("ssh-head-clone"); | ||
| assert!(host.git(&clone, &["clone", "-q", "ada@x:ada/legacy.git", "copy"]).status.success()); | ||
| assert_eq!(git(&clone.join("copy"), &["branch", "--show-current"]), "master"); | ||
| } | ||
| #[test] | ||
| fn admin_create_and_delete() { | ||
| let host = Host::new("admin-crud"); | ||
| let out = host.admin(&["create", "ada", "tools"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&out).trim(), "git@git.um9i.dev:ada/tools.git"); | ||
| assert_eq!(git(&host.repo("ada", "tools"), &["symbolic-ref", "HEAD"]), "refs/heads/main"); | ||
| let out = host.admin(&["delete", "ada", "tools"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("--yes"), "{}", stderr(&out)); | ||
| assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); | ||
| assert!(!host.repo("ada", "tools").exists()); | ||
| assert!(!host.admin(&["create", "Ada", "tools"]).status.success(), "owner names are validated"); | ||
| } | ||
| #[test] | ||
| fn admin_add_key() { | ||
| let host = Host::new("admin-keys"); | ||
| let key = host.dir.join("ada.pub"); | ||
| fs::write(&key, ed25519_key(7)).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let keys = fs::read_to_string(&host.keys).unwrap(); | ||
| assert!(keys.starts_with("restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 AAAA"), "{keys}"); | ||
| assert!(!keys.contains("test@example"), "the key's comment is dropped"); | ||
| assert!(host.repos.join("ada").is_dir(), "the owner's directory exists"); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| let second = host.dir.join("bob.pub"); | ||
| fs::write(&second, ed25519_key(9)).unwrap(); | ||
| assert!(host.admin(&["add-key", "bob", second.to_str().unwrap()]).status.success()); | ||
| assert_eq!(fs::read_to_string(&host.keys).unwrap().lines().count(), 2, "both keys are kept"); | ||
| } | ||
| #[test] | ||
| fn admin_add_key_rejects_bad_keys() { | ||
| let host = Host::new("admin-badkeys"); | ||
| let cases = [ | ||
| ("rsa", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ test\n".to_string()), | ||
| ("garbage", "not a key\n".to_string()), | ||
| ("bad-base64", "ssh-ed25519 !!!!\n".to_string()), | ||
| ("short", "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5\n".to_string()), | ||
| ("options", format!("command=\"sh\" {}", ed25519_key(1))), | ||
| ]; | ||
| for (name, text) in cases { | ||
| let file = host.dir.join(format!("{name}.pub")); | ||
| fs::write(&file, text).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "{name} was accepted"); | ||
| } | ||
| assert!(!host.keys.exists(), "no key was written"); | ||
| } | ||
| #[test] | ||
| fn admin_needs_root_outside_a_local_tree() { | ||
| if nix::unistd::geteuid().is_root() { | ||
| return; | ||
| } | ||
| let out = std::process::Command::new(common::GITV) | ||
| .args(["create", "ada", "tools"]) | ||
| .env_remove("GITV_REPOS") | ||
| .output() | ||
| .unwrap(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("as root"), "{}", stderr(&out)); | ||
| } | ||
tests/web.rsAdded
+448−0
| @@ -0,0 +1,448 @@ | ||
| //! `gitv-web` served over HTTP against a fixture repository: every view, the links between | ||
| //! them, escaping and the requests it must refuse. | ||
| mod common; | ||
| use std::fs; | ||
| use std::path::PathBuf; | ||
| use std::sync::OnceLock; | ||
| use common::{Host, Server, git}; | ||
| /// Object ids in the fixture that tests link to. | ||
| struct Fixture { | ||
| repos: PathBuf, | ||
| first: String, | ||
| removal: String, | ||
| merge: String, | ||
| tip: String, | ||
| } | ||
| const README: &str = "# Fixture {onclick=alert(1) #main .skip} | ||
| See the [guide](docs/guide.md), the [source](src) and [a site](https://example.com). | ||
| [bad](javascript:alert(1)) [escape](../../etc/passwd) | ||
| <script>alert(1)</script> | ||
|  | ||
| ```rust | ||
| fn main() {} | ||
| ``` | ||
| "; | ||
| const GUIDE: &str = "# Guide\n\nBack to [main.rs](../src/main.rs).\n\n| a | b |\n|---|---|\n| 1 | 2 |\n"; | ||
| /// Build the fixture once per test run: | ||
| /// | ||
| /// first: README.md, docs/guide.md, src/main.rs, img/logo.svg, data.bin, star*.txt, old.txt, | ||
| /// glob*/inside.txt (tagged v0.1.0, annotated) | ||
| /// removal: delete old.txt, edit src/main.rs, add globber.txt | ||
| /// merge: merge of branch `side`, which added side.txt | ||
| /// tip: add a submodule at vendor/lib and a 1.2 MB big.txt (tagged `light`, lightweight) | ||
| /// `long`: 55 more commits on top of `first`, for paging | ||
| /// plus an empty repository, ada/empty. | ||
| fn fixture() -> &'static Fixture { | ||
| static FIXTURE: OnceLock<Fixture> = OnceLock::new(); | ||
| FIXTURE.get_or_init(|| { | ||
| let host = Host::new("web-host"); | ||
| let work = common::scratch("web-work"); | ||
| git(&work, &["init", "-q", "-b", "main"]); | ||
| for (path, text) in [ | ||
| ("README.md", README), | ||
| ("docs/guide.md", GUIDE), | ||
| ("src/main.rs", "fn main() {\n println!(\"<hi>\");\n}\n"), | ||
| ("img/logo.svg", "<svg xmlns=\"http://www.w3.org/2000/svg\"/>"), | ||
| ("star*.txt", "a star\n"), | ||
| ("old.txt", "going away\n"), | ||
| ("glob*/inside.txt", "a folder whose name is a glob\n"), | ||
| ] { | ||
| let file = work.join(path); | ||
| fs::create_dir_all(file.parent().unwrap()).unwrap(); | ||
| fs::write(file, text).unwrap(); | ||
| } | ||
| fs::write(work.join("data.bin"), [0u8, 1, 2, 0, 255]).unwrap(); | ||
| git(&work, &["add", "."]); | ||
| git(&work, &["commit", "-qm", "First commit", "-m", "With a body line."]); | ||
| git(&work, &["tag", "-a", "v0.1.0", "-m", "First release"]); | ||
| let first = git(&work, &["rev-parse", "HEAD"]); | ||
| git(&work, &["rm", "-q", "old.txt"]); | ||
| // Matches the pattern glob* but isn't in the folder glob*. | ||
| fs::write(work.join("globber.txt"), "not in glob*\n").unwrap(); | ||
| git(&work, &["add", "globber.txt"]); | ||
| fs::write(work.join("src/main.rs"), "fn main() {\n println!(\"changed\");\n}\n").unwrap(); | ||
| git(&work, &["commit", "-qam", "Remove old.txt"]); | ||
| let removal = git(&work, &["rev-parse", "HEAD"]); | ||
| git(&work, &["checkout", "-qb", "side"]); | ||
| fs::write(work.join("side.txt"), "from the side\n").unwrap(); | ||
| git(&work, &["add", "side.txt"]); | ||
| git(&work, &["commit", "-qm", "Side work"]); | ||
| git(&work, &["checkout", "-q", "main"]); | ||
| git(&work, &["merge", "-q", "--no-ff", "--no-edit", "-m", "Merge side", "side"]); | ||
| let merge = git(&work, &["rev-parse", "HEAD"]); | ||
| let cacheinfo = format!("160000,{first},vendor/lib"); | ||
| git(&work, &["update-index", "--add", "--cacheinfo", &cacheinfo]); | ||
| fs::write(work.join("big.txt"), "x".repeat(1_200_000)).unwrap(); | ||
| git(&work, &["add", "big.txt"]); | ||
| git(&work, &["commit", "-qm", "Add a submodule and a big file"]); | ||
| git(&work, &["tag", "light"]); | ||
| let tip = git(&work, &["rev-parse", "HEAD"]); | ||
| git(&work, &["checkout", "-qb", "long", &first]); | ||
| for n in 1..=55 { | ||
| git(&work, &["commit", "-q", "--allow-empty", "-m", &format!("Long {n}")]); | ||
| } | ||
| git(&work, &["checkout", "-q", "main"]); | ||
| let out = host.git(&work, &["push", "-q", "ada@x:ada/site.git", "main", "side", "long", "v0.1.0", "light"]); | ||
| assert!(out.status.success(), "{}", common::stderr(&out)); | ||
| assert!(host.admin(&["create", "ada", "empty"]).status.success()); | ||
| Fixture { repos: host.repos.clone(), first, removal, merge, tip } | ||
| }) | ||
| } | ||
| fn server() -> Server { | ||
| Server::start(&fixture().repos) | ||
| } | ||
| fn location(response: &common::Response) -> &str { | ||
| response.header("location") | ||
| } | ||
| #[test] | ||
| fn index_lists_repositories_newest_first() { | ||
| let s = server(); | ||
| let page = s.get("/"); | ||
| assert_eq!(page.status, 200); | ||
| let html = page.text(); | ||
| assert!(html.contains("2 repositories"), "{html}"); | ||
| let site = html.find("ada/</span>site").expect("site listed"); | ||
| let empty = html.find("ada/</span>empty").expect("empty listed"); | ||
| assert!(site < empty, "the repository with commits comes first"); | ||
| assert!(html.contains("No commits yet")); | ||
| } | ||
| #[test] | ||
| fn every_page_sends_the_security_headers() { | ||
| let s = server(); | ||
| for path in ["/", "/ada/site/tree", "/ada/site/raw?path=src/main.rs", "/nope"] { | ||
| let page = s.get(path); | ||
| let csp = page.header("content-security-policy"); | ||
| assert!(csp.contains("default-src 'none'") && !csp.contains("script-src"), "{path}: {csp}"); | ||
| assert_eq!(page.header("x-content-type-options"), "nosniff", "{path}"); | ||
| assert_eq!(page.header("referrer-policy"), "no-referrer", "{path}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn static_assets_are_served_and_the_stylesheet_is_versioned() { | ||
| let s = server(); | ||
| let html = s.get("/").text(); | ||
| let start = html.find("/style.css?v=").expect("versioned stylesheet link"); | ||
| let url = &html[start..start + html[start..].find('"').unwrap()]; | ||
| let css = s.get(url); | ||
| assert_eq!(css.status, 200); | ||
| assert!(css.header("content-type").starts_with("text/css")); | ||
| assert!(css.header("cache-control").contains("immutable")); | ||
| assert!(css.text().contains("--accent")); | ||
| for (path, kind) in [ | ||
| ("/favicon.svg", "image/svg+xml"), | ||
| ("/fonts/display.woff2", "font/woff2"), | ||
| ("/fonts/text.woff2", "font/woff2"), | ||
| ("/fonts/mono.woff2", "font/woff2"), | ||
| ] { | ||
| let asset = s.get(path); | ||
| assert_eq!((asset.status, asset.header("content-type")), (200, kind), "{path}"); | ||
| assert!(!asset.body.is_empty(), "{path}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn repository_root_redirects_to_the_tree() { | ||
| let s = server(); | ||
| let page = s.get("/ada/site"); | ||
| assert_eq!(page.status, 303); | ||
| assert_eq!(location(&page), "/ada/site/tree"); | ||
| } | ||
| #[test] | ||
| fn tree_lists_folders_first_and_renders_the_readme() { | ||
| let s = server(); | ||
| let page = s.get("/ada/site/tree"); | ||
| assert_eq!(page.status, 200); | ||
| let html = page.text(); | ||
| let docs = html.find(">docs<").unwrap(); | ||
| let readme = html.find(">README.md<").unwrap(); | ||
| assert!(docs < readme, "folders come before files"); | ||
| assert!(html.contains("Commits<span class=\"n\">5</span>"), "commit count on main, side included"); | ||
| assert!(html.contains("Tags<span class=\"n\">2</span>")); | ||
| assert!(html.contains("Add a submodule and a big file"), "latest commit in the header"); | ||
| assert!(html.contains("git@git.um9i.dev:ada/site.git"), "clone address"); | ||
| // README rendering: Markdown, safe links and escaped HTML. | ||
| assert!(html.contains("<article class=\"markdown\"><h1>Fixture {onclick=alert(1) #main .skip}</h1>"), "{html}"); | ||
| assert!(html.contains("href=\"/ada/site/blob?ref=main&path=docs/guide.md\"")); | ||
| assert!(html.contains("href=\"/ada/site/blob?ref=main&path=src\"")); | ||
| assert!(html.contains("href=\"https://example.com\"")); | ||
| assert!(html.contains("src=\"/ada/site/raw?ref=main&path=img/logo.svg\"")); | ||
| assert!(html.contains("<script>alert(1)</script>")); | ||
| assert!(!html.contains("<script"), "no script element reaches the page"); | ||
| assert!(!html.contains("javascript:") && !html.contains("passwd")); | ||
| assert!(html.contains("<pre class=\"code\">") && html.contains("hl-"), "fenced code is highlighted"); | ||
| } | ||
| #[test] | ||
| fn tree_shows_submodules_without_links() { | ||
| let s = server(); | ||
| let html = s.get("/ada/site/tree?path=vendor").text(); | ||
| assert!(html.contains("class=\"entry sub\""), "{html}"); | ||
| assert!(html.contains(&format!("Submodule at {}", &fixture().first[..7]))); | ||
| assert!(!html.contains("path=vendor/lib\""), "the submodule isn't a link"); | ||
| } | ||
| #[test] | ||
| fn tree_breadcrumbs_and_parent_link() { | ||
| let s = server(); | ||
| let html = s.get("/ada/site/tree?path=docs").text(); | ||
| assert!(html.contains("<nav class=\"crumbs\"")); | ||
| assert!(html.contains("<b>docs</b>")); | ||
| assert!(html.contains("href=\"/ada/site/tree?ref=main\"><svg class=\"ic\""), "the .. row leads to the root"); | ||
| let root = s.get("/ada/site/tree").text(); | ||
| assert!(!root.contains("<nav class=\"crumbs\""), "no breadcrumbs at the root"); | ||
| } | ||
| #[test] | ||
| fn tree_at_a_tag_and_a_commit() { | ||
| let s = server(); | ||
| let at_tag = s.get("/ada/site/tree?ref=v0.1.0").text(); | ||
| assert!(at_tag.contains(">old.txt<"), "old.txt exists at v0.1.0"); | ||
| assert!(!at_tag.contains(">big.txt<")); | ||
| let at_commit = s.get(&format!("/ada/site/tree?ref={}", fixture().removal)).text(); | ||
| assert!(!at_commit.contains(">old.txt<")); | ||
| } | ||
| #[test] | ||
| fn file_view_highlights_with_line_numbers() { | ||
| let s = server(); | ||
| let page = s.get("/ada/site/blob?path=src/main.rs"); | ||
| assert_eq!(page.status, 200); | ||
| let html = page.text(); | ||
| assert!(html.contains("<pre class=\"gutter\" aria-hidden=\"true\">1\n2\n3\n</pre>"), "{html}"); | ||
| assert!(html.contains("hl-"), "highlighted"); | ||
| assert!(html.contains("changed") && !html.contains("<hi>"), "current content, escaped"); | ||
| assert!(html.contains("3 lines, 39 bytes")); | ||
| assert!(html.contains("<b>main.rs</b>")); | ||
| assert!(html.contains("href=\"/ada/site/raw?ref=main&path=src/main.rs\">Raw")); | ||
| // A second view comes from the cache and is identical. | ||
| assert_eq!(s.get("/ada/site/blob?path=src/main.rs").text(), html); | ||
| } | ||
| #[test] | ||
| fn markdown_files_have_preview_and_code_views() { | ||
| let s = server(); | ||
| let preview = s.get("/ada/site/blob?path=docs/guide.md").text(); | ||
| assert!(preview.contains("<article class=\"markdown\"><h1>Guide</h1>"), "{preview}"); | ||
| assert!(preview.contains("<table>")); | ||
| assert!(preview.contains("href=\"/ada/site/blob?ref=main&path=src/main.rs\""), "relative link resolved"); | ||
| assert!(preview.contains("aria-current=\"true\">Preview")); | ||
| let code = s.get("/ada/site/blob?path=docs/guide.md&view=code").text(); | ||
| assert!(code.contains("<pre class=\"gutter\"")); | ||
| assert!(code.contains("aria-current=\"true\">Code")); | ||
| assert!(!code.contains("<article class=\"markdown\">")); | ||
| } | ||
| #[test] | ||
| fn binary_and_oversized_files_are_not_shown_inline() { | ||
| let s = server(); | ||
| let binary = s.get("/ada/site/blob?path=data.bin").text(); | ||
| assert!(binary.contains("This is a binary file"), "{binary}"); | ||
| let big = s.get("/ada/site/blob?path=big.txt").text(); | ||
| assert!(big.contains("too large to show here"), "{big}"); | ||
| assert!(big.contains("1.1 MB")); | ||
| assert!(!big.contains("xxxxxxxxxx"), "the content isn't on the page"); | ||
| } | ||
| #[test] | ||
| fn raw_serves_files_with_safe_types() { | ||
| let s = server(); | ||
| let text = s.get("/ada/site/raw?path=src/main.rs"); | ||
| assert_eq!(text.status, 200); | ||
| assert_eq!(text.header("content-type"), "text/plain; charset=utf-8"); | ||
| assert!(text.text().starts_with("fn main()")); | ||
| let svg = s.get("/ada/site/raw?path=img/logo.svg"); | ||
| assert_eq!(svg.header("content-type"), "image/svg+xml"); | ||
| let binary = s.get("/ada/site/raw?path=data.bin"); | ||
| assert_eq!(binary.header("content-type"), "application/octet-stream"); | ||
| assert_eq!(binary.header("content-disposition"), "attachment; filename*=UTF-8''data.bin"); | ||
| assert_eq!(binary.body, [0u8, 1, 2, 0, 255]); | ||
| let big = s.get("/ada/site/raw?path=big.txt"); | ||
| assert_eq!(big.body.len(), 1_200_000, "Raw serves files too large to show"); | ||
| } | ||
| #[test] | ||
| fn file_paths_are_literal() { | ||
| let s = server(); | ||
| assert_eq!(s.get("/ada/site/blob?path=star%2A.txt").status, 200); | ||
| assert_eq!(s.get("/ada/site/blob?path=st%2A").status, 404, "a glob doesn't match star*.txt"); | ||
| assert_eq!(s.get("/ada/site/blob?path=%2A.txt").status, 404); | ||
| } | ||
| #[test] | ||
| fn folder_history_is_literal_too() { | ||
| let s = server(); | ||
| let html = s.get("/ada/site/tree?path=glob%2A").text(); | ||
| assert!(html.contains(">inside.txt<"), "{html}"); | ||
| // The folder's latest commit is the one that created it, not the later one that added | ||
| // globber.txt, which the pattern glob* would also match. | ||
| assert!(html.contains(">First commit</a></div>"), "{html}"); | ||
| } | ||
| #[test] | ||
| fn file_and_folder_links_reach_the_right_view() { | ||
| let s = server(); | ||
| let folder = s.get("/ada/site/blob?path=src"); | ||
| assert_eq!(folder.status, 303); | ||
| assert_eq!(location(&folder), "/ada/site/tree?ref=main&path=src"); | ||
| let file = s.get("/ada/site/tree?path=README.md"); | ||
| assert_eq!(file.status, 303); | ||
| assert_eq!(location(&file), "/ada/site/blob?ref=main&path=README.md"); | ||
| } | ||
| #[test] | ||
| fn history_lists_commits_with_tags_and_pages() { | ||
| let s = server(); | ||
| let html = s.get("/ada/site/log").text(); | ||
| // In git's own order, including the merged branch's commit. | ||
| let expected = git(&fixture().repos.join("ada/site.git"), &["log", "--format=%s", "main"]); | ||
| let order: Vec<usize> = expected | ||
| .lines() | ||
| .map(|subject| html.find(subject).unwrap_or_else(|| panic!("{subject} missing"))) | ||
| .collect(); | ||
| assert_eq!(order.len(), 5); | ||
| assert!(order.windows(2).all(|w| w[0] < w[1]), "out of order: {order:?}"); | ||
| assert!(html.contains(">v0.1.0</a>") && html.contains(">light</a>"), "tag chips"); | ||
| assert!(html.contains("Ada Lovelace committed 2026-01-02")); | ||
| assert!(!html.contains(">Older<"), "one page is enough for main"); | ||
| let first = s.get("/ada/site/log?ref=long").text(); | ||
| assert_eq!(first.matches("class=\"commit-row\"").count(), 50); | ||
| assert!(first.contains("Long 55") && !first.contains("Long 5<")); | ||
| assert!(first.contains("page=1\">Older<") && !first.contains(">Newer<")); | ||
| let second = s.get("/ada/site/log?ref=long&page=1").text(); | ||
| assert_eq!(second.matches("class=\"commit-row\"").count(), 6, "Long 1-5 and First commit"); | ||
| assert!(second.contains("page=0\">Newer<") && !second.contains(">Older<")); | ||
| } | ||
| #[test] | ||
| fn commit_shows_message_facts_and_diff() { | ||
| let s = server(); | ||
| let f = fixture(); | ||
| let html = s.get(&format!("/ada/site/commit?id={}", f.removal)).text(); | ||
| assert!(html.contains("<h2 class=\"ctitle\">Remove old.txt</h2>")); | ||
| assert!(html.contains(&format!("<span class=\"sha\">{}</span>", &f.removal[..12]))); | ||
| assert!(html.contains(&format!("id={}\" ", f.first)) || html.contains(&format!("id={}\"", f.first)), "parent link"); | ||
| assert!(html.contains("3 files changed"), "{html}"); | ||
| assert!(html.contains("<span class=\"status\">Deleted</span>")); | ||
| // A deleted file links to its last version, in the parent commit. | ||
| assert!(html.contains(&format!("href=\"/ada/site/blob?ref={}&path=old.txt\"", f.first))); | ||
| assert!(html.contains("<tr class=\"del\"><td class=\"num\" data-n=\"1\"></td><td class=\"num\" data-n=\"\"></td><td class=\"line\" data-s=\"-\">going away</td></tr>")); | ||
| assert!(html.contains("data-s=\"+\"> println!(\"changed\");</td>")); | ||
| assert!(html.contains(&format!("href=\"/ada/site/tree?ref={}\">Browse files", f.removal))); | ||
| let first = s.get(&format!("/ada/site/commit?id={}", &f.first[..10])).text(); | ||
| assert!(first.contains("With a body line."), "commit body"); | ||
| assert!(first.contains("<span class=\"status\">Added</span>")); | ||
| assert!(first.contains("Binary file changed.")); | ||
| assert!(!first.contains("<dt>Parent</dt>"), "the root commit has no parent"); | ||
| } | ||
| #[test] | ||
| fn merge_commits_show_what_they_brought_in() { | ||
| let s = server(); | ||
| let html = s.get(&format!("/ada/site/commit?id={}", fixture().merge)).text(); | ||
| assert!(html.contains("1 file changed"), "{html}"); | ||
| assert!(html.contains("<b>side.txt</b>")); | ||
| assert_eq!(html.matches("<dt>Parent</dt>").count(), 1); | ||
| assert_eq!(html.matches("class=\"sha\" href").count(), 2, "both parents are linked"); | ||
| } | ||
| #[test] | ||
| fn tags_page_lists_annotated_and_lightweight_tags() { | ||
| let s = server(); | ||
| let html = s.get("/ada/site/tags").text(); | ||
| assert!(html.contains("<span class=\"tname\">v0.1.0</span><span class=\"tnote\">First release</span>"), "{html}"); | ||
| assert!(html.contains("<span class=\"tname\">light</span>")); | ||
| assert!(html.contains(&fixture().tip[..7])); | ||
| assert!(html.contains("href=\"/ada/site/tree?ref=v0.1.0\">Browse files")); | ||
| } | ||
| #[test] | ||
| fn ref_menu_lists_branches_and_tags() { | ||
| let s = server(); | ||
| let html = s.get("/ada/site/tree?ref=side").text(); | ||
| for name in ["main", "side", "long", "v0.1.0", "light"] { | ||
| assert!(html.contains(&format!(">{name}</a>")), "{name} missing from the menu"); | ||
| } | ||
| assert!(html.contains("aria-current=\"true\">side</a>")); | ||
| } | ||
| #[test] | ||
| fn empty_repository_explains_how_to_start() { | ||
| let s = server(); | ||
| let page = s.get("/ada/empty/tree"); | ||
| assert_eq!(page.status, 200); | ||
| let html = page.text(); | ||
| assert!(html.contains("This repository is empty")); | ||
| assert!(html.contains("git push git@git.um9i.dev:ada/empty.git main")); | ||
| let tags = s.get("/ada/empty/tags").text(); | ||
| assert!(tags.contains("No tags yet")); | ||
| } | ||
| #[test] | ||
| fn bad_requests_are_not_found() { | ||
| let s = server(); | ||
| let missing = [ | ||
| "/nope", | ||
| "/ada/nope/tree", | ||
| "/Ada/site/tree", | ||
| "/ada/site/unknown", | ||
| "/ada/site/tree?ref=--help", | ||
| "/ada/site/tree?ref=main..side", | ||
| "/ada/site/tree?ref=main%40%7B0%7D", | ||
| "/ada/site/tree?ref=missing", | ||
| "/ada/site/tree?path=nope", | ||
| "/ada/site/blob?path=../README.md", | ||
| "/ada/site/blob?path=docs/../README.md", | ||
| "/ada/site/blob", | ||
| "/ada/site/commit?id=XYZ", | ||
| "/ada/site/commit?id=abc", | ||
| "/ada/site/commit?id=0000000000", | ||
| "/ada/site/log?page=400000000000000000", | ||
| ]; | ||
| for path in missing { | ||
| let page = s.get(path); | ||
| assert_eq!(page.status, 404, "{path}"); | ||
| assert!(page.text().contains("Nothing here"), "{path}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn writes_are_refused() { | ||
| let s = server(); | ||
| let mut stream = std::net::TcpStream::connect(("127.0.0.1", s.port)).unwrap(); | ||
| use std::io::{Read, Write}; | ||
| write!(stream, "POST /ada/site/tree HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap(); | ||
| let mut reply = String::new(); | ||
| stream.read_to_string(&mut reply).unwrap(); | ||
| assert!(reply.starts_with("HTTP/1.1 405"), "{reply}"); | ||
| } | ||