GITv

Protect a repository's branches from force-pushes and deletion

Browse files

`protect <name> on|off`, over SSH or as root, makes pushes refuse to rewrite or delete any branch, while new branches and ordinary pushes go through. It is a gitv-protected marker in the repository, like visibility, so backups carry it and only gitv changes it; pushes then run with receive.denyNonFastForwards and receive.denyDeletes alongside the recovery settings. Git applies both to branches only, so tags stay movable; the push log records it when they move. The signed-in header shows a Protected badge. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 23:45
Commit
2188fe3aea4b
Parent
1be53be

10 files changed +131−10

+1−1
@@ -76,7 +76,7 @@ Three crates. `gitv` depends only on `gitv-core` and a few small crates, so buil
- **Pushes.**
- Pushing to a missing name creates the repository. It is built in a private staging folder and published by rename.
- A push holds the repository's `flock` shared. The backup takes it exclusive.
- A push runs with `RECOVERY_CONFIG` (reflogs on every ref, unreachable objects kept 30 days), and appends ref changes to `gitv-push.log`.
- A push runs with `RECOVERY_CONFIG` (reflogs on every ref, unreachable objects kept 30 days), and appends ref changes to `gitv-push.log`. A repository with a `gitv-protected` marker (`gitv protect`) also gets `PROTECTED_CONFIG` (no non-fast-forward or deleting branch updates; git applies neither to tags).
- **Deletion** moves a repository to `<owner>/.trash/<name>.<unix time>`. `gitv purge`, run daily by a timer, removes entries older than 30 days. After that, `gitv-restore <snapshot> DIR OWNER/NAME` copies one repository out of a backup, and `gitv import` publishes it through the same staging and no-replace rename as `create` (`Contents::CopyOf`).
- **Logging.** SSH users only ever see generic errors. Details go to syslog, or to `$GITV_LOG` when it is set.
@@ -16,4 +16,4 @@ Deferred until a second person pushes to the server: individual accounts and rep
- [x] **Description, default branch and index filter.** Over SSH (and as root): `description <name> <text>` writes git's `description` file, and `default-branch <name> <branch>` points `HEAD` at an existing branch. The index shows descriptions and can be filtered by name with a plain GET form (`?q=`). The repository header shows its visibility to the signed-in operator.
- [x] **Tagged source archives.** The tags page links a `.tar.gz` of each tag, made by `git archive` and served through the download pool, under the repository's access rules. Tag annotations remain the release notes. Verify with a tagged GITv release that the archive matches `git archive` run locally.
- [x] **Single-repository restore from backup.** Document restoring one repository from a retained snapshot after its trash entry was purged, and test it in `tests/backup.rs`: branches, tags, default branch and visibility come back, it can be restored under a new name, and a repository that has since taken the name is never overwritten.
- [ ] **Optional: protect a repository from history rewrites.** `protect <name> on|off` sets `receive.denyNonFastForwards` and `receive.denyDeletes` for that repository. Verify that force-pushes and branch deletion are refused while ordinary pushes still work, and that the operator's push log and reflogs are unaffected.
- [x] **Optional: protect a repository from history rewrites.** `protect <name> on|off` sets `receive.denyNonFastForwards` and `receive.denyDeletes` for that repository's pushes (git applies both to branches only). Verify that force-pushes and branch deletion are refused while ordinary pushes still work, and that the operator's push log and reflogs are unaffected.
+3−1
@@ -2,7 +2,7 @@
Git hosting with SSH pushes, public and private repository browsing, and read-only HTTPS cloning for public repositories.
- `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `description`, `default-branch`, `delete`, `add-key`, `keys`, `remove-key`, `trash`, `restore`, `purge`, `import`)
- `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `protect`, `description`, `default-branch`, `delete`, `add-key`, `keys`, `remove-key`, `trash`, `restore`, `purge`, `import`)
- `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, compare, tags, archive), with Markdown rendering and syntax highlighting (`crates/gitv-web/src/render.rs`)
**Linking to code.** A file's History lists the commits that changed it, and a folder's History does the same for everything inside. Permalink opens the file at the commit you're looking at, so the link keeps showing the same content after the branch moves. Click a line number to link that line (`#L12`). To link a range, add `lines=` to the address, for example `…&lines=12-20#L12`; the server marks those lines, and Permalink keeps the range.
@@ -33,6 +33,8 @@ gitv description um9i my-project "A small toolbox"
gitv default-branch um9i my-project release
```
**Protecting history.** `ssh git@git.um9i.dev protect my-project on` (or `gitv protect um9i my-project on`) makes pushes refuse to force-update or delete any branch; new branches and ordinary pushes still work, and `off` lifts it. Git applies this to branches only: tags can still be moved or deleted, and the push log records it when they are. It's kept as a `gitv-protected` file in the repository, like visibility, so backups carry it, and the repository header shows it when you're signed in.
The description lives in git's own `description` file in the repository. Signed in, the repository header also shows whether it's public, and for a public repository both its HTTPS and SSH addresses.
**Limits.** The web server runs at most 16 page renders, 6 raw or archive downloads and 4 HTTPS clones at once. Some render and download slots are kept for signed-in sessions, so anonymous visitors can't crowd out the owner. Each anonymous client (an IPv4 address or IPv6 /64, as Caddy reports it) may hold at most 4 renders, 2 downloads and 2 clones at a time. Past these limits a request gets 503 at once rather than queueing.
@@ -106,12 +106,30 @@ impl RepoDir {
}
pub fn is_public(&self) -> bool {
matches!(try_kind_at(&self.fd, OsStr::new("gitv-public")), Ok(Some(SFlag::S_IFREG)))
self.has_marker("gitv-public")
}
pub fn set_public(&self, public: bool) -> nix::Result<()> {
let marker = "gitv-public";
if public {
self.set_marker("gitv-public", public)
}
/// Whether pushes may only move branches forwards and never delete them (`gitv protect`).
pub fn is_protected(&self) -> bool {
self.has_marker("gitv-protected")
}
pub fn set_protected(&self, protected: bool) -> nix::Result<()> {
self.set_marker("gitv-protected", protected)
}
/// A setting kept as an empty file in the repository directory: present (and a regular
/// file) means on. Backups and restores carry it with the repository.
fn has_marker(&self, marker: &str) -> bool {
matches!(try_kind_at(&self.fd, OsStr::new(marker)), Ok(Some(SFlag::S_IFREG)))
}
fn set_marker(&self, marker: &str, on: bool) -> nix::Result<()> {
if on {
match openat(
&self.fd,
marker,
@@ -119,7 +137,7 @@ impl RepoDir {
Mode::S_IRUSR,
) {
Ok(_) => Ok(()),
Err(nix::errno::Errno::EEXIST) if self.is_public() => Ok(()),
Err(nix::errno::Errno::EEXIST) if self.has_marker(marker) => Ok(()),
Err(error) => Err(error),
}
} else {
@@ -25,6 +25,8 @@ pub(crate) struct Masthead<'a> {
pub home: String,
/// "Public" or "Private", shown only when signed in.
pub visibility: Option<&'static str>,
/// Whether pushes are held to fast-forwards, shown only when signed in.
pub protected: bool,
pub description: Option<String>,
/// Each way to clone it: protocol and address.
pub addresses: Vec<(&'static str, String)>,
@@ -159,6 +159,7 @@ impl Repo {
name: &self.name,
home: self.url("tree", &[]),
visibility: self.signed_in.then_some(if public { "Public" } else { "Private" }),
protected: self.signed_in && self.reader.dir.is_protected(),
description: self.reader.dir.description(),
addresses,
tabs: vec![
@@ -1,4 +1,4 @@
<div class="repohead"><div class="repoid"><div class="repoline"><h1 class="reponame"><a class="own" href="/">{{ owner }}</a><span class="sep">/</span><a href="{{ home }}">{{ name }}</a></h1>{% if let Some(visibility) = visibility %}<span class="vis">{{ visibility }}</span>{% endif %}</div>
<div class="repohead"><div class="repoid"><div class="repoline"><h1 class="reponame"><a class="own" href="/">{{ owner }}</a><span class="sep">/</span><a href="{{ home }}">{{ name }}</a></h1>{% if let Some(visibility) = visibility %}<span class="vis">{{ visibility }}</span>{% endif %}{% if protected %}<span class="vis" title="Pushes can't force-update or delete branches">Protected</span>{% endif %}</div>
{% if let Some(description) = description %}<p class="repodesc">{{ description }}</p>{% endif %}</div>
<div class="clones">{% for (protocol, address) in addresses %}<label class="clone"><span>{{ protocol }}</span><input readonly aria-label="{{ protocol }} clone address" value="{{ address }}"></label>{% endfor %}</div></div>
<nav class="tabs" aria-label="Repository">{% for tab in tabs %}<a href="{{ tab.href }}"{% if tab.current %} aria-current="page"{% endif %}>{{ tab.icon|safe }}{{ tab.label }}{% if let Some(n) = tab.count %}<span class="n">{{ n }}</span>{% endif %}</a>{% endfor %}</nav>
@@ -880,6 +880,10 @@ fn public_web_clone_and_visibility_changes() {
assert!(operator.contains("value=\"https://git.example.test/ada/sharing\""), "{operator}");
assert!(operator.contains("value=\"git@git.example.test:ada/sharing.git\""), "{operator}");
assert!(operator.contains("<span class=\"vis\">Public</span>"), "{operator}");
assert!(!operator.contains(">Protected<"), "{operator}");
assert!(host.ssh("ada", "protect sharing on").status.success());
assert!(server.get("/ada/sharing/tree").text().contains(">Protected</span>"));
assert!(!server.get_signed_out("/ada/sharing/tree").text().contains("Protected"), "only the operator sees it");
assert_eq!(server.get_signed_out("/ada/sharing/raw?path=hello").text(), "public content");
// Both protocol versions clone; version 2 is what the server speaks when asked.
for version in ["0", "2"] {
@@ -29,6 +29,7 @@ fn help() -> String {
list list your repositories
create <name> create an empty repository
visibility <name> public|private set web access
protect <name> [on|off] show or set whether pushes may rewrite or delete branches
description <name> [<text>] show or set the one-line description (\"\" removes it)
default-branch <name> [<branch>] show or set the branch the web shows and clones check out
delete <name> --yes move a repository to the trash (the operator can restore it for 30 days)
@@ -54,6 +55,15 @@ enum Action {
},
/// Set repository web visibility to public or private (root)
Visibility { owner: String, name: String, visibility: String },
/// Show or set whether pushes may force-update or delete branches (root)
Protect {
#[arg(value_parser = name)]
owner: String,
#[arg(value_parser = name)]
name: String,
/// on: branches only move forwards and are never deleted; off: anything
value: Option<String>,
},
/// Show or set a repository's one-line description; "" removes it (root)
Description {
#[arg(value_parser = name)]
@@ -769,6 +779,21 @@ fn visibility(owner: &str, name: &str, visibility: &str) -> Result<(), String> {
.map_err(|e| format!("couldn't set visibility: {e}"))
}
/// Print whether a repository is protected, or turn protection `on` or `off`.
fn protect(owner: &str, name: &str, value: Option<&str>) -> Result<(), String> {
let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?;
let on = match value {
None => {
println!("{}", if repo.is_protected() { "on" } else { "off" });
return Ok(());
}
Some("on") => true,
Some("off") => false,
Some(_) => return Err("choose on or off".into()),
};
repo.set_protected(on).map_err(|e| format!("couldn't set protection: {e}"))
}
/// Print a repository's description, or set it to `text`; an empty text removes it.
fn description(owner: &str, name: &str, text: Option<&str>) -> Result<(), String> {
let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?;
@@ -817,6 +842,8 @@ fn serve(owner: &str, command: &str) -> Result<u8, String> {
[program @ ("git-upload-pack" | "git-receive-pack"), path] => return serve_git(owner, program, path),
["visibility", name, value] => visibility(owner, name, value)?,
// Unquoted words are one description: `description tools A small toolbox`.
["protect", name] => protect(owner, name, None)?,
["protect", name, value] => protect(owner, name, Some(value))?,
["description", name] => description(owner, name, None)?,
["description", name, text @ ..] => description(owner, name, Some(&text.join(" ")))?,
["default-branch", name] => default_branch(owner, name, None)?,
@@ -937,10 +964,15 @@ fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> {
// objects nothing refers to any more stay as long as those entries do. Given through
// the environment, so it covers every repository, old or new, and the gc a push
// triggers inherits it.
command.envs(RECOVERY_CONFIG.iter().enumerate().flat_map(|(i, (key, value))| {
// A protected repository also refuses force-pushes and deletions of every branch (git
// applies these to refs/heads only; tags stay movable, and the push log records them).
// Given here, not in the repository's own config, so only `gitv protect` changes it.
let protection: &[(&str, &str)] = if repo.is_protected() { &PROTECTED_CONFIG } else { &[] };
let settings: Vec<_> = RECOVERY_CONFIG.iter().chain(protection).collect();
command.envs(settings.iter().enumerate().flat_map(|(i, (key, value))| {
[(format!("GIT_CONFIG_KEY_{i}"), *key), (format!("GIT_CONFIG_VALUE_{i}"), *value)]
}));
command.env("GIT_CONFIG_COUNT", RECOVERY_CONFIG.len().to_string());
command.env("GIT_CONFIG_COUNT", settings.len().to_string());
ref_snapshot(&repo)
.inspect_err(|e| log_operator(&format!("{owner}/{name}.git: no push log for this push: {e}")))
.ok()
@@ -970,6 +1002,10 @@ const RECOVERY_CONFIG: [(&str, &str); 4] = [
("gc.autoDetach", "false"),
];
/// What a protected repository's pushes also run with: no branch may move except forwards,
/// and none may be deleted.
const PROTECTED_CONFIG: [(&str, &str); 2] = [("receive.denyNonFastForwards", "true"), ("receive.denyDeletes", "true")];
/// Where each repository records its pushes' ref changes. Git drops a branch's reflog when the
/// branch is deleted; this keeps the commit it pointed at findable.
const PUSH_LOG: &str = "gitv-push.log";
@@ -1088,6 +1124,7 @@ fn run() -> Result<u8, String> {
Action::Purge { older_than_days } => purge(older_than_days)?,
Action::Import { owner, name, source } => import(&owner, &name, &source)?,
Action::Visibility { owner, name, visibility: value } => visibility(&owner, &name, &value)?,
Action::Protect { owner, name, value } => protect(&owner, &name, value.as_deref())?,
Action::Description { owner, name, text } => description(&owner, &name, text.as_deref())?,
Action::DefaultBranch { owner, name, branch } => default_branch(&owner, &name, branch.as_deref())?,
Action::AddKey { owner, public_key, label } => add_key(&owner, &public_key, label.as_deref())?,
@@ -858,3 +858,60 @@ fn adding_a_key_again_with_a_label_renames_it() {
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);
}