Skip to content

Commit 449a5b9

Browse files
fix(backend-ssh): key remote units by agent identity
The systemd instance, env-file path and returned `backend_agent_id` were all derived from the agent's display name. A name is not unique: two agents called the same thing on one SSH account collapsed onto one unit and one env file, so the second deploy overwrote the first agent's minted nsec and starting either record drove whichever identity was written last. Key them on the agent's pubkey instead — the record's own primary key, and the only stable identifier the payload can carry. The slug keeps the name as its readable stem and appends a 12-hex fragment of the key, so `systemctl --user status` still reads as the agent a human recognizes. The payload field is required, not optional: falling back to the name on an absent `pubkey` would reintroduce the collision silently, so deploy refuses a payload without a 64-character hex key. Signed-off-by: Troy Hoffman <[email protected]>
1 parent 2a495cc commit 449a5b9

4 files changed

Lines changed: 116 additions & 28 deletions

File tree

‎crates/buzz-backend-ssh/src/deploy.rs‎

Lines changed: 97 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ const RESERVED_ENV_KEYS: &[&str] = &[
4848
/// `Debug` would put provider credentials one `{:?}` away from a log line.
4949
pub struct Agent {
5050
pub name: String,
51+
/// The agent's minted Nostr pubkey — the desktop record's own primary key,
52+
/// and the only stable identifier in the payload. See [`Agent::slug`].
53+
pub pubkey: String,
5154
pub relay_url: String,
5255
pub private_key_nsec: Secret,
5356
pub auth_tag: Option<String>,
@@ -120,8 +123,31 @@ impl Agent {
120123
reached the host (see instanceInputForDefinition provider branch)",
121124
)?;
122125

126+
// The one stable identifier in the payload, and what every host-side
127+
// name is keyed on. Refused rather than defaulted for the same reason
128+
// the minted key is: without it two agents that merely share a display
129+
// name would share one unit, one env file and one `backend_agent_id`,
130+
// and the second deploy would overwrite the first agent's identity.
131+
//
132+
// Validated to the shape the desktop always mints (`to_hex()` of a
133+
// Nostr public key) because the fragment taken from it becomes a
134+
// filename and a systemd instance name. Anything else is a payload bug,
135+
// and sanitizing it would trade a loud failure for a silent collision.
136+
let pubkey = string("pubkey").ok_or(
137+
"deploy payload carries no 'pubkey': the remote unit would be keyed on the agent's \
138+
display name, which two agents can share",
139+
)?;
140+
if pubkey.len() != 64 || !pubkey.chars().all(|c| c.is_ascii_hexdigit()) {
141+
return Err(format!(
142+
"'pubkey' is not a 64-character hex Nostr public key: {} characters",
143+
pubkey.len()
144+
));
145+
}
146+
let pubkey = pubkey.to_lowercase();
147+
123148
Ok(Self {
124149
name: string("name").ok_or("'name' is required")?,
150+
pubkey,
125151
relay_url: string("relay_url").ok_or("'relay_url' is required")?,
126152
private_key_nsec,
127153
auth_tag: string("auth_tag"),
@@ -166,10 +192,17 @@ impl Agent {
166192
/// `record.backend_agent_id`.
167193
///
168194
/// It becomes both a filename and a unit instance name, so it follows the
169-
/// desktop's own `util::slugify` rule. The hash suffix is not decoration:
170-
/// the payload carries no stable agent identifier, and without it two
171-
/// agents whose names differ only in punctuation would share one unit and
172-
/// one env file.
195+
/// desktop's own `util::slugify` rule. The name is the readable half; the
196+
/// **pubkey fragment is the identity**, and it is what makes the name safe
197+
/// to read: two agents may legitimately be called "Research Bot" on one SSH
198+
/// account, and keying on the name alone gave them one unit, one env file
199+
/// and one `backend_agent_id` — so the second deploy silently overwrote the
200+
/// first agent's minted nsec, and starting either record then drove
201+
/// whichever identity was written last.
202+
///
203+
/// [`PUBKEY_FRAGMENT`] characters of a 256-bit key are far more than a
204+
/// per-host unit namespace needs to stay collision-free, and short enough
205+
/// to leave the name legible in `systemctl --user status`.
173206
pub fn slug(&self) -> String {
174207
let sanitized: String = self
175208
.name
@@ -182,23 +215,17 @@ impl Agent {
182215
let stem = &stem[..stem.len().min(32)];
183216
let stem = stem.trim_end_matches('-');
184217
let stem = if stem.is_empty() { "agent" } else { stem };
185-
format!("{stem}-{}", short_hash(&self.name))
218+
// Hex and lowercased by `from_request`, so this is already unit-safe.
219+
format!("{stem}-{}", &self.pubkey[..PUBKEY_FRAGMENT])
186220
}
187221

188222
pub fn agent_id(&self) -> String {
189223
format!("buzz-acp@{}", self.slug())
190224
}
191225
}
192226

193-
/// FNV-1a, truncated. Only ever used to keep distinct names on distinct units.
194-
fn short_hash(value: &str) -> String {
195-
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
196-
for byte in value.as_bytes() {
197-
hash ^= u64::from(*byte);
198-
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
199-
}
200-
format!("{:08x}", hash as u32)
201-
}
227+
/// How much of the agent's pubkey identifies its unit. See [`Agent::slug`].
228+
const PUBKEY_FRAGMENT: usize = 12;
202229

203230
pub fn env_map(value: Option<&serde_json::Value>) -> BTreeMap<String, String> {
204231
value
@@ -663,13 +690,18 @@ mod tests {
663690
use super::*;
664691

665692
const NSEC: &str = "nsec1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";
693+
/// A 64-hex Nostr pubkey, in the shape `record.pubkey` always carries.
694+
const PUBKEY: &str = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
695+
/// The fragment of [`PUBKEY`] every host-side name is keyed on.
696+
const PUBKEY_SLUG: &str = "3bf0c63fcb93";
666697

667698
fn request() -> serde_json::Value {
668699
serde_json::json!({
669700
"op": "deploy",
670701
"provider_config": { "ssh_host": "vps", "ssh_user": "ubuntu" },
671702
"agent": {
672703
"name": "Research Bot",
704+
"pubkey": PUBKEY,
673705
"relay_url": "wss://relay.example/ws",
674706
"private_key_nsec": NSEC,
675707
"auth_tag": "tag-abc",
@@ -1018,24 +1050,65 @@ mod tests {
10181050
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
10191051
"{slug}"
10201052
);
1021-
assert!(slug.starts_with("research-bot-"));
1022-
// Redeploy is the start path: the same name must yield the same unit
1053+
assert_eq!(slug, format!("research-bot-{PUBKEY_SLUG}"));
1054+
// Redeploy is the start path: the same agent must yield the same unit
10231055
// and the same agent_id, or start would provision a duplicate.
10241056
assert_eq!(slug, Agent::from_request(&request()).unwrap().slug());
10251057
assert_eq!(agent.agent_id(), format!("buzz-acp@{slug}"));
10261058
}
10271059

1060+
/// The collision this key exists to prevent: one SSH account, two agents a
1061+
/// user called the same thing. Keyed on the name they shared a unit, an env
1062+
/// file and an `agent_id`, so the second deploy overwrote the first's nsec.
10281063
#[test]
1029-
fn names_that_sanitize_alike_still_get_distinct_units() {
1030-
let named = |name: &str| {
1064+
fn two_agents_with_one_name_get_distinct_units() {
1065+
let deployed = |pubkey: &str| {
10311066
let mut request = request();
1032-
request["agent"]["name"] = serde_json::json!(name);
1033-
Agent::from_request(&request).unwrap().slug()
1067+
request["agent"]["pubkey"] = serde_json::json!(pubkey);
1068+
let agent = Agent::from_request(&request).unwrap();
1069+
(agent.slug(), agent.agent_id())
10341070
};
1035-
assert_ne!(named("Bot!"), named("Bot?"));
1036-
// A name with nothing usable still produces a legal instance name.
1037-
let empty = named("!!!");
1038-
assert!(empty.starts_with("agent-"), "{empty}");
1071+
let other = "e88a691e98d9987c964521dff60025f60700378a4879180dcbbb4a5027850411";
1072+
let (first_slug, first_id) = deployed(PUBKEY);
1073+
let (second_slug, second_id) = deployed(other);
1074+
assert_ne!(first_slug, second_slug);
1075+
assert_ne!(first_id, second_id);
1076+
// Both still name the agent a human recognizes.
1077+
assert!(first_slug.starts_with("research-bot-"), "{first_slug}");
1078+
assert!(second_slug.starts_with("research-bot-"), "{second_slug}");
1079+
}
1080+
1081+
#[test]
1082+
fn a_name_with_nothing_usable_still_produces_a_legal_instance_name() {
1083+
let mut request = request();
1084+
request["agent"]["name"] = serde_json::json!("!!!");
1085+
let slug = Agent::from_request(&request).unwrap().slug();
1086+
assert_eq!(slug, format!("agent-{PUBKEY_SLUG}"));
1087+
}
1088+
1089+
/// The identity is refused rather than defaulted: a payload without it
1090+
/// would silently fall back to name-keyed units, which is the collision.
1091+
#[test]
1092+
fn deploy_refuses_a_payload_with_no_usable_agent_identity() {
1093+
let mut request = request();
1094+
request["agent"].as_object_mut().unwrap().remove("pubkey");
1095+
assert!(rejection(&request).contains("no 'pubkey'"));
1096+
1097+
for bad in ["", "abc123", &"z".repeat(64)] {
1098+
request["agent"]["pubkey"] = serde_json::json!(bad);
1099+
let error = rejection(&request);
1100+
assert!(
1101+
error.contains("pubkey"),
1102+
"accepted {bad:?} with error {error}"
1103+
);
1104+
}
1105+
1106+
// Case is normalized, so the same key never yields two units.
1107+
request["agent"]["pubkey"] = serde_json::json!(PUBKEY.to_uppercase());
1108+
assert_eq!(
1109+
Agent::from_request(&request).unwrap().slug(),
1110+
Agent::from_request(&self::request()).unwrap().slug()
1111+
);
10391112
}
10401113

10411114
#[test]

‎desktop/src-tauri/src/commands/agents_deploy.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,13 @@ pub(super) fn deploy_payload_json(
165165
) -> serde_json::Value {
166166
serde_json::json!({
167167
"name": &record.name,
168+
// The record's own primary key, and the only stable identifier a
169+
// provider can key host-side names on. The SSH provider derives its
170+
// systemd instance, env-file path and returned `backend_agent_id` from
171+
// a fragment of it: two agents can legitimately share a display name on
172+
// one host, and a name-keyed unit gave the second deploy the first
173+
// agent's env file — overwriting its minted nsec.
174+
"pubkey": &record.pubkey,
168175
"relay_url": relay_url,
169176
"private_key_nsec": &record.private_key_nsec,
170177
"auth_tag": &record.auth_tag,

‎desktop/src-tauri/src/commands/agents_tests.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,11 @@ fn deploy_payload_carries_the_full_behavioral_quad() {
440440
);
441441

442442
assert_eq!(payload["parallelism"], 4);
443+
// The record's own primary key. A provider keys host-side names on this —
444+
// the SSH provider's systemd instance and env file both carry a fragment of
445+
// it — because two agents can legitimately share a display name, and a
446+
// name-keyed unit lets the second deploy overwrite the first agent's nsec.
447+
assert_eq!(payload["pubkey"], "abcd1234");
443448
assert_eq!(payload["respond_to"], "allowlist");
444449
assert_eq!(payload["respond_to_allowlist"][0], "a".repeat(64));
445450
assert_eq!(payload["model"], "gpt-x");

‎docs/remote-agents.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -411,10 +411,13 @@ WantedBy=default.target
411411
macOS hosts reject. Resolution runs *first*; the install only fills an empty `$acp`, so a deploy
412412
that installed `buzz-acp` writes the path of the copy it just installed, not a stale one.
413413

414-
The instance name is derived from the agent name: lowercased, non-alphanumerics collapsed to `-`,
415-
truncated to 32 characters, plus an 8-hex FNV-1a suffix of the original name. The suffix is not
416-
decoration — the payload carries no stable agent identifier, so without it two agents whose names
417-
differ only in punctuation would share one unit and one env file.
414+
The instance name is the agent name made unit-safe — lowercased, non-alphanumerics collapsed to `-`,
415+
truncated to 32 characters — followed by the first 12 hex characters of the agent's `pubkey`. The
416+
name is the readable half; **the pubkey fragment is the identity**. A display name is not unique:
417+
two agents called "Research Bot" on one SSH account keyed on the name alone shared one unit, one env
418+
file and one `agent_id`, so the second deploy overwrote the first agent's minted nsec and starting
419+
either record drove whichever identity was written last. `deploy` therefore refuses a payload whose
420+
`agent.pubkey` is absent or is not a 64-character hex key, rather than falling back to the name.
418421

419422
## Env file contract
420423

0 commit comments

Comments
 (0)