GITv

List SSH keys and revoke one by fingerprint

Browse files

Revoking a lost device's key used to mean editing authorized_keys by hand. `gitv keys [owner]` now lists each key's owner, SHA-256 fingerprint (as ssh-keygen -l prints it) and label, and `gitv remove-key <fingerprint>` removes exactly that key. `add-key --label` names the device; the key file's own comment is still dropped, since it is often an email address. Adding and removing share edit_keys: the keys lock, an atomic publish and restorecon, so concurrent changes can't undo each other. Removal keeps every other line byte for byte, including hand-written ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 23:15
Commit
a76c35082bbc
Parent
94562a0

6 files changed +274−26

+1−1
@@ -72,7 +72,7 @@ Three crates. `gitv` depends only on `gitv-core` and a few small crates, so buil
### `gitv` (SSH and admin)
- **Access.** `gitv add-key` writes `restrict,command="<gitv> serve <owner>"` lines to `/etc/gitv/authorized_keys`. A key reaches only its owner's repositories, and `serve` parses `SSH_ORIGINAL_COMMAND`.
- **Access.** `gitv add-key` writes `restrict,command="<gitv> serve <owner>"` lines to `/etc/gitv/authorized_keys`. A key reaches only its owner's repositories, and `serve` parses `SSH_ORIGINAL_COMMAND`. `gitv keys` and `remove-key` list and revoke keys by SHA-256 fingerprint; every change to the keys file goes through `edit_keys` (the `keys.lock` flock, then `publish_file`, then `restorecon`).
- **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.
@@ -445,6 +445,7 @@ dependencies = [
"clap",
"gitv-core",
"nix",
"sha2",
"shlex",
]
+12−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`, `delete`, `add-key`, `trash`, `restore`, `purge`)
- `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `delete`, `add-key`, `keys`, `remove-key`, `trash`, `restore`, `purge`)
- `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, tags), with Markdown rendering and syntax highlighting (`crates/gitv-web/src/render.rs`)
**Who can read what.** Over SSH each key reaches only its owner's repositories. The web browser has one account, and whoever signs in to it can read every repository on the server. It binds to localhost only; put it behind an HTTPS reverse proxy.
@@ -33,6 +33,17 @@ gitv purge # remove entries deleted 30+ days ag
History overwritten by a push can be recovered for the same 30 days. Every push records a reflog entry for each ref it changes, and keeps unreachable objects as long as those entries; for example, `git -C <repo> rev-parse main@{1}` finds where `main` pointed before a force-push. Git drops a branch's reflog when the branch is deleted, so each push also appends its ref changes to `gitv-push.log` in the repository (`<unix time> <old> <new> <ref>`, `-` for none). To bring back a deleted branch, find its last commit there and run `git -C <repo> branch <name> <commit>`.
**SSH keys.** Each key in `/etc/gitv/authorized_keys` reaches only its owner's repositories. Give each device its own key and a label, so a lost one can be revoked alone:
```sh
gitv add-key um9i laptop.pub --label "laptop" # Ed25519 only; the key file's own comment isn't kept
gitv keys # owner, SHA-256 fingerprint (as ssh-keygen -l shows it), label
gitv keys um9i # one owner's keys
gitv remove-key SHA256:gNSIRW+2Iyiuvsdp/bgjy38bvWHw6wQm3tuoXrl3WjQ
```
`remove-key` rewrites the file atomically under the same lock as `add-key` and keeps every other line as it was, including hand-written ones (listed with `-` as the owner when they aren't a `gitv serve` command). sshd reads the file on each connection, so the key stops working at once, but a connection already open finishes what it is doing.
The browser follows the system's light or dark setting. Its stylesheet (`crates/gitv-web/assets/style.css`) and the Red Hat Display, Text and Mono fonts (`crates/gitv-web/assets/fonts`, SIL Open Font License) are built into the `gitv-web` binary, so the server needs no font packages.
## Web sign-in
@@ -11,4 +11,5 @@ gitv-core.workspace = true
base64.workspace = true
clap.workspace = true
nix.workspace = true
sha2.workspace = true
shlex.workspace = true
@@ -84,6 +84,20 @@ enum Action {
#[arg(value_parser = name)]
owner: String,
public_key: PathBuf,
/// A name for the device that holds the key, shown by `gitv keys`
#[arg(long, value_parser = label)]
label: Option<String>,
},
/// List registered keys with their owner, fingerprint and label (root)
Keys {
/// Only this owner's keys
#[arg(value_parser = name)]
owner: Option<String>,
},
/// Revoke a key by its fingerprint, as `gitv keys` lists it (root)
RemoveKey {
/// SHA256:<base64>, with or without the SHA256: prefix
fingerprint: String,
},
/// Handle one SSH request (forced command from authorized_keys)
Serve {
@@ -97,6 +111,16 @@ fn name(value: &str) -> Result<String, String> {
check_name(value).map(str::to_string)
}
/// A key's label becomes the comment field of its authorized_keys line, so it must stay on one
/// line and hold nothing a terminal would act on.
fn label(value: &str) -> Result<String, String> {
let value = value.trim();
if value.is_empty() || value.chars().count() > 64 || value.chars().any(char::is_control) {
return Err("a label is 1 to 64 characters, with no control characters".into());
}
Ok(value.to_string())
}
fn check_name(value: &str) -> Result<&str, String> {
if valid_name(value) { Ok(value) } else { Err(NAME_RULE.into()) }
}
@@ -416,7 +440,7 @@ fn purge(days: u64) -> Result<(), String> {
if failures == 0 { Ok(()) } else { Err(format!("{failures} trash entries couldn't be purged")) }
}
fn add_key(owner: &str, file: &Path) -> Result<(), String> {
fn add_key(owner: &str, file: &Path, label: Option<&str>) -> Result<(), String> {
let text = fs::read_to_string(file).map_err(|e| e.to_string())?;
let parts: Vec<&str> = text.split_whitespace().collect();
if parts.len() < 2 || parts[0] != "ssh-ed25519" {
@@ -434,28 +458,96 @@ fn add_key(owner: &str, file: &Path) -> Result<(), String> {
// Prepare everything the key needs first: publishing the key file is the last step, so a
// failure leaves no key installed and a retry starts clean.
owner_directory(owner)?;
// The key file's own comment is dropped (it is often an email address); only a label the
// operator chose is kept.
let comment = label.map(|l| format!(" {l}")).unwrap_or_default();
edit_keys(|old| {
if old.lines().any(|row| parse_key_line(row).is_some_and(|k| k.blob == blob)) {
return Err("key already registered".into());
}
let separator = if old.is_empty() || old.ends_with('\n') { "" } else { "\n" };
let command = config::command();
Ok(format!("{old}{separator}restrict,command=\"{command} serve {owner}\" ssh-ed25519 {token}{comment}\n"))
})
}
/// Read the keys file, let `change` produce its new contents, and publish them, all under the
/// keys lock, so two administrators changing keys at once can't undo each other's work.
fn edit_keys(change: impl FnOnce(&str) -> Result<String, String>) -> Result<(), String> {
let keys = keys_path();
let directory = keys.parent().ok_or("authorized_keys has no directory")?;
// Serialise writers, so two keys added at once can't overwrite each other.
let lock =
fs::File::options().create(true).append(true).open(directory.join("keys.lock")).map_err(|e| e.to_string())?;
let _lock = Flock::lock(lock, FlockArg::LockExclusive).map_err(|(_, e)| e.to_string())?;
let old = match fs::read_to_string(&keys) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e.to_string()),
};
if old.lines().any(|row| key_blob(row).as_deref() == Some(blob.as_slice())) {
return Err("key already registered".into());
}
let separator = if old.is_empty() || old.ends_with('\n') { "" } else { "\n" };
let line = format!("{separator}restrict,command=\"{} serve {owner}\" ssh-ed25519 {token}\n", config::command());
// Readable by sshd. The key counts as added only once the rename survives a crash.
gitv_core::publish_file(&keys, format!("{old}{line}").as_bytes(), 0o644, true, |_| Ok::<(), String>(()))
let old = read_keys(&keys)?;
let new = change(&old)?;
// Readable by sshd. The change counts only once the rename survives a crash.
gitv_core::publish_file(&keys, new.as_bytes(), 0o644, true, |_| Ok::<(), String>(()))
.map_err(|e| format!("couldn't write {}: {e}", keys.display()))?;
relabel(&keys, Path::new("/sys/fs/selinux"), Path::new("/usr/sbin/restorecon"))
}
/// The keys file's contents; a missing file holds no keys.
fn read_keys(keys: &Path) -> Result<String, String> {
match fs::read_to_string(keys) {
Ok(text) => Ok(text),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
Err(e) => Err(format!("couldn't read {}: {e}", keys.display())),
}
}
/// A key's fingerprint as `ssh-keygen -l` prints it: unpadded base64 of the blob's SHA-256.
fn fingerprint(blob: &[u8]) -> String {
use sha2::{Digest, Sha256};
format!("SHA256:{}", base64::engine::general_purpose::STANDARD_NO_PAD.encode(Sha256::digest(blob)))
}
/// Print every active key, one per line: owner, fingerprint, label. Lines not written by
/// `add-key` are listed too, with `-` for an owner that isn't a GITv forced command.
fn list_keys(only: Option<&str>) -> Result<(), String> {
let text = read_keys(&keys_path())?;
let rows: Vec<(&str, String, &str)> = text
.lines()
.filter_map(parse_key_line)
.map(|k| (k.owner().unwrap_or("-"), fingerprint(&k.blob), k.comment))
.filter(|(owner, _, _)| only.is_none_or(|o| o == *owner))
.collect();
if rows.is_empty() {
eprintln!("gitv: no keys registered");
}
let width = rows.iter().map(|(owner, _, _)| owner.len()).max().unwrap_or(0);
for (owner, fingerprint, label) in rows {
println!("{owner:<width$} {fingerprint} {label}");
}
Ok(())
}
/// Remove the key with this fingerprint. Every other line, including comments and lines
/// `add-key` didn't write, is kept byte for byte.
fn remove_key(wanted: &str) -> Result<(), String> {
let wanted = format!("SHA256:{}", wanted.strip_prefix("SHA256:").unwrap_or(wanted));
let mut removed = Vec::new();
edit_keys(|old| {
let mut kept = String::with_capacity(old.len());
for row in old.split_inclusive('\n') {
match parse_key_line(row.trim_end_matches(['\n', '\r'])) {
Some(k) if fingerprint(&k.blob) == wanted => {
removed.push(format!("{} {}", k.owner().unwrap_or("-"), k.comment).trim_end().to_string())
}
_ => kept.push_str(row),
}
}
if removed.is_empty() {
return Err(format!("no key has the fingerprint {wanted}; run: gitv keys"));
}
Ok(kept)
})?;
for key in removed {
println!("removed {wanted} ({key}); connections already open stay open until they end");
}
Ok(())
}
/// Give a file the SELinux label the system's policy names for its path. A file published by
/// rename carries the label its directory gives new files, not the one the policy names (sshd
/// reads authorized keys labelled `ssh_home_t`), so without this every added key would leave
@@ -468,33 +560,67 @@ fn relabel(path: &Path, selinuxfs: &Path, restorecon: &Path) -> Result<(), Strin
match status {
Ok(status) if status.success() => Ok(()),
outcome => Err(format!(
"added the key, but couldn't give {} its SELinux label ({}); run: restorecon {0}",
"updated the keys, but couldn't give {} its SELinux label ({}); run: restorecon {0}",
path.display(),
outcome.map_or_else(|e| e.to_string(), |s| s.to_string())
)),
}
}
/// The decoded Ed25519 key in an authorized_keys line, wherever it sits: after options, and
/// before any comment.
/// An active authorized_keys line, taken apart.
struct KeyLine<'a> {
options: &'a str,
blob: Vec<u8>,
comment: &'a str,
}
impl<'a> KeyLine<'a> {
/// The owner a GITv forced command (`command="<gitv> serve <owner>"`) serves.
fn owner(&self) -> Option<&'a str> {
let start = self.options.find("command=\"")? + "command=\"".len();
let options: &'a str = self.options;
let value = &options[start..];
let value = &value[..value.find('"')?];
match value.split_whitespace().collect::<Vec<_>>().as_slice() {
[_, "serve", owner] if valid_name(owner) => Some(owner),
_ => None,
}
}
}
/// Split off the field at the start of `text` (after any spaces or tabs) from what follows it.
fn next_field(text: &str) -> Option<(&str, &str)> {
let text = text.trim_start_matches([' ', '\t']);
let end = text.find([' ', '\t']).unwrap_or(text.len());
(end > 0).then(|| (&text[..end], text[end..].trim_matches([' ', '\t'])))
}
/// The options, decoded key and comment of an authorized_keys line, wherever the key sits.
///
/// A line is `[options] type key [comment]`. Blank and `#` lines are skipped, options are
/// skipped as one field (they can hold quoted spaces), and only the key field itself is read,
/// so a key mentioned in a comment or a commented-out line doesn't count.
fn key_blob(line: &str) -> Option<Vec<u8>> {
fn parse_key_line(line: &str) -> Option<KeyLine<'_>> {
const TYPES: [&str; 4] = ["ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "sk-ssh-ed25519@openssh.com"];
let line = line.trim_start();
if line.is_empty() || line.starts_with('#') {
return None;
}
// Fields are separated by spaces or tabs. The first is the key type, or else the options.
let first = line.split([' ', '\t']).next()?;
let rest = if TYPES.contains(&first) { line } else { skip_options(line)? };
let mut fields = rest.split([' ', '\t']).filter(|f| !f.is_empty());
if !TYPES.contains(&fields.next()?) {
let (first, _) = next_field(line)?;
let (options, rest) = if TYPES.contains(&first) {
("", line)
} else {
let rest = skip_options(line)?;
(&line[..line.len() - rest.len()], rest)
};
let (kind, rest) = next_field(rest)?;
if !TYPES.contains(&kind) {
return None;
}
base64::engine::general_purpose::STANDARD.decode(fields.next()?).ok()
let (key, comment) = next_field(rest)?;
let blob = base64::engine::general_purpose::STANDARD.decode(key).ok()?;
Some(KeyLine { options: options.trim_end(), blob, comment })
}
/// What follows the options field: its end is the first whitespace outside double quotes.
@@ -800,7 +926,9 @@ fn run() -> Result<u8, String> {
Action::Restore { owner, entry, as_name } => restore(&owner, &entry, as_name.as_deref())?,
Action::Purge { older_than_days } => purge(older_than_days)?,
Action::Visibility { owner, name, visibility: value } => visibility(&owner, &name, &value)?,
Action::AddKey { owner, public_key } => add_key(&owner, &public_key)?,
Action::AddKey { owner, public_key, label } => add_key(&owner, &public_key, label.as_deref())?,
Action::Keys { owner } => list_keys(owner.as_deref())?,
Action::RemoveKey { fingerprint } => remove_key(&fingerprint)?,
Action::Serve { .. } => unreachable!(),
}
Ok(0)
@@ -638,3 +638,110 @@ fn ssh_create_keeps_server_details_for_the_operator() {
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<String> {
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");
}