Skip to content

The agent that grows with you

fix(buzz): load owner auth tag from credentials

Alex P. Günsberg51ffeb059c8b
diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.py
index f3c06a0e785..6f91909a327 100644
--- a/plugins/platforms/buzz/adapter.py
+++ b/plugins/platforms/buzz/adapter.py
@@ -361,12 +361,47 @@ def _resolve_private_key(extra: Optional[dict] = None) -> str:
return ""
+def _resolve_auth_tag(extra: Optional[dict] = None) -> str:
+ """Resolve and validate the optional NIP-OA owner-attestation tag."""
+ configured = os.getenv("BUZZ_AUTH_TAG", "").strip()
+ if configured:
+ raw: Any = configured
+ else:
+ credentials_file = os.getenv("BUZZ_CREDENTIALS_FILE", "").strip() or (extra or {}).get(
+ "credentials_file", ""
+ )
+ if not credentials_file:
+ return ""
+ try:
+ data = json.loads(Path(credentials_file).expanduser().read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return ""
+ if not isinstance(data, dict) or "auth_tag" not in data:
+ return ""
+ raw = data["auth_tag"]
+
+ if isinstance(raw, str):
+ try:
+ raw = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise ValueError("Buzz auth tag is not valid JSON") from exc
+ if (
+ not isinstance(raw, list)
+ or len(raw) != 4
+ or raw[0] != "auth"
+ or not all(isinstance(part, str) for part in raw)
+ ):
+ raise ValueError("Buzz auth tag must be a four-string auth tag")
+ return json.dumps(raw, separators=(",", ":"))
+
+
async def _exec_buzz(
cli_path: str,
args: List[str],
*,
relay_url: str,
private_key: str,
+ auth_tag: str = "",
input_text: Optional[str] = None,
timeout: float = _CLI_TIMEOUT,
) -> Tuple[int, str, str]:
@@ -379,6 +414,9 @@ async def _exec_buzz(
env = os.environ.copy()
env["BUZZ_RELAY_URL"] = relay_url
env["BUZZ_PRIVATE_KEY"] = private_key
+ env.pop("BUZZ_AUTH_TAG", None)
+ if auth_tag:
+ env["BUZZ_AUTH_TAG"] = auth_tag
proc = await asyncio.create_subprocess_exec(
cli_path,
*args,
@@ -512,6 +550,7 @@ class BuzzAdapter(BasePlatformAdapter):
# never logged). connect() re-resolves it to fail fast with a clear
# error when it is missing.
self._private_key: str = ""
+ self._auth_tag: str = ""
# Identity — filled in by connect() from ``buzz users get``
self._self_pubkey: str = ""
@@ -554,11 +593,13 @@ class BuzzAdapter(BasePlatformAdapter):
async def _run_cli(self, args: List[str], *, input_text: Optional[str] = None) -> Tuple[int, str, str]:
if not self._private_key:
self._private_key = _resolve_private_key(self._extra)
+ self._auth_tag = _resolve_auth_tag(self._extra)
return await _exec_buzz(
self.cli_path,
args,
relay_url=self.relay_url,
private_key=self._private_key,
+ auth_tag=self._auth_tag,
input_text=input_text,
)
@@ -574,7 +615,13 @@ class BuzzAdapter(BasePlatformAdapter):
logger.error("Buzz: buzz CLI binary not found (set BUZZ_CLI_PATH or put 'buzz' on PATH)")
self._set_fatal_error("cli_missing", "buzz CLI binary not found", retryable=False)
return False
- self._private_key = _resolve_private_key(self._extra)
+ try:
+ self._private_key = _resolve_private_key(self._extra)
+ self._auth_tag = _resolve_auth_tag(self._extra)
+ except ValueError as exc:
+ logger.error("Buzz: invalid owner-auth configuration — %s", exc)
+ self._set_fatal_error("config_invalid", str(exc), retryable=False)
+ return False
if not self._private_key:
logger.error("Buzz: no private key (set BUZZ_PRIVATE_KEY or a credentials file)")
self._set_fatal_error("config_missing", "BUZZ_PRIVATE_KEY must be set", retryable=False)
@@ -885,12 +932,14 @@ class BuzzAdapter(BasePlatformAdapter):
# multiplex profile a missing tag fails closed to "" instead of
# attaching the default profile's tag from os.environ, while
# single-profile and unscoped default-profile reads keep the legacy
- # env behavior (the wrapper falls back to os.environ there).
+ # env behavior. ``self._auth_tag`` is populated by connect() via
+ # ``_resolve_auth_tag`` (scope-aware read + credentials-file
+ # fallback, #79514).
event = build_auth_event(
private_key=self._private_key,
challenge=str(message[1]),
relay_url=self._websocket_url(),
- auth_tag_json=_get_scoped_secret("BUZZ_AUTH_TAG", "") or "",
+ auth_tag_json=self._auth_tag,
)
await websocket.send(json.dumps(["AUTH", event], separators=(",", ":")))
while True:
@@ -1549,6 +1598,10 @@ async def _standalone_send(
relay = (_relay_raw or extra.get("relay_url", "")).strip()
private_key = _resolve_private_key(extra)
_cli_raw = _scoped_platform_setting("BUZZ_CLI_PATH", extra, "cli_path")
+ try:
+ auth_tag = _resolve_auth_tag(extra)
+ except ValueError as exc:
+ return {"error": f"Buzz standalone send: {exc}"}
cli_path = _resolve_cli_path(
str(_cli_raw or "").strip() or str(extra.get("cli_path", "") or "")
)
@@ -1568,7 +1621,12 @@ async def _standalone_send(
args += ["--file", str(path)]
try:
code, out, err = await _exec_buzz(
- cli_path, args, relay_url=relay, private_key=private_key, input_text=message
+ cli_path,
+ args,
+ relay_url=relay,
+ private_key=private_key,
+ auth_tag=auth_tag,
+ input_text=message,
)
except asyncio.CancelledError:
raise
diff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.py
index b7fc5a261cb..fa2a348a13a 100644
--- a/tests/gateway/test_buzz_adapter.py
+++ b/tests/gateway/test_buzz_adapter.py
@@ -19,6 +19,7 @@ npub_to_hex = _buzz_mod.npub_to_hex
_normalize_user_ref = _buzz_mod._normalize_user_ref
_cli_error_message = _buzz_mod._cli_error_message
_resolve_private_key = _buzz_mod._resolve_private_key
+_resolve_auth_tag = _buzz_mod._resolve_auth_tag
check_requirements = _buzz_mod.check_requirements
validate_config = _buzz_mod.validate_config
register = _buzz_mod.register
@@ -46,6 +47,7 @@ _ENV_VARS = (
"BUZZ_AUTH_TAG",
"BUZZ_CLI_PATH",
"BUZZ_CREDENTIALS_FILE",
+ "BUZZ_AUTH_TAG",
)
@@ -926,6 +928,20 @@ class TestCredentialResolution:
monkeypatch.setenv("BUZZ_CREDENTIALS_FILE", str(creds))
assert _resolve_private_key() == "nsec1fromfile"
+ def test_owner_auth_tag_from_credentials_file(self, monkeypatch, tmp_path):
+ tag = ["auth", "b" * 64, "", "c" * 128]
+ creds = tmp_path / "agent_credentials.json"
+ creds.write_text(json.dumps({"nsec": "nsec1fromfile", "auth_tag": tag}), encoding="utf-8")
+ monkeypatch.setenv("BUZZ_CREDENTIALS_FILE", str(creds))
+ assert json.loads(_resolve_auth_tag()) == tag
+
+ def test_invalid_owner_auth_tag_fails_closed(self, monkeypatch, tmp_path):
+ creds = tmp_path / "agent_credentials.json"
+ creds.write_text(json.dumps({"nsec": "nsec1fromfile", "auth_tag": ["bad"]}), encoding="utf-8")
+ monkeypatch.setenv("BUZZ_CREDENTIALS_FILE", str(creds))
+ with pytest.raises(ValueError, match="auth tag"):
+ _resolve_auth_tag()
+
# ── Env enablement / registration / standalone send ──────────────────────
@@ -969,8 +985,8 @@ class TestStandaloneSend:
captured = {}
- async def fake_exec(cli_path, args, *, relay_url, private_key, input_text=None, timeout=30.0):
- captured.update(cli_path=cli_path, args=args, relay_url=relay_url, input_text=input_text)
+ async def fake_exec(cli_path, args, *, relay_url, private_key, auth_tag="", input_text=None, timeout=30.0):
+ captured.update(cli_path=cli_path, args=args, relay_url=relay_url, auth_tag=auth_tag, input_text=input_text)
return 0, json.dumps({"accepted": True, "event_id": "evt-cron", "message": ""}), ""
monkeypatch.setattr(_buzz_mod, "_exec_buzz", fake_exec)
diff --git a/tests/gateway/test_buzz_websocket.py b/tests/gateway/test_buzz_websocket.py
index d6762fb9a74..03f470a2d10 100644
--- a/tests/gateway/test_buzz_websocket.py
+++ b/tests/gateway/test_buzz_websocket.py
@@ -119,3 +119,12 @@ async def test_websocket_auth_raises_on_rejection():
await adapter._authenticate_websocket(RejectingWs())
+async def test_websocket_auth_uses_credentials_owner_tag():
+ adapter = _make_adapter()
+ adapter._auth_tag = json.dumps(["auth", "b" * 64, "", "c" * 128])
+ websocket = _FakeWebSocket()
+ await adapter._authenticate_websocket(websocket)
+ assert ["auth", "b" * 64, "", "c" * 128] in websocket.sent[0][1]["tags"]
+
+