Skip to content

Commit c3084b3

Browse files
johnmatthewtennantnpub1qye6rec0htgg3np8yt6plpyyg8cyffaq66emt3kmk05eylckkzhq0hnf2k
andauthored
fix(cli,relay): resolve agents by verified owner (#2615)
## Context `buzz users get --name Honey` searches relay-wide profiles and returns up to 100 identically named results without verified ownership metadata. An agent resolving “my Honey” cannot distinguish the requesting human's agent from another owner's agent, and the owned match can be excluded by the result limit. This caused the wrong Honey and Bumble pubkeys to be added to a channel. ## Summary This bug fix makes personal-agent resolution owner-aware. Callers can filter profiles by a verified owner identity before result limits are applied, and all profile results expose enough ownership context to diagnose duplicate names. ## Changes - Adds `buzz users get --owner me|<hex>|<npub>` for name and pubkey lookups. - Resolves `me` to the NIP-OA owner identity when the CLI runs as an agent. - Filters profiles by the relay's verified `agent_owner_pubkey` relationship before applying the result limit. - Returns `owner_pubkey`, `owner_display_name`, and client-relative `owned_by_me` in compact and JSON output. - Returns an empty result when no owned profile matches instead of removing the ownership constraint. - Rejects malformed owner values instead of silently running an unscoped query; explicit `null` remains equivalent to no owner filter for ordinary CLI lookups. - Rejects owner constraints on specialized channel-window, feed, and thread filters that cannot enforce author filtering. - Scopes owner filtering and enrichment to the active community. - Adds a partial `(community_id, agent_owner_pubkey)` index for owner lookups. - Documents the safe `users get --name Honey --owner me` lookup. ## Reviewer-reproducible examples The relay-backed test creates two same-name agents with different verified owners, queries through the HTTP `/query` route, verifies only the selected owner's agent is returned with verified owner metadata, and verifies a missing owner returns `[]`. ```bash cargo test -p buzz-relay query_agent_owner_returns_only_verified_owner_matches --lib -- --ignored ``` The owner/author intersection and unsupported-specialized-filter contracts also have infrastructure-free relay tests: ```bash cargo test -p buzz-relay agent_owner --lib ``` The CLI surface is visible in command help: ```bash cargo run -q -p buzz-cli -- users get --help | grep -- --owner ``` ```text --owner <OWNER> Filter agents by verified owner (`me`, 64-char hex, or npub) ``` ## Validation - `cargo test -p buzz-cli` (252 passed) - `cargo test -p buzz-db` (84 passed, 122 infrastructure tests ignored) - `cargo test -p buzz-relay --lib` (owner-filter tests pass; the full local suite is blocked by unrelated Postgres pool timeouts in media/admin tests) - `cargo test -p buzz-relay query_agent_owner_returns_only_verified_owner_matches --lib -- --ignored` (passed) - `cargo check --workspace --all-targets` - `cargo fmt --all -- --check` - Pre-push Rust, Desktop, and Desktop Tauri suites passed - Pre-push mobile suite could not start because `flutter` is not installed - `pnpm check:file-sizes` (passed after rebasing onto current `main`) --------- Signed-off-by: npub1qye6rec0htgg3np8yt6plpyyg8cyffaq66emt3kmk05eylckkzhq0hnf2k <0133a1e70fbad088cc2722f41f848441f044a7a0d6b3b5c6dbb3e9927f16b0ae@buzz.block.builderlab.xyz> Co-authored-by: npub1qye6rec0htgg3np8yt6plpyyg8cyffaq66emt3kmk05eylckkzhq0hnf2k <0133a1e70fbad088cc2722f41f848441f044a7a0d6b3b5c6dbb3e9927f16b0ae@buzz.block.builderlab.xyz>
1 parent 8bb43d5 commit c3084b3

8 files changed

Lines changed: 568 additions & 9 deletions

File tree

‎crates/buzz-cli/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ buzz reactions get --event <event-id>
5656
buzz users get # your own profile
5757
buzz users get --pubkey <hex> # single user
5858
buzz users get --pubkey <hex> --pubkey <hex> # batch (max 200)
59+
buzz users get --name Honey --owner me # exact-name lookup scoped to your verified owner
5960
buzz users set-presence --status online
6061

6162
# DMs

‎crates/buzz-cli/src/commands/users.rs‎

Lines changed: 94 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use nostr::PublicKey;
2+
13
use crate::client::{normalize_write_response, BuzzClient};
24
use crate::error::CliError;
35
use crate::validate::validate_hex64;
@@ -13,6 +15,7 @@ pub async fn cmd_get_users(
1315
client: &BuzzClient,
1416
pubkeys: &[String],
1517
name: Option<&str>,
18+
owner: Option<&str>,
1619
format: &crate::OutputFormat,
1720
) -> Result<(), CliError> {
1821
if let Some(query) = name {
@@ -21,7 +24,7 @@ pub async fn cmd_get_users(
2124
"--name and --pubkey are mutually exclusive".into(),
2225
));
2326
}
24-
return search_by_name(client, query, format).await;
27+
return search_by_name(client, query, owner, format).await;
2528
}
2629

2730
for pk in pubkeys {
@@ -38,12 +41,18 @@ pub async fn cmd_get_users(
3841
pubkeys.iter().map(|s| s.as_str()).collect()
3942
};
4043

44+
let owner = resolve_owner(client, owner)?;
4145
let filter = serde_json::json!({
4246
"kinds": [0],
4347
"authors": authors,
44-
"limit": authors.len()
48+
"limit": authors.len(),
49+
"include_agent_owner": true,
50+
"agent_owner": owner,
4551
});
4652
let resp = client.query(&filter).await?;
53+
let my_owner_pubkey = client
54+
.auth_tag_owner_hex()
55+
.unwrap_or_else(|| client.keys().public_key().to_hex());
4756
let events: Vec<serde_json::Value> = serde_json::from_str(&resp).unwrap_or_default();
4857
let profiles: Vec<serde_json::Value> = events
4958
.iter()
@@ -55,6 +64,7 @@ pub async fn cmd_get_users(
5564
"pubkey".to_string(),
5665
serde_json::json!(e.get("pubkey").and_then(|v| v.as_str()).unwrap_or("")),
5766
);
67+
copy_owner_fields(e, obj, &my_owner_pubkey);
5868
}
5969
Some(profile)
6070
})
@@ -66,6 +76,9 @@ pub async fn cmd_get_users(
6676
.map(|p| serde_json::json!({
6777
"pubkey": p.get("pubkey").cloned().unwrap_or_default(),
6878
"display_name": p.get("display_name").or_else(|| p.get("name")).cloned().unwrap_or_default(),
79+
"owner_pubkey": p.get("owner_pubkey").cloned().unwrap_or_default(),
80+
"owner_display_name": p.get("owner_display_name").cloned().unwrap_or_default(),
81+
"owned_by_me": p.get("owned_by_me").cloned().unwrap_or_default(),
6982
}))
7083
.collect();
7184
serde_json::to_string(&compact).unwrap_or_default()
@@ -76,23 +89,70 @@ pub async fn cmd_get_users(
7689
Ok(())
7790
}
7891

92+
fn copy_owner_fields(
93+
event: &serde_json::Value,
94+
profile: &mut serde_json::Map<String, serde_json::Value>,
95+
my_owner_pubkey: &str,
96+
) {
97+
if let Some(value) = event.get("agent_owner_pubkey") {
98+
profile.insert("owner_pubkey".to_string(), value.clone());
99+
}
100+
if let Some(value) = event.get("agent_owner_display_name") {
101+
profile.insert("owner_display_name".to_string(), value.clone());
102+
}
103+
if let Some(owner) = event
104+
.get("agent_owner_pubkey")
105+
.and_then(|value| value.as_str())
106+
{
107+
profile.insert(
108+
"owned_by_me".to_string(),
109+
serde_json::json!(owner == my_owner_pubkey),
110+
);
111+
}
112+
}
113+
114+
fn resolve_owner(client: &BuzzClient, owner: Option<&str>) -> Result<Option<String>, CliError> {
115+
owner
116+
.map(|owner| {
117+
if owner == "me" {
118+
Ok(client
119+
.auth_tag_owner_hex()
120+
.unwrap_or_else(|| client.keys().public_key().to_hex()))
121+
} else {
122+
PublicKey::parse(owner)
123+
.map(|pubkey| pubkey.to_hex())
124+
.map_err(|e| {
125+
CliError::Usage(format!("--owner must be `me`, a pubkey, or npub: {e}"))
126+
})
127+
}
128+
})
129+
.transpose()
130+
}
131+
79132
/// Search for users by display name via NIP-50 full-text search on kind:0 profiles.
80133
/// Returns [] if the relay does not implement NIP-50 search.
81134
async fn search_by_name(
82135
client: &BuzzClient,
83136
query: &str,
137+
owner: Option<&str>,
84138
format: &crate::OutputFormat,
85139
) -> Result<(), CliError> {
86140
if query.trim().is_empty() {
87141
return Err(CliError::Usage("--name cannot be empty".into()));
88142
}
89143

144+
let owner = resolve_owner(client, owner)?;
90145
let filter = serde_json::json!({
91146
"kinds": [0],
92147
"search": query,
93-
"limit": 100
148+
"limit": 100,
149+
"include_agent_owner": true,
150+
"agent_owner": owner,
94151
});
95152
let raw = client.query(&filter).await?;
153+
let my_owner_pubkey = client
154+
.auth_tag_owner_hex()
155+
.unwrap_or_else(|| client.keys().public_key().to_hex());
96156

97157
// Parse and filter client-side for case-insensitive substring match
98158
// on display_name or name fields (NIP-50 may return broader matches).
@@ -126,6 +186,7 @@ async fn search_by_name(
126186
"pubkey".to_string(),
127187
serde_json::json!(event.get("pubkey").and_then(|v| v.as_str()).unwrap_or("")),
128188
);
189+
copy_owner_fields(event, obj, &my_owner_pubkey);
129190
}
130191
Some(profile)
131192
})
@@ -137,6 +198,9 @@ async fn search_by_name(
137198
.map(|p| serde_json::json!({
138199
"pubkey": p.get("pubkey").cloned().unwrap_or_default(),
139200
"display_name": p.get("display_name").or_else(|| p.get("name")).cloned().unwrap_or_default(),
201+
"owner_pubkey": p.get("owner_pubkey").cloned().unwrap_or_default(),
202+
"owner_display_name": p.get("owner_display_name").cloned().unwrap_or_default(),
203+
"owned_by_me": p.get("owned_by_me").cloned().unwrap_or_default(),
140204
}))
141205
.collect();
142206
serde_json::to_string(&compact).unwrap_or_default()
@@ -311,9 +375,11 @@ pub async fn dispatch(
311375
) -> Result<(), CliError> {
312376
use crate::UsersCmd;
313377
match cmd {
314-
UsersCmd::Get { pubkeys, name } => {
315-
cmd_get_users(client, &pubkeys, name.as_deref(), format).await
316-
}
378+
UsersCmd::Get {
379+
pubkeys,
380+
name,
381+
owner,
382+
} => cmd_get_users(client, &pubkeys, name.as_deref(), owner.as_deref(), format).await,
317383
UsersCmd::SetProfile {
318384
name,
319385
avatar,
@@ -336,9 +402,30 @@ pub async fn dispatch(
336402

337403
#[cfg(test)]
338404
mod tests {
339-
use super::presence_subject;
405+
use super::{copy_owner_fields, presence_subject};
340406
use serde_json::json;
341407

408+
#[test]
409+
fn copy_owner_fields_marks_authenticated_owner() {
410+
let owner = "a".repeat(64);
411+
let event = json!({
412+
"agent_owner_pubkey": owner,
413+
"agent_owner_display_name": "John",
414+
});
415+
let mut profile = serde_json::Map::new();
416+
copy_owner_fields(&event, &mut profile, &"a".repeat(64));
417+
assert_eq!(profile["owner_display_name"], "John");
418+
assert_eq!(profile["owned_by_me"], true);
419+
}
420+
421+
#[test]
422+
fn copy_owner_fields_marks_other_owner() {
423+
let event = json!({"agent_owner_pubkey": "a".repeat(64)});
424+
let mut profile = serde_json::Map::new();
425+
copy_owner_fields(&event, &mut profile, &"b".repeat(64));
426+
assert_eq!(profile["owned_by_me"], false);
427+
}
428+
342429
#[test]
343430
fn presence_subject_uses_p_tag() {
344431
let event = json!({"pubkey": "relay", "tags": [["p", "user"]]});

‎crates/buzz-cli/src/lib.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,9 @@ pub enum UsersCmd {
808808
/// Search by display name (case-insensitive substring match)
809809
#[arg(long = "name")]
810810
name: Option<String>,
811+
/// Filter agents by verified owner (`me`, 64-char hex, or npub)
812+
#[arg(long = "owner")]
813+
owner: Option<String>,
811814
},
812815
/// Update the current identity's profile
813816
#[command(name = "set-profile")]

‎crates/buzz-db/src/lib.rs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1843,6 +1843,24 @@ impl Db {
18431843
user::search_users(&self.pool, community_id, query, limit).await
18441844
}
18451845

1846+
/// Return agent pubkeys whose verified owner matches `owner_pubkey`.
1847+
pub async fn list_agent_pubkeys_by_owner(
1848+
&self,
1849+
community_id: CommunityId,
1850+
owner_pubkey: &[u8],
1851+
) -> Result<Vec<Vec<u8>>> {
1852+
user::list_agent_pubkeys_by_owner(&self.pool, community_id, owner_pubkey).await
1853+
}
1854+
1855+
/// Fetch verified ownership metadata for the requested agent pubkeys.
1856+
pub async fn get_agent_owners(
1857+
&self,
1858+
community_id: CommunityId,
1859+
agent_pubkeys: &[Vec<u8>],
1860+
) -> Result<Vec<user::AgentOwner>> {
1861+
user::get_agent_owners(&self.pool, community_id, agent_pubkeys).await
1862+
}
1863+
18461864
/// Atomically set agent owner — only if no owner is currently assigned.
18471865
/// Returns Ok(true) if set, Ok(false) if an owner already exists.
18481866
pub async fn set_agent_owner(

‎crates/buzz-db/src/migration.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -560,7 +560,7 @@ mod tests {
560560
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
561561
migrations.sort_by_key(|migration| migration.version);
562562

563-
assert_eq!(migrations.len(), 24);
563+
assert_eq!(migrations.len(), 25);
564564
assert_eq!(migrations[0].version, 1);
565565
assert_eq!(&*migrations[0].description, "initial schema");
566566
assert!(migrations[0]

‎crates/buzz-db/src/user.rs‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@ use buzz_core::CommunityId;
55
use sqlx::PgPool;
66
use sqlx::Row;
77

8+
/// Ownership metadata for an agent profile.
9+
#[derive(Debug, Clone, PartialEq, Eq)]
10+
pub struct AgentOwner {
11+
/// Raw agent public key.
12+
pub agent_pubkey: Vec<u8>,
13+
/// Raw owner public key, verified when the agent authenticated via NIP-OA.
14+
pub owner_pubkey: Vec<u8>,
15+
/// Owner's current display name, when available.
16+
pub owner_display_name: Option<String>,
17+
}
18+
819
/// A user's profile fields.
920
#[derive(Debug, Clone)]
1021
pub struct UserProfile {
@@ -280,6 +291,65 @@ pub async fn search_users(
280291
.collect())
281292
}
282293

294+
/// Return agent pubkeys whose verified owner matches `owner_pubkey`.
295+
pub async fn list_agent_pubkeys_by_owner(
296+
pool: &PgPool,
297+
community_id: CommunityId,
298+
owner_pubkey: &[u8],
299+
) -> Result<Vec<Vec<u8>>> {
300+
let rows = sqlx::query_scalar::<_, Vec<u8>>(
301+
r#"
302+
SELECT pubkey
303+
FROM users
304+
WHERE community_id = $1 AND agent_owner_pubkey = $2
305+
"#,
306+
)
307+
.bind(community_id.as_uuid())
308+
.bind(owner_pubkey)
309+
.fetch_all(pool)
310+
.await?;
311+
Ok(rows)
312+
}
313+
314+
/// Fetch verified ownership metadata for the requested agent pubkeys.
315+
pub async fn get_agent_owners(
316+
pool: &PgPool,
317+
community_id: CommunityId,
318+
agent_pubkeys: &[Vec<u8>],
319+
) -> Result<Vec<AgentOwner>> {
320+
if agent_pubkeys.is_empty() {
321+
return Ok(Vec::new());
322+
}
323+
324+
let rows = sqlx::query_as::<_, (Vec<u8>, Vec<u8>, Option<String>)>(
325+
r#"
326+
SELECT agent.pubkey, agent.agent_owner_pubkey, owner.display_name
327+
FROM users agent
328+
LEFT JOIN users owner
329+
ON owner.community_id = agent.community_id
330+
AND owner.pubkey = agent.agent_owner_pubkey
331+
WHERE agent.community_id = $1
332+
AND agent.pubkey = ANY($2)
333+
AND agent.agent_owner_pubkey IS NOT NULL
334+
"#,
335+
)
336+
.bind(community_id.as_uuid())
337+
.bind(agent_pubkeys)
338+
.fetch_all(pool)
339+
.await?;
340+
341+
Ok(rows
342+
.into_iter()
343+
.map(
344+
|(agent_pubkey, owner_pubkey, owner_display_name)| AgentOwner {
345+
agent_pubkey,
346+
owner_pubkey,
347+
owner_display_name,
348+
},
349+
)
350+
.collect())
351+
}
352+
283353
/// Set the owner pubkey for an agent user.
284354
/// The owner pubkey must already exist in the users table (FK constraint).
285355
/// Returns an error if the agent pubkey is not found (rows_affected == 0).
@@ -464,6 +534,57 @@ mod tests {
464534
);
465535
}
466536

537+
#[tokio::test]
538+
#[ignore = "requires Postgres"]
539+
async fn test_agent_owner_queries_are_scoped_and_include_display_name() {
540+
let db = setup_db().await;
541+
let community = make_community(&db.pool).await;
542+
let agent_pk = random_pubkey();
543+
let other_agent_pk = random_pubkey();
544+
let owner_pk = random_pubkey();
545+
let other_owner_pk = random_pubkey();
546+
for pubkey in [&agent_pk, &other_agent_pk, &owner_pk, &other_owner_pk] {
547+
ensure_user(&db.pool, community, pubkey).await.unwrap();
548+
}
549+
update_user_profile(
550+
&db.pool,
551+
community,
552+
&owner_pk,
553+
Some("Owner Name"),
554+
None,
555+
None,
556+
None,
557+
)
558+
.await
559+
.unwrap();
560+
set_agent_owner(&db.pool, community, &agent_pk, &owner_pk)
561+
.await
562+
.unwrap();
563+
set_agent_owner(&db.pool, community, &other_agent_pk, &other_owner_pk)
564+
.await
565+
.unwrap();
566+
567+
assert_eq!(
568+
list_agent_pubkeys_by_owner(&db.pool, community, &owner_pk)
569+
.await
570+
.unwrap(),
571+
vec![agent_pk.clone()]
572+
);
573+
assert_eq!(
574+
get_agent_owners(&db.pool, community, &[agent_pk.clone(), other_agent_pk],)
575+
.await
576+
.unwrap()
577+
.into_iter()
578+
.find(|owner| owner.agent_pubkey == agent_pk)
579+
.unwrap(),
580+
AgentOwner {
581+
agent_pubkey: agent_pk,
582+
owner_pubkey: owner_pk,
583+
owner_display_name: Some("Owner Name".into()),
584+
}
585+
);
586+
}
587+
467588
/// set_channel_add_policy should persist each of the three valid policies.
468589
#[tokio::test]
469590
#[ignore = "requires Postgres"]

0 commit comments

Comments
 (0)