//! `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 "), "{}", 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.example.test: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.example.test:ada/alpha.git\ngit@git.example.test: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"); let out = host.ssh("ada", "delete notes --yes"); assert!(out.status.success(), "{}", stderr(&out)); assert!(stdout(&out).contains("trash"), "{}", stdout(&out)); assert!(!host.repo("ada", "notes").exists()); assert_eq!(trash(&host, "ada").len(), 1, "the repository waits in the trash"); assert!(host.logged().contains("ada/notes.git moved to the trash"), "{}", host.logged()); assert!(!host.ssh("ada", "delete notes --yes").status.success(), "a missing repository can't be deleted"); assert_eq!(stdout(&host.ssh("ada", "list")), "git@git.example.test:ada/alpha.git\n", "the trash isn't listed"); } /// The names in an owner's trash. fn trash(host: &Host, owner: &str) -> Vec { let mut names: Vec = fs::read_dir(host.repos.join(owner).join(".trash")) .map(|dir| dir.map(|e| e.unwrap().file_name().into_string().unwrap()).collect()) .unwrap_or_default(); names.sort(); names } #[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"); // The address without `.git` names the same repository. let out = host.git(&clone, &["clone", "-q", "ada@x:ada/project", "bare-name"]); assert!(out.status.success(), "{}", stderr(&out)); assert!(clone.join("bare-name/hello.txt").is_file()); // 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.example.test: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 deleted_repositories_can_be_restored_until_purged() { let host = Host::new("admin-trash"); let dir = work("admin-trash-work", "main"); assert!(host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main"]).status.success()); assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); let [entry] = <[String; 1]>::try_from(trash(&host, "ada")).unwrap(); assert!(entry.starts_with("tools."), "{entry}"); let listed = stdout(&host.admin(&["trash"])); assert!(listed.contains(&format!("ada {entry}")) && listed.contains("deleted 0 days ago"), "{listed}"); // Restoring never replaces what is at the name now. assert!(host.admin(&["create", "ada", "tools"]).status.success()); let out = host.admin(&["restore", "ada", &entry]); assert!(!out.status.success()); assert!(stderr(&out).contains("--as"), "{}", stderr(&out)); let out = host.admin(&["restore", "ada", &entry, "--as", "tools-old"]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(git(&host.repo("ada", "tools-old"), &["log", "--format=%s", "main"]), "First"); assert!(trash(&host, "ada").is_empty()); assert!(!host.admin(&["restore", "ada", &entry]).status.success(), "an entry restores once"); assert!(!host.admin(&["restore", "ada", "../../etc"]).status.success(), "entries are validated"); // A purge keeps recent entries and removes old enough ones. assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); assert!(host.admin(&["purge"]).status.success()); assert_eq!(trash(&host, "ada").len(), 1, "a fresh entry survives the default purge"); let out = host.admin(&["purge", "--older-than-days", "0"]); assert!(out.status.success(), "{}", stderr(&out)); assert!(stdout(&out).contains("purged ada/.trash/tools."), "{}", stdout(&out)); assert!(trash(&host, "ada").is_empty()); } #[test] fn overwritten_and_deleted_branches_stay_recoverable() { let host = Host::new("ssh-recovery"); let dir = work("ssh-recovery-work", "main"); let remote = "ada@x:ada/history.git"; assert!(host.git(&dir, &["push", "-q", remote, "main", "main:topic"]).status.success()); let first = git(&dir, &["rev-parse", "HEAD"]); // Rewrite main and force it over the old commit, then delete topic. git(&dir, &["commit", "-q", "--amend", "-m", "Rewritten"]); let rewritten = git(&dir, &["rev-parse", "HEAD"]); assert!(host.git(&dir, &["push", "-qf", remote, "main"]).status.success()); assert!(host.git(&dir, &["push", "-q", remote, ":topic"]).status.success()); let repo = host.repo("ada", "history"); assert_eq!(git(&repo, &["rev-parse", "main@{1}"]), first, "the reflog keeps the overwritten commit"); let log = fs::read_to_string(repo.join("gitv-push.log")).unwrap(); let lines: Vec> = log.lines().map(|l| l.split(' ').skip(1).collect()).collect(); assert_eq!( lines, [ vec!["-", first.as_str(), "refs/heads/main"], vec!["-", first.as_str(), "refs/heads/topic"], vec![first.as_str(), rewritten.as_str(), "refs/heads/main"], vec![first.as_str(), "-", "refs/heads/topic"], ], "{log}" ); assert_eq!(git(&repo, &["cat-file", "-t", &first]), "commit", "the deleted branch's commit is still there"); } #[test] fn the_configuration_file_sets_the_host_and_the_forced_command() { let host = Host::new("ssh-config"); let config = host.dir.join("gitv.conf"); fs::write(&config, "# this server\nhost = Code.Example.org\ncommand = /opt/gitv/bin/gitv\n").unwrap(); let admin = |args: &[&str]| { std::process::Command::new(&*common::GITV) .args(args) .env("GITV_CONFIG", &config) .env("GITV_REPOS", &host.repos) .env("GITV_KEYS", &host.keys) .output() .unwrap() }; let out = admin(&["create", "ada", "tools"]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(stdout(&out).trim(), "git@code.example.org:ada/tools.git"); let key = host.dir.join("ada.pub"); fs::write(&key, ed25519_key(3)).unwrap(); assert!(admin(&["add-key", "ada", key.to_str().unwrap()]).status.success()); assert!(fs::read_to_string(&host.keys).unwrap().starts_with("restrict,command=\"/opt/gitv/bin/gitv serve ada\"")); // A mistake stops every command, and a key holder isn't shown the server's paths. fs::write(&config, "hostname = code.example.org\n").unwrap(); let out = admin(&["create", "ada", "other"]); assert!(!out.status.success()); assert!(stderr(&out).contains("unknown setting `hostname`"), "{}", stderr(&out)); let out = std::process::Command::new(&*common::GITV) .args(["serve", "ada"]) .env("SSH_ORIGINAL_COMMAND", "list") .env("GITV_CONFIG", &config) .env("GITV_REPOS", &host.repos) .env("GITV_LOG", host.log()) .output() .unwrap(); assert!(!out.status.success()); assert!(stderr(&out).contains("misconfigured") && !stderr(&out).contains("gitv.conf"), "{}", stderr(&out)); assert!(host.logged().contains("unknown setting `hostname`"), "{}", host.logged()); } #[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)); } #[test] fn symlinked_repositories_are_refused() { let host = Host::new("ssh-symlink-repo"); let dir = work("ssh-symlink-repo-work", "main"); assert!(host.git(&dir, &["push", "-q", "bob@x:bob/real.git", "main"]).status.success()); // ada/link.git points at bob's repository: following it would cross the owner boundary. fs::create_dir_all(host.repos.join("ada")).unwrap(); std::os::unix::fs::symlink(host.repo("bob", "real"), host.repo("ada", "link")).unwrap(); let clone = scratch("ssh-symlink-repo-clone"); assert!(!host.git(&clone, &["clone", "-q", "ada@x:ada/link.git"]).status.success(), "read through a symlink"); let out = host.git(&dir, &["push", "-q", "ada@x:ada/link.git", "main:other"]); assert!(!out.status.success(), "wrote through a symlink"); assert!(git(&host.repo("bob", "real"), &["branch", "--list", "other"]).is_empty()); assert_eq!(stdout(&host.ssh("ada", "list")), "", "symlinks aren't listed"); assert!(!host.ssh("ada", "delete link --yes").status.success()); assert!(host.repo("bob", "real").join("HEAD").is_file(), "the target survives"); } #[test] fn symlinked_owner_directories_are_refused() { let host = Host::new("ssh-symlink-owner"); let outside = scratch("ssh-symlink-owner-outside"); std::os::unix::fs::symlink(&outside, host.repos.join("ada")).unwrap(); let dir = work("ssh-symlink-owner-work", "main"); let out = host.git(&dir, &["push", "-q", "ada@x:ada/new.git", "main"]); assert!(!out.status.success(), "created a repository through a symlinked owner directory"); assert!(!host.ssh("ada", "create other").status.success()); assert!(fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the tree"); } #[test] fn simultaneous_first_pushes_all_succeed() { let host = std::sync::Arc::new(Host::new("ssh-race")); let dir = work("ssh-race-work", "main"); // Each push sends its own branch: racing to create one *branch* is git's business, but // racing to create the *repository* must not fail anyone. let pushes: Vec<_> = (0..6) .map(|n| { let (host, dir) = (host.clone(), dir.clone()); std::thread::spawn(move || host.git(&dir, &["push", "-q", "ada@x:ada/raced.git", &format!("main:b{n}")])) }) .collect(); for push in pushes { let out = push.join().unwrap(); assert!(out.status.success(), "{}", stderr(&out)); } let leftovers: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect(); assert_eq!(leftovers, [std::ffi::OsString::from("raced.git")], "no staging directories left behind"); assert_eq!(git(&host.repo("ada", "raced"), &["for-each-ref", "--format=%(refname:lstrip=2)"]).lines().count(), 6); assert_eq!(host.logged(), "", "losing a creation race is ordinary and isn't logged"); } #[test] fn add_key_failure_installs_nothing() { let host = Host::new("admin-keys-atomic"); // A file where the owner's directory should go makes preparing the owner fail. fs::write(host.repos.join("ada"), "not a directory").unwrap(); let key = host.dir.join("ada.pub"); fs::write(&key, ed25519_key(3)).unwrap(); let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); assert!(!out.status.success()); assert!(!host.keys.exists(), "the key was installed although the command failed"); // Once the problem is fixed, a retry succeeds rather than finding the key already there. fs::remove_file(host.repos.join("ada")).unwrap(); let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); assert!(out.status.success(), "{}", stderr(&out)); } #[test] fn a_failed_key_write_leaves_no_temporary_file() { use std::os::unix::process::CommandExt; let host = Host::new("admin-keys-cleanup"); let key = host.dir.join("ada.pub"); fs::write(&key, ed25519_key(4)).unwrap(); let mut command = std::process::Command::new(&*common::GITV); command .args(["add-key", "ada", key.to_str().unwrap()]) .env("GITV_HOST", common::TEST_HOST) .env("GITV_CONFIG", common::NO_CONFIG) .env("GITV_REPOS", &host.repos) .env("GITV_KEYS", &host.keys); // Files may grow to 16 bytes, so writing the new keys file fails part way. With SIGXFSZ // ignored the write returns an error instead of killing the process. // SAFETY: signal and setrlimit are async-signal-safe and the closure does nothing else. unsafe { command.pre_exec(|| { nix::libc::signal(nix::libc::SIGXFSZ, nix::libc::SIG_IGN); nix::sys::resource::setrlimit(nix::sys::resource::Resource::RLIMIT_FSIZE, 16, 16) .map_err(std::io::Error::from) }); } let out = command.output().unwrap(); assert!(!out.status.success(), "the write should have failed"); assert!(stderr(&out).contains("File too large"), "it failed while writing: {}", stderr(&out)); assert!(!host.keys.exists(), "no keys file was published"); let left: Vec<_> = fs::read_dir(&host.dir) .unwrap() .map(|e| e.unwrap().file_name().into_string().unwrap()) .filter(|n| n.starts_with(".authorized_keys")) .collect(); assert!(left.is_empty(), "temporary files left behind: {left:?}"); } #[test] fn add_key_respects_existing_lines() { let host = Host::new("admin-keys-existing"); let blob = ed25519_key(5); let blob = blob.split_whitespace().nth(1).unwrap(); // Written by hand: options in front, a comment after, and no final newline. fs::write(&host.keys, format!("restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob} laptop")) .unwrap(); let same = host.dir.join("same.pub"); fs::write(&same, ed25519_key(5)).unwrap(); let out = host.admin(&["add-key", "bob", same.to_str().unwrap()]); assert!(!out.status.success(), "the same key was registered twice"); assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); let other = host.dir.join("other.pub"); fs::write(&other, ed25519_key(6)).unwrap(); assert!(host.admin(&["add-key", "bob", other.to_str().unwrap()]).status.success()); let keys = fs::read_to_string(&host.keys).unwrap(); let lines: Vec<&str> = keys.lines().collect(); assert_eq!(lines.len(), 2, "{keys}"); assert!( lines[0].ends_with(" laptop") && lines[1].starts_with("restrict,command=\"/usr/local/bin/gitv serve bob\"") ); } #[test] fn the_readme_fake_ssh_script_works() { let host = Host::new("ssh-script"); let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/fake-ssh"); let dir = work("ssh-script-work", "main"); let out = common::git_cmd(&dir) .env("GIT_SSH_COMMAND", &script) .env("GITV_REPOS", &host.repos) .args(["push", "-q", "um9i@local:um9i/demo.git", "main"]) .output() .unwrap(); assert!(out.status.success(), "{}", stderr(&out)); assert!(host.repo("um9i", "demo").join("HEAD").is_file()); } #[test] fn default_branch_repair_keeps_branch_names_exact() { use std::os::unix::ffi::OsStrExt; // Names that whitespace splitting or UTF-8 conversion would mangle. let names: [&[u8]; 2] = ["trunk\u{a0}line".as_bytes(), b"caf\xe9"]; for (n, name) in names.iter().enumerate() { let host = Host::new(&format!("ssh-head-bytes-{n}")); let dir = work(&format!("ssh-head-bytes-{n}-work"), "main"); let target = [b"main:refs/heads/".as_slice(), name].concat(); let out = common::git_cmd(&dir) .env("GIT_SSH_COMMAND", host.ssh_script()) .args([std::ffi::OsStr::new("push"), "-q".as_ref(), "ada@x:ada/odd.git".as_ref()]) .arg(std::ffi::OsStr::from_bytes(&target)) .output() .unwrap(); assert!(out.status.success(), "{}", stderr(&out)); let head = common::git_cmd(&host.repo("ada", "odd")).args(["symbolic-ref", "HEAD"]).output().unwrap(); assert_eq!( head.stdout, [b"refs/heads/".as_slice(), name, b"\n"].concat(), "HEAD names the pushed branch exactly" ); let clone = scratch(&format!("ssh-head-bytes-{n}-clone")); let out = host.git(&clone, &["clone", "-q", "ada@x:ada/odd.git", "copy"]); assert!(out.status.success(), "{}", stderr(&out)); assert!(clone.join("copy/hello.txt").is_file(), "the clone checked out the default branch"); } } #[test] fn commented_keys_do_not_block_registration() { let host = Host::new("admin-keys-comments"); let key = ed25519_key(8); let blob = key.split_whitespace().nth(1).unwrap(); // The key is retired (commented out) and also mentioned in another key's comment. let other = ed25519_key(9); let other_blob = other.split_whitespace().nth(1).unwrap(); fs::write( &host.keys, format!( "# restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob}\n\ # ssh-ed25519 {blob} old laptop\n\ command=\"/usr/local/bin/gitv serve bob\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {other_blob} replaces ssh-ed25519 {blob}\n" ), ) .unwrap(); let file = host.dir.join("ada.pub"); fs::write(&file, &key).unwrap(); let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]); assert!(out.status.success(), "{}", stderr(&out)); // A real duplicate behind quoted options with spaces is still caught. let again = host.dir.join("bob.pub"); fs::write(&again, &other).unwrap(); let out = host.admin(&["add-key", "carol", again.to_str().unwrap()]); assert!(!out.status.success()); assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); } #[test] fn tab_separated_keys_are_recognised() { let host = Host::new("admin-keys-tabs"); let key = ed25519_key(11); let blob = key.split_whitespace().nth(1).unwrap(); // An active key written with tabs between its fields, with and without options. fs::write( &host.keys, format!("ssh-ed25519\t{blob}\tlaptop\nrestrict\tssh-ed25519\t{}\n", { let other = ed25519_key(12); other.split_whitespace().nth(1).unwrap().to_string() }), ) .unwrap(); for (seed, owner) in [(11, "bob"), (12, "carol")] { let file = host.dir.join(format!("{owner}.pub")); fs::write(&file, ed25519_key(seed)).unwrap(); let out = host.admin(&["add-key", owner, file.to_str().unwrap()]); assert!(!out.status.success(), "key {seed} was registered a second time"); assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); } } #[test] fn creation_never_replaces_what_is_at_the_name() { let host = Host::new("admin-create-noreplace"); // An empty directory (which a plain rename would silently replace) and a symlink. fs::create_dir_all(host.repo("ada", "empty")).unwrap(); let elsewhere = scratch("admin-create-noreplace-elsewhere"); std::os::unix::fs::symlink(&elsewhere, host.repo("ada", "link")).unwrap(); for name in ["empty", "link"] { let out = host.admin(&["create", "ada", name]); assert!(!out.status.success(), "{name} was created over"); assert!(stderr(&out).contains("already exists"), "{name}: {}", stderr(&out)); } assert!(fs::read_dir(host.repo("ada", "empty")).unwrap().next().is_none(), "the directory is untouched"); assert!(fs::read_dir(&elsewhere).unwrap().next().is_none(), "nothing was written through the symlink"); let names: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect(); assert_eq!(names.len(), 2, "no staging directory left behind: {names:?}"); } #[test] fn purging_removes_links_inside_a_repository_without_following_them() { let host = Host::new("admin-delete-links"); assert!(host.admin(&["create", "ada", "tools"]).status.success()); let outside = scratch("admin-delete-links-outside"); fs::write(outside.join("precious.txt"), "keep").unwrap(); std::os::unix::fs::symlink(&outside, host.repo("ada", "tools").join("escape")).unwrap(); let out = host.admin(&["delete", "ada", "tools", "--yes"]); assert!(out.status.success(), "{}", stderr(&out)); assert!(!host.repo("ada", "tools").exists()); let out = host.admin(&["purge", "--older-than-days", "0"]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(fs::read_to_string(outside.join("precious.txt")).unwrap(), "keep"); assert!(trash(&host, "ada").is_empty(), "the trash is emptied"); assert_eq!(fs::read_dir(host.repos.join("ada")).unwrap().count(), 1, "only the trash itself is left"); } #[test] fn a_failed_first_push_tells_the_operator_why() { let host = Host::new("ssh-first-push-log"); let elsewhere = scratch("ssh-first-push-log-elsewhere"); fs::create_dir_all(host.repos.join("ada")).unwrap(); std::os::unix::fs::symlink(&elsewhere, host.repo("ada", "taken")).unwrap(); let dir = work("ssh-first-push-log-work", "main"); let out = host.git(&dir, &["push", "-q", "ada@x:ada/taken.git", "main"]); assert!(!out.status.success()); // The client gets the generic answer, without server details. assert!(stderr(&out).contains("gitv: repository unavailable"), "{}", stderr(&out)); assert!(!stderr(&out).contains("already exists"), "{}", stderr(&out)); // The operator gets the cause. let log = host.logged(); assert!(log.contains("first push to ada/taken.git couldn't create it: repository already exists"), "{log}"); } #[test] fn ssh_create_keeps_server_details_for_the_operator() { let host = Host::new("ssh-create-private"); // A file where the owner's directory should be: creation fails on the server's side. fs::write(host.repos.join("ada"), "not a directory").unwrap(); let out = host.ssh("ada", "create notes"); assert!(!out.status.success()); let said = stderr(&out); assert!(said.contains("couldn't create the repository; the server's operator can see why"), "{said}"); assert!(!said.contains(host.repos.to_str().unwrap()), "a server path reached the client: {said}"); let log = host.logged(); assert!(log.contains("ssh create of ada/notes.git failed:") && log.contains("is not a directory"), "{log}"); // An administrator running the same thing sees the details directly. let out = host.admin(&["create", "ada", "notes"]); assert!(!out.status.success()); assert!(stderr(&out).contains("is not a directory"), "{}", stderr(&out)); // "Already exists" is safe to tell anyone. fs::remove_file(host.repos.join("ada")).unwrap(); assert!(host.ssh("ada", "create notes").status.success()); let out = host.ssh("ada", "create notes"); assert!(stderr(&out).contains("gitv: repository already exists"), "{}", stderr(&out)); } /// The owner sshd would run `gitv serve` for when `key` connects: the forced command of the /// first active line holding that key, as sshd reads authorized_keys. `None` means sshd /// refuses the key. fn sshd_owner(keys: &std::path::Path, key: &str) -> Option { let blob = key.split_whitespace().nth(1).unwrap(); let text = fs::read_to_string(keys).unwrap_or_default(); let line = text .lines() .filter(|l| !l.trim_start().starts_with('#')) .find(|l| l.split([' ', '\t']).any(|field| field == blob))?; let command = line.split("serve ").nth(1)?; Some(command.split('"').next()?.to_string()) } /// The fingerprint `ssh-keygen -l` prints for a key file. fn ssh_keygen_fingerprint(file: &std::path::Path) -> String { let out = std::process::Command::new("ssh-keygen").arg("-lf").arg(file).output().unwrap(); assert!(out.status.success(), "{}", stderr(&out)); stdout(&out).split_whitespace().nth(1).unwrap().to_string() } #[test] fn keys_are_listed_and_revoked_one_at_a_time() { let host = Host::new("admin-keys-revoke"); let add = |owner: &str, seed: u8, label: &str| { let file = host.dir.join(format!("{owner}-{seed}.pub")); fs::write(&file, ed25519_key(seed)).unwrap(); let out = host.admin(&["add-key", owner, file.to_str().unwrap(), "--label", label]); assert!(out.status.success(), "{}", stderr(&out)); file }; let laptop = add("ada", 21, "ada's laptop"); add("ada", 22, "desktop"); add("bob", 23, "bob's phone"); let out = host.admin(&["create", "ada", "tools"]); assert!(out.status.success(), "{}", stderr(&out)); let listed = stdout(&host.admin(&["keys"])); let rows: Vec<&str> = listed.lines().collect(); assert_eq!(rows.len(), 3, "{listed}"); let laptop_print = ssh_keygen_fingerprint(&laptop); assert!(rows[0].starts_with("ada ") && rows[0].contains(&laptop_print), "{listed}"); assert!(rows[0].ends_with(" ada's laptop"), "the label is kept whole: {listed}"); assert!(rows[2].starts_with("bob ") && rows[2].ends_with("bob's phone"), "{listed}"); let only_ada = stdout(&host.admin(&["keys", "ada"])); assert_eq!(only_ada.lines().count(), 2, "{only_ada}"); assert!(!only_ada.contains("bob"), "{only_ada}"); // A fingerprint that matches nothing changes nothing. let before = fs::read(&host.keys).unwrap(); let out = host.admin(&["remove-key", "SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"]); assert!(!out.status.success()); assert!(stderr(&out).contains("no key has the fingerprint"), "{}", stderr(&out)); assert_eq!(fs::read(&host.keys).unwrap(), before); // Revoking the laptop (prefix optional) leaves the desktop working. let bare = laptop_print.strip_prefix("SHA256:").unwrap(); let out = host.admin(&["remove-key", bare]); assert!(out.status.success(), "{}", stderr(&out)); assert!(stdout(&out).contains("ada ada's laptop"), "{}", stdout(&out)); assert_eq!(sshd_owner(&host.keys, &ed25519_key(21)), None, "the revoked key no longer gets in"); let owner = sshd_owner(&host.keys, &ed25519_key(22)).expect("the other key still gets in"); let out = host.ssh(&owner, "list"); assert!(out.status.success() && stdout(&out).contains("ada/tools.git"), "{}", stderr(&out)); assert_eq!(sshd_owner(&host.keys, &ed25519_key(23)).as_deref(), Some("bob")); assert!(!stdout(&host.admin(&["keys"])).contains(&laptop_print)); } #[test] fn removing_a_key_keeps_every_other_line_exactly() { let host = Host::new("admin-keys-remove-exact"); let blob = |seed| ed25519_key(seed).split_whitespace().nth(1).unwrap().to_string(); // Hand-written: a comment, options with quoted spaces, tabs, a non-GITv key, and the key // to remove last with no final newline. let kept = format!( "# retired: ssh-ed25519 {}\n\ command=\"/usr/local/bin/gitv serve bob\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {} work\n\ ssh-ed25519\t{}\tbackup box\n", blob(31), blob(32), blob(33) ); fs::write(&host.keys, format!("{kept}restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {}", blob(31))) .unwrap(); let listed = stdout(&host.admin(&["keys"])); assert_eq!(listed.lines().count(), 3, "the commented-out key isn't listed: {listed}"); assert!(listed.contains("bob ") && listed.contains("- ") && listed.contains("backup box"), "{listed}"); let file = host.dir.join("ada.pub"); fs::write(&file, ed25519_key(31)).unwrap(); let out = host.admin(&["remove-key", &ssh_keygen_fingerprint(&file)]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(fs::read_to_string(&host.keys).unwrap(), kept, "only the active line went"); } #[test] fn key_labels_stay_on_one_line() { let host = Host::new("admin-keys-labels"); let file = host.dir.join("ada.pub"); fs::write(&file, ed25519_key(41)).unwrap(); for label in ["", " ", "two\nlines", "\u{1b}[31mred", &"x".repeat(65)] { let out = host.admin(&["add-key", "ada", file.to_str().unwrap(), "--label", label]); assert!(!out.status.success(), "{label:?} was accepted"); } assert!(!host.keys.exists(), "no key was written"); } #[test] fn descriptions_are_set_shown_and_removed() { let host = Host::new("ssh-description"); assert!(host.ssh("ada", "create tools").status.success()); // `git init` writes a placeholder, which doesn't count as a description. let out = host.ssh("ada", "description tools"); assert!(out.status.success() && stdout(&out).is_empty(), "{}", stdout(&out)); assert!(host.ssh("ada", "description tools A small toolbox").status.success()); assert_eq!(stdout(&host.ssh("ada", "description tools")), "A small toolbox\n"); assert_eq!(fs::read_to_string(host.repo("ada", "tools").join("description")).unwrap(), "A small toolbox\n"); // Quoted, as one argument, from the admin command too. let out = host.admin(&["description", "ada", "tools", " Tools for ada "]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(stdout(&host.ssh("ada", "description tools")), "Tools for ada\n"); for bad in ["description tools 'two\nlines'", &format!("description tools {}", "x".repeat(161))] { let out = host.ssh("ada", bad); assert!(!out.status.success(), "{bad} was accepted"); assert!(stderr(&out).contains("one line of at most 160"), "{}", stderr(&out)); } assert_eq!(stdout(&host.ssh("ada", "description tools")), "Tools for ada\n", "a refusal changes nothing"); assert!(host.ssh("ada", "description tools ''").status.success()); assert!(!host.repo("ada", "tools").join("description").exists()); // Only the owner's own repositories. assert!(!host.ssh("bob", "description tools Mine now").status.success()); let leftovers: Vec<_> = fs::read_dir(host.repo("ada", "tools")) .unwrap() .map(|e| e.unwrap().file_name().into_string().unwrap()) .filter(|n| n.starts_with(".description")) .collect(); assert!(leftovers.is_empty(), "{leftovers:?}"); } #[test] fn the_default_branch_can_be_chosen_among_existing_branches() { let host = Host::new("ssh-default-branch"); let dir = work("ssh-default-branch-work", "main"); git(&dir, &["branch", "release"]); let out = host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main", "release"]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "main\n"); let out = host.ssh("ada", "default-branch tools release"); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "release\n"); let head = common::git_cmd(&host.repo("ada", "tools")).args(["symbolic-ref", "HEAD"]).output().unwrap(); assert_eq!(head.stdout, b"refs/heads/release\n"); // Names that aren't existing branches, or aren't branch names at all, change nothing. for bad in ["missing", "-x", "../main", "HEAD", "refs/heads/main", "main^"] { let out = host.ssh("ada", &format!("default-branch tools '{bad}'")); assert!(!out.status.success(), "{bad} was accepted"); assert!(stderr(&out).contains("no branch named"), "{bad}: {}", stderr(&out)); } assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "release\n"); let out = host.admin(&["default-branch", "ada", "tools", "main"]); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "main\n"); assert!(!host.ssh("bob", "default-branch tools release").status.success()); } #[test] fn adding_a_key_again_with_a_label_renames_it() { let host = Host::new("admin-keys-relabel"); let file = host.dir.join("ada.pub"); fs::write(&file, ed25519_key(51)).unwrap(); let blob = ed25519_key(52).split_whitespace().nth(1).unwrap().to_string(); // Another key, written by hand: options with quoted spaces, an old comment, no final newline. let handwritten = format!("command=\"/usr/local/bin/gitv serve ada\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {blob}"); fs::write(&host.keys, format!("# keep me\n{handwritten} old laptop")).unwrap(); assert!(host.admin(&["add-key", "ada", file.to_str().unwrap()]).status.success()); // Again without a label is still a mistake. let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]); assert!(!out.status.success() && stderr(&out).contains("already registered"), "{}", stderr(&out)); // With one, the key is renamed in place. let before = fs::read_to_string(&host.keys).unwrap(); let out = host.admin(&["add-key", "ada", file.to_str().unwrap(), "--label", "omarchy"]); assert!(out.status.success(), "{}", stderr(&out)); assert!(stdout(&out).starts_with("relabelled SHA256:") && stdout(&out).trim_end().ends_with(" omarchy")); let after = fs::read_to_string(&host.keys).unwrap(); assert_eq!(after.lines().count(), before.lines().count(), "no line was added"); assert_eq!(after.lines().nth(2).unwrap(), format!("{} omarchy", before.lines().nth(2).unwrap())); let out = host.admin(&["add-key", "ada", file.to_str().unwrap(), "--label", "work laptop"]); assert!(out.status.success(), "{}", stderr(&out)); assert!( fs::read_to_string(&host.keys) .unwrap() .lines() .nth(2) .unwrap() .ends_with(&format!("{} work laptop", ed25519_key(51).split_whitespace().nth(1).unwrap())) ); // A hand-written line keeps its options; only the comment changes, and the ending stays. let other = host.dir.join("other.pub"); fs::write(&other, ed25519_key(52)).unwrap(); let out = host.admin(&["add-key", "ada", other.to_str().unwrap(), "--label", "desk"]); assert!(out.status.success(), "{}", stderr(&out)); let text = fs::read_to_string(&host.keys).unwrap(); assert!(text.starts_with(&format!("# keep me\n{handwritten} desk\n")), "{text}"); assert!(stdout(&host.admin(&["keys", "ada"])).contains(" desk\n")); // A key never moves to another owner, and a refusal changes nothing. let before = fs::read(&host.keys).unwrap(); let out = host.admin(&["add-key", "bob", file.to_str().unwrap(), "--label", "mine"]); assert!(!out.status.success() && stderr(&out).contains("another owner"), "{}", stderr(&out)); assert_eq!(fs::read(&host.keys).unwrap(), before); } #[test] fn a_protected_repository_refuses_rewrites_and_deletions() { let host = Host::new("ssh-protect"); let dir = work("ssh-protect-work", "main"); git(&dir, &["branch", "feature"]); let push = |args: &[&str]| host.git(&dir, &[&["push", "ada@x:ada/tools.git"][..], args].concat()); assert!(push(&["main", "feature"]).status.success()); assert_eq!(stdout(&host.ssh("ada", "protect tools")), "off\n"); let out = host.ssh("ada", "protect tools on"); assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(stdout(&host.ssh("ada", "protect tools")), "on\n"); let repo = host.repo("ada", "tools"); let tip = |branch: &str| git(&repo, &["rev-parse", branch]); // Moving forwards, and new branches and tags, still work. fs::write(dir.join("hello.txt"), "more\n").unwrap(); git(&dir, &["commit", "-qam", "Second"]); git(&dir, &["tag", "v1"]); let out = push(&["main", "v1", "main:refs/heads/new"]); assert!(out.status.success(), "{}", stderr(&out)); let second = tip("main"); // A rewrite of any branch, and any deletion, is refused and changes nothing. git(&dir, &["commit", "-q", "--amend", "-m", "Rewritten"]); let out = push(&["--force", "main"]); assert!(!out.status.success()); assert!(stderr(&out).contains("non-fast-forward"), "{}", stderr(&out)); assert_eq!(tip("main"), second); // Every branch, not just the default: `new` is at Second, and First would rewind it. let out = push(&["--force", "HEAD~1:new"]); assert!(!out.status.success(), "other branches are protected too"); assert_eq!(tip("new"), second); let out = push(&[":feature"]); assert!(!out.status.success(), "a branch was deleted"); assert!(stderr(&out).contains("deletion prohibited"), "{}", stderr(&out)); assert!(git(&repo, &["show-ref"]).contains("refs/heads/feature")); // Git applies both settings to branches only. A deleted tag is still in the push log, so // it can be put back. assert!(push(&[":refs/tags/v1"]).status.success(), "git now protects tags too: update the docs"); let log = fs::read_to_string(repo.join("gitv-push.log")).unwrap(); assert!(log.lines().last().unwrap().ends_with(&format!(" {second} - refs/tags/v1")), "{log}"); // Kept by gitv, not in the repository's own config, where a later tool might drop it. assert!(!fs::read_to_string(repo.join("config")).unwrap().contains("receive.")); // Recovery still records every change that did happen, and only those. assert_eq!(log.lines().count(), 6, "{log}"); // Only the owner's key, and only on or off. assert!(!host.ssh("bob", "protect tools off").status.success()); assert!(!host.ssh("ada", "protect tools maybe").status.success()); assert_eq!(stdout(&host.ssh("ada", "protect tools")), "on\n"); // Turned off, as root here, a rewrite goes through. assert!(host.admin(&["protect", "ada", "tools", "off"]).status.success()); let out = push(&["--force", "main"]); assert!(out.status.success(), "{}", stderr(&out)); assert_ne!(tip("main"), second); } #[test] fn hooks_in_a_repository_never_run() { use std::os::unix::fs::PermissionsExt; let host = Host::new("ssh-no-hooks"); let dir = work("ssh-no-hooks-work", "main"); assert!(host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main"]).status.success()); // A hook planted in the repository, as one copied in with a restored folder could be. let ran = host.dir.join("hook-ran"); let hooks = host.repo("ada", "tools").join("hooks"); fs::create_dir_all(&hooks).unwrap(); for hook in ["pre-receive", "post-receive", "update"] { let path = hooks.join(hook); fs::write(&path, format!("#!/bin/sh\ntouch '{}'\n", ran.display())).unwrap(); fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); } fs::write(dir.join("hello.txt"), "again\n").unwrap(); git(&dir, &["commit", "-qam", "Second"]); let out = host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main"]); assert!(out.status.success(), "{}", stderr(&out)); assert!(!ran.exists(), "a hook ran"); }