Rename a key by adding it again with a label
Browse filesLabelling an existing key meant removing it and adding it back, leaving a moment when it didn't work. `gitv add-key <owner> <key> --label <text>` for a key that owner already has now renames it in place, keeping everything before the key on its line, options included. Without a label it is still refused, and a key registered to another owner is never moved. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 23:43
- Commit
- 1be53be4fb6a
- Parent
- 96810b9
3 files changed +89−8
+2−1
| @@ -57,10 +57,11 @@ History overwritten by a push can be recovered for the same 30 days. Every push | ||
| 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 add-key um9i laptop.pub --label "work" # a key um9i already has: renames it in place | ||
| 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. | ||
| Adding a key the owner already has, with a label, only renames it: its line keeps its options, and the key never stops working. A key registered to another owner is refused. `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. | ||
| @@ -549,14 +549,39 @@ fn add_key(owner: &str, file: &Path, label: Option<&str>) -> Result<(), String> | ||
| // 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(); | ||
| let mut relabelled = false; | ||
| 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 registered: Vec<KeyLine> = old.lines().filter_map(parse_key_line).filter(|k| k.blob == blob).collect(); | ||
| if registered.is_empty() { | ||
| let separator = if old.is_empty() || old.ends_with('\n') { "" } else { "\n" }; | ||
| let command = config::command(); | ||
| return Ok(format!( | ||
| "{old}{separator}restrict,command=\"{command} serve {owner}\" ssh-ed25519 {token}{comment}\n" | ||
| )); | ||
| } | ||
| // Registering a key again with a label renames it, but only for the owner it already | ||
| // serves: a key never moves to another owner this way. | ||
| let Some(label) = label else { return Err("key already registered".into()) }; | ||
| if registered.iter().any(|k| k.owner() != Some(owner)) { | ||
| return Err("key already registered for another owner".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")) | ||
| }) | ||
| relabelled = true; | ||
| Ok(old | ||
| .split_inclusive('\n') | ||
| .map(|row| { | ||
| let line = row.trim_end_matches(['\n', '\r']); | ||
| match parse_key_line(line) { | ||
| // Everything up to the key stays as it was, options included. | ||
| Some(k) if k.blob == blob => format!("{} {label}{}", &line[..k.key_end], &row[line.len()..]), | ||
| _ => row.to_string(), | ||
| } | ||
| }) | ||
| .collect()) | ||
| })?; | ||
| if relabelled { | ||
| println!("relabelled {} as {}", fingerprint(&blob), label.unwrap_or_default()); | ||
| } | ||
| Ok(()) | ||
| } | ||
| /// Read the keys file, let `change` produce its new contents, and publish them, all under the | ||
| @@ -660,6 +685,8 @@ struct KeyLine<'a> { | ||
| options: &'a str, | ||
| blob: Vec<u8>, | ||
| comment: &'a str, | ||
| /// Where the key field ends in the line given to [`parse_key_line`]. | ||
| key_end: usize, | ||
| } | ||
| impl<'a> KeyLine<'a> { | ||
| @@ -690,6 +717,7 @@ fn next_field(text: &str) -> Option<(&str, &str)> { | ||
| /// so a key mentioned in a comment or a commented-out line doesn't count. | ||
| 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 original = line; | ||
| let line = line.trim_start(); | ||
| if line.is_empty() || line.starts_with('#') { | ||
| return None; | ||
| @@ -708,7 +736,9 @@ fn parse_key_line(line: &str) -> Option<KeyLine<'_>> { | ||
| } | ||
| let (key, comment) = next_field(rest)?; | ||
| let blob = base64::engine::general_purpose::STANDARD.decode(key).ok()?; | ||
| Some(KeyLine { options: options.trim_end(), blob, comment }) | ||
| // Every field is a slice of the line handed in, so its position is its address's offset. | ||
| let key_end = key.as_ptr() as usize - original.as_ptr() as usize + key.len(); | ||
| Some(KeyLine { options: options.trim_end(), blob, comment, key_end }) | ||
| } | ||
| /// What follows the options field: its end is the first whitespace outside double quotes. | ||
| @@ -808,3 +808,53 @@ fn the_default_branch_can_be_chosen_among_existing_branches() { | ||
| 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); | ||
| } | ||