Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 94 additions & 2 deletions crates/buzz-acp/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ pub enum ConfigError {

#[error("config file error: {0}")]
ConfigFile(String),

#[error("key broker: {0}")]
KeyBroker(String),
}

#[derive(Debug, Clone, PartialEq, clap::ValueEnum)]
Expand Down Expand Up @@ -251,9 +254,26 @@ pub struct CliArgs {
#[arg(long, env = "BUZZ_RELAY_URL", default_value = "ws://localhost:3000")]
pub relay_url: String,

#[arg(long, env = "BUZZ_PRIVATE_KEY", hide_env_values = true)]
/// Required unless --key-broker-account is set.
#[arg(
long,
env = "BUZZ_PRIVATE_KEY",
hide_env_values = true,
default_value = "",
hide_default_value = true
)]
pub private_key: String,

/// Read the signing key from the local key broker instead of the
/// environment, and give children only this account name.
#[arg(
long,
env = "BUZZ_KEY_BROKER_ACCOUNT",
hide_env_values = true,
conflicts_with = "private_key"
)]
pub key_broker_account: Option<String>,

/// Agent owner pubkey (64-char hex). Used for --respond-to=owner-only gate.
#[arg(long, env = "BUZZ_ACP_AGENT_OWNER")]
pub agent_owner: Option<String>,
Expand Down Expand Up @@ -461,6 +481,13 @@ pub struct CliArgs {
#[arg(long, env = "BUZZ_ACP_SESSION_TITLE")]
pub session_title: Option<String>,

/// Register Claude Agent SDK sessions with Claude Remote Control so they
/// are discoverable in the owner's Claude app. Claude-only and opt-in:
/// other ACP adapters ignore it, and the default preserves local-only
/// session behavior.
#[arg(long, env = "BUZZ_ACP_CLAUDE_REMOTE_CONTROL", default_value_t = false)]
pub claude_remote_control: bool,

/// Permission mode for agents that support `session/set_config_option`
/// with `configId: "mode"` (e.g. `claude-agent-acp`).
///
Expand Down Expand Up @@ -546,6 +573,7 @@ pub struct ChannelFilter {
#[derive(Debug)]
pub struct Config {
pub keys: Keys,
pub key_broker_account: Option<String>,
pub relay_url: String,
pub agent_command: String,
pub agent_args: Vec<String>,
Expand Down Expand Up @@ -594,6 +622,8 @@ pub struct Config {
/// Sanitized session title, sent as `_meta.sessionTitle` on `session/new`.
/// `None` when unset or when the configured value sanitized to empty.
pub session_title: Option<String>,
/// Whether Claude sessions should start the Remote Control bridge.
pub claude_remote_control: bool,
/// Permission mode to apply after session creation. `Default` = skip.
pub permission_mode: PermissionMode,
/// Inbound author gate mode.
Expand Down Expand Up @@ -963,7 +993,10 @@ impl Config {
/// tests can construct `CliArgs` via `CliArgs::try_parse_from` and exercise the full
/// validation path without going through process args.
pub fn from_args(mut args: CliArgs) -> Result<Self, ConfigError> {
let keys = Keys::parse(&args.private_key)?;
let keys = match &args.key_broker_account {
Some(account) => Keys::parse(crate::key_broker::fetch(account)?.as_str())?,
None => Keys::parse(&args.private_key)?,
};
// Best-effort zeroize: overwrite the raw private key string to reduce
// exposure via core dumps or heap inspection (#41). Without the `zeroize`
// crate we can only clear the String — the allocator may retain copies.
Expand Down Expand Up @@ -1185,6 +1218,7 @@ impl Config {

let config = Config {
keys,
key_broker_account: args.key_broker_account,
relay_url: args.relay_url,
agent_command,
agent_args,
Expand Down Expand Up @@ -1223,6 +1257,7 @@ impl Config {
.session_title
.as_deref()
.and_then(sanitize_session_title),
claude_remote_control: args.claude_remote_control,
permission_mode: args.permission_mode,
respond_to: args.respond_to,
respond_to_allowlist,
Expand Down Expand Up @@ -1567,10 +1602,38 @@ mod tests {
use crate::filter::{ChannelScope, SubscriptionRule};
use clap::{Parser, ValueEnum};

#[test]
fn broker_account_replaces_the_private_key_argument() {
let args = CliArgs::parse_from([
"buzz-acp",
"--key-broker-account",
"claude-agent-private-key",
]);
assert_eq!(
args.key_broker_account.as_deref(),
Some("claude-agent-private-key")
);
assert!(args.private_key.is_empty());
}

#[test]
fn broker_account_and_private_key_cannot_both_be_set() {
let key = "0".repeat(64);
let parsed = CliArgs::try_parse_from([
"buzz-acp",
"--private-key",
&key,
"--key-broker-account",
"claude-agent-private-key",
]);
assert!(parsed.is_err());
}

/// Build a minimal Config for testing without CLI parsing.
fn test_config(mode: SubscribeMode) -> Config {
Config {
keys: nostr::Keys::generate(),
key_broker_account: None,
relay_url: "ws://localhost:3000".into(),
agent_command: "goose".into(),
agent_args: vec!["acp".into()],
Expand Down Expand Up @@ -1601,6 +1664,7 @@ mod tests {
model: None,
effort_level: None,
session_title: None,
claude_remote_control: false,
permission_mode: PermissionMode::BypassPermissions,
respond_to: RespondTo::Anyone,
respond_to_allowlist: HashSet::new(),
Expand Down Expand Up @@ -3245,4 +3309,32 @@ channels = "ALL"
Add `hide_env_values = true` to each: {violations:?}"
);
}

#[test]
fn help_exposes_explicit_claude_remote_control_opt_in() {
use clap::CommandFactory;

let help = CliArgs::command().render_long_help().to_string();
assert!(
help.contains("--claude-remote-control"),
"operators need an explicit opt-in before Claude ACP sessions register for Remote Control"
);
}

#[test]
fn claude_remote_control_is_opt_in_and_reaches_config() {
let defaults = CliArgs::try_parse_from(["buzz-acp", "--private-key", TEST_PRIVATE_KEY])
.expect("parse defaults");
assert!(!defaults.claude_remote_control);

let enabled = CliArgs::try_parse_from([
"buzz-acp",
"--private-key",
TEST_PRIVATE_KEY,
"--claude-remote-control",
])
.expect("parse opt-in");
let config = Config::from_args(enabled).expect("build config");
assert!(config.claude_remote_control);
}
}
51 changes: 45 additions & 6 deletions crates/buzz-acp/src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,22 @@ pub(crate) struct GitEnvironment {

impl GitEnvironment {
pub(crate) fn for_config(config: &mut crate::config::Config) -> anyhow::Result<Self> {
let environment =
Self::install(&config.keys, &config.relay_url, &std::env::current_exe()?)?;
let broker_mode = config.key_broker_account.is_some();
let mut environment = Self::install_with(
&config.keys,
&config.relay_url,
&std::env::current_exe()?,
!broker_mode,
)?;
// Broker mode keeps the key out of every child's environment.
if let Some(account) = &config.key_broker_account {
environment
.env
.retain(|(name, _)| name != "BUZZ_PRIVATE_KEY");
environment
.env
.push((crate::key_broker::ACCOUNT_ENV.into(), account.clone()));
}
config
.persona_env_vars
.retain(|(name, _)| !is_managed_env(name));
Expand All @@ -23,10 +37,23 @@ impl GitEnvironment {
Ok(environment)
}

/// Test seam: production goes through `for_config`, which decides `persist_key`.
#[cfg(test)]
pub(crate) fn install(
keys: &nostr::Keys,
relay_url: &str,
executable: &Path,
) -> anyhow::Result<Self> {
Self::install_with(keys, relay_url, executable, true)
}

/// With `persist_key` false, no key file exists and no config names one:
/// the Git helpers read the key from the broker when Git runs them.
fn install_with(
keys: &nostr::Keys,
relay_url: &str,
executable: &Path,
persist_key: bool,
) -> anyhow::Result<Self> {
let agent = GitIdentityMode::from_value(std::env::var_os(GIT_IDENTITY_ENV).as_deref())?
== GitIdentityMode::Agent;
Expand All @@ -37,8 +64,10 @@ impl GitEnvironment {
symlink(executable, &dir.path().join("git-sign-nostr"))?;
}
let keyfile = dir.path().join(".nostr-key");
let secret = Zeroizing::new(keys.secret_key().to_secret_hex());
write_keyfile_atomic(&keyfile, secret.as_bytes())?;
if persist_key {
let secret = Zeroizing::new(keys.secret_key().to_secret_hex());
write_keyfile_atomic(&keyfile, secret.as_bytes())?;
}
let info = KeyInfo {
keyfile_path: keyfile
.to_str()
Expand All @@ -61,12 +90,15 @@ impl GitEnvironment {
let relay = relay.as_str().trim_end_matches('/');
// `user` mode keeps only relay auth; its commits carry the operator's
// own identity, so no attribution or signing is installed.
let managed = if agent {
let mut managed = if agent {
let display_name = std::env::var("BUZZ_ACP_DISPLAY_NAME").ok();
identity_entries(&info, relay, display_name.as_deref())
} else {
vec![("nostr.keyfile".into(), info.keyfile_path.clone())]
};
if !persist_key {
managed.retain(|(key, _)| !same_config_key(key, "nostr.keyfile"));
}
// In `user` mode nothing later overrides inherited identity or signing,
// so drop agent mode's own managed keys, the author/committer
// overrides and includes.
Expand All @@ -83,6 +115,9 @@ impl GitEnvironment {
.any(|(managed, _)| same_config_key(managed, key))
});
}
if !persist_key {
inherited.retain(|(key, _)| !same_config_key(key, "nostr.keyfile"));
}
let mut env = build_git_env(relay, &managed, inherited);
let mut paths = vec![dir.path().to_path_buf()];
paths.extend(std::env::split_paths(
Expand All @@ -96,7 +131,10 @@ impl GitEnvironment {
));
env.push(("GIT_TERMINAL_PROMPT".into(), "0".into()));
// CLI flags must work even when the caller did not export these variables.
env.push(("BUZZ_PRIVATE_KEY".into(), secret.to_string()));
if persist_key {
let secret = Zeroizing::new(keys.secret_key().to_secret_hex());
env.push(("BUZZ_PRIVATE_KEY".into(), secret.to_string()));
}
env.push(("BUZZ_RELAY_URL".into(), relay_url.to_owned()));
// MCP children start from a cleared env; forward the resolved mode so a
// nested harness keeps it instead of defaulting to `agent`.
Expand Down Expand Up @@ -387,6 +425,7 @@ pub(crate) fn is_managed_env(name: &str) -> bool {
"PATH"
| "GIT_TERMINAL_PROMPT"
| "BUZZ_PRIVATE_KEY"
| crate::key_broker::ACCOUNT_ENV
| "BUZZ_RELAY_URL"
| GIT_IDENTITY_ENV
)
Expand Down
Loading
Loading