mirror of
https://github.com/block/buzz.git
synced 2026-11-16 06:11:34 +00:00
# Kubernetes backend plugin (crates/buzz-backend-kubernetes) + desktop deploy path Implements docs/remote-agents.md (merged @28ae6cd21) as ONE PR: the provider binary, the desktop changes that make it work, the harness inactivity reaper, the Sprig image, and the conformance/live-test suites. Channel: buzz-remote-agents (29414326-dba7-402d-b384-b1b34d63a2e6), thread c42b70ef. ## What's here (by lane) - **crates/buzz-backend-kubernetes** (Dawn): stdin/stdout JSON provider, info + deploy; pure classify.rs (one match arm per spec state-machine row); reconcile/GC with ownership-marker gate + same-clock orphan check; per-attempt immutable Secrets; three-tier env with clear-then-write authoritative tier. - **Desktop** (Mari): KD3 launch block from resolved descriptor, KD5 pre-secret negotiation gate (resolve-once → stage-and-digest → info → protocol gate → deploy), KD1 Windows extension strip, bundling (externalBin + Justfile + release/canary workflows + stub loops), tauri.windows.conf.json platform override (Decision B: no Windows artifact). - **buzz-acp** (Max): KD4 BUZZ_ACP_EXIT_AFTER_INACTIVITY reaper (pool-independent; reset only at accepted dispatch; in-flight turn/heartbeat defers, never resets); BUZZ_ACP_EXIT_AFTER_INACTIVITY + BUZZ_ACP_NO_PRESENCE reserved. KD8 fix. - **Image + tests** (Perci): Dockerfile.sprig (digest-pinned bases, exec buzz-acp PID 1, relay-scoped credential config), image contract script, provider conformance suites (golden wire fixtures shared with desktop tests), live-local runbook (namespace-scoped, shared-cluster safe). - **Docs** (Sami, first commit): citation re-pin c1bca1b56 →28ae6cd21(44/49 were already byte-exact; 3 offsets fixed) + I3 presence-bound correction (below). ## Named spec deviations (deliberate, each with rationale) 1. **No baked default image yet.** ghcr.io/block/buzz-sprig is unpublished (verified: anonymous pull 403 vs control 200). Omitted `image` returns an in-band field-required error instead of a default. 2. **Image override STRICTER than spec §Image:** digest-only (`name@sha256:<64hex>`); ALL tags rejected; `name:tag@digest` normalized. With no baked default the override is the only path, so tag-acceptance would make mutability the v1 norm. Strictness is reversible; a moved tag under an nsec is not. Baked digest default + tag re-acceptance = follow-up with image publish. 3. **imagePullSecrets not in schema (v1).** Explicit user images may rely on namespace-preprovisioned pull credentials — the substrate boundary. Field added only if the publish decision proves it necessary. 9-field budget intact. 4. **Decision A closed: writable empty workspace.** Nest projection = named follow-up; no image-side scaffolding. 5. **Decision D overridden by Tyler (event b55398d8):** provider ships bundled with the desktop like buzz-acp/buzz-agent; spec §Distribution's separate release workflow deleted for v1. 6. **I3/vision presence bound corrected 90s → 180s.** PRESENCE_TTL_SECS moved in #3783 during this spec's base→merge window; the number was inherited, not chosen. Spec :206/:216/:928 + inline quote + VISION_REMOTE_AGENTS.md:59 corrected. ← Tyler: the vision is your document; this edit is flagged for your explicit eyes. 7. **Spec citations are pinned to 28ae6cd21** (main at spec merge) and resolve there, not at this PR's head — this PR's own lanes move crates/buzz-acp/src/lib.rs by ~100 lines (19 citations across KD4/KD6/KD7/ §Stop/§Launch data). Known Defects rows fixed BY this PR retire on merge; the section documents main as of the pin. 8. **KD7 grace tension declared:** pod terminationGracePeriodSeconds=60 vs KD7's measured ~87s shutdown tail at parallelism 10 (~197s at cap 32). KD7 is ruled out of scope, so L1-3's "enough grace for full graceful shutdown" is NOT met at default config — deliberate, resolved by the KD7 follow-up, not silently. ## Question for Tyler Will ghcr.io/block/buzz-sprig publish PUBLIC? If private-by-policy, §Image needs an imagePullSecrets story before the baked-default follow-up can land. ## Out of scope (named follow-ups) KD6 exit-code contract + KD7 shutdown budget (gate OnFailure), OnFailure restart policy, Windows provider binary, PVCs/nest projection, mesh deployability, sprig image publish workflow + baked multi-arch digest default. ## Reproduce locally (four traps that cost us real time) **1. Git hooks inherit the invoking shell's PATH — pin the shell, not just your verification commands.** `rust-toolchain.toml` pins `1.95.0`, but the rustup shim that honors that pin lives in `~/.cargo/bin`. If Homebrew's cargo is earlier on PATH, `cargo` in this repo is 1.89.0, which cannot build the workspace at all: ``` $ /opt/homebrew/bin/cargo check -p buzz-db error: rustc 1.89.0 is not supported by the following packages: sqlx@0.9.0 requires rustc 1.94.0 ... # exit 101 ``` Verifying with `PATH="$HOME/.cargo/bin:$PATH" cargo test` does *not* protect the push: lefthook's `pre-push` → `just test-unit` re-resolves `cargo` from the shell's own PATH, so a green local run is followed by a hook failure on a crate you never touched. Export the PATH for the whole shell, not per-command. This bit twice. **2. Line-scope your mutations, or the mutation edits its own detector.** When mutation-testing the respond-to guard, a whole-file `sed` on the mode literal touches 5 sites — the guard *and* the fixtures/assertions that test it. The mutation and its detector move together and the suite stays green, which reads as "this code is dead" when it actually means "you deleted the experiment": ``` # WRONG — 5 sites, guard and tests mutate together $ sed -i '' 's/"allowlist"/"allowlist-DISABLED"/g' src/env.rs test result: ok. 145 passed; 0 failed # false survivor # RIGHT — 1 site, anchored to the guard's own definition line $ sed -i '' '/^const RESPOND_TO_ALLOWLIST/s/"allowlist"/"allowlist-DISABLED"/' src/env.rs failures: env::tests::allowlist_mode_with_an_empty_list_is_refused env::tests::an_allowlist_entry_that_is_not_64_hex_is_refused test result: FAILED. 143 passed; 2 failed # real kill ``` Restore by copying a pristine file back and confirming `git diff --stat` is empty, not by re-running an inverse `sed`. **3. A completeness guard is not a correctness guard.** The shared wire fixture `tests/fixtures/provider-wire/deploy-full-launch.request.json` passed every test we had while containing four classes of invented data (wrong `respond_to` encoding, an env key no emitter writes, allowlist entries that fail the harness's own 64-hex rule, a `launch.env` key from no descriptor layer). The provider's tests could not have caught this: its types are deliberately indifferent to these values (`Option<String>`, `Vec<String>`, arbitrary map), so "the provider parses it" was never evidence that the desktop emits it. The fix was not a stronger provider assertion but a rule about provenance — "recorded" means executed-and-transcribed, and the desktop's whole-object equality test is the only enforcement that can exist. See the fixture README. **4. Every drift this arc was a value that agreed with itself.** Five invented values were found, and not one was caught by an assertion failing — each was caught by someone asking where a value came from. A named constant referenced symbolically on both the fixture and assertion side. A `sed` that mutated its own detector. Six probe rows that all died at the same unrelated error. A descriptor struct literal compared against a fixture built from that literal (`launch.args: ["run","--session"]`, which the resolver actually returns as `["acp"]`). The general defense is not more assertions but provenance: a stub is a control that varies nothing, and the more faithful it looks the better it hides. Ask what executed, not what passed. *Fixture-test determinism caveat (post-verification, Quinn + Dawn).* The desktop's whole-object fixture test calls the real resolver, which consults a process-global harness registry whose own docs require `registry_test_lock` for any test touching it. The fixture test holds no lock and is nonetheless deterministic — but by containment, not by ordering. Measured, not derived: planting a definition with `id: "goose"` directly into the registry (bypassing the loader) changes the resolved descriptor from `args: ["acp"]` to `args: ["--poisoned"]`, so `resolve_effective_harness_descriptor` **does** reach the registry for this id — it does not short-circuit on the builtin table first. Two controls discriminate: an empty registry and a registry poisoned under a *different* id both return `["acp"]`. What actually protects the test is that the registry has exactly one writer (`update_loaded_harness_registry`, reached only via `warm_harness_registry_from_dir`) — but that writer concatenates **two** sources of unequal strength (`custom_harnesses.rs:319-326`). Custom files pass through `load_custom_harnesses`, whose `check_id_collision` rejects the reserved builtin id `goose` case-insensitively at the loader — and that leg is tested (`load_applies_id_collision_check` writes a real `goose.json` and asserts the loader drops it). Preset definitions (`preset_harness_definitions`, `presets.rs:177-193`) are a bare `.map` over `PRESET_HARNESSES` with **no collision check** — exhaustive call-site enumeration at `60007fda4` finds four production `check_id_collision` sites, none on the preset path. That leg holds only because `goose` is not in the preset table today (intersection of TIER1 and preset ids is empty) — executed, not just read: adding a preset with `id: "goose"`, `args: ["--poisoned"]` and warming via the normal preset-only path (`warm_harness_registry_from_dir(None)`, no custom dir, no direct writer) flips the fixture's emitted `launch.args` from `["acp"]` to `["--poisoned"]` at `60007fda4`, command/env/policy_env unchanged. So: no test in the suite can put a `goose` entry in the registry via the custom path, and no preset currently carries one, so no interleaving can perturb this fixture — containment with one checked leg and one coincidental one. A future fixture built on a **non-builtin** runtime id has no containment at all — it would be order-dependent against whatever registry-writing test ran last and must take the lock. *Late instance, found while reviewing the mode guard.* The guard exact-matches `respond_to` untrimmed and case-sensitively, which is only correct if clap's `ValueEnum` derive is case-sensitive. `config.rs` gives two answers: the derive at `:448-453` carries no `ignore_case`, while the crate's own tests call `RespondTo::from_str(s, true)` — `ignore_case = true`. Reading the source supports either. Measured on the built binary instead: `owner-only` starts, `OWNER-ONLY` / `Owner-Only` / `ALLOWLIST` / `NOBODY` all exit rc=2 `invalid value`. Case-sensitive at the CLI, so the guard is right — and right for a reason the source does not state. The `from_str(_, true)` tests exercise a different surface and are not evidence about the CLI. *Corollary, and the sharper half.* When a test helper **reimplements** production instead of calling it, the helper is a fork — and a fork can be right while production is wrong, or wrong in the same way, and the suite reports green either way. Both `BUZZ_ACP_ALLOWED_*` gates are forked like this: production compares **strings** while the helpers compare **post-parse enums** (`config.rs:2623`) or re-derive the split (`buzz-cli/.../channels.rs:1296`). Production and the helper each carry their *own* copy of the empty-entry filter (`:1025` and `:1300`), so fixing one says nothing about the other. Measured on `buzz-cli`, restoring byte-exact between runs: | tree | result | |---|---| | baseline | 274 passed | | drop the empty-filter in **production** only (the real fix) | **274 passed** — no signal | | drop it in the **test helper** only | **273 passed, 1 failed** (`channels.rs:1338`) | Two independent defects, stacked, and worse together than either alone: production can be fixed with no test ever noticing, *and* the helper cannot be corrected without a false alarm demanding the bug back. The root cause is one bit of type information — `check_allowed_channel_add_policy(allowed_raw: &str, ..)` cannot represent "unset", while production reads `env::var(..) -> Result`, where unset and `""` are different states. A helper whose parameter type can't represent all of production's input states isn't testing production's states — it's testing a subset it silently chose. Same family as the struct-literal descriptor and the fixture drift: the test and the thing it tests agreeing with each other, rather than the test measuring the thing. Neither defect is in this PR's diff (`git diff --name-only28ae6cd21<head> -- crates/buzz-cli` is empty); both are now filed as NIP-34 issues on this repo: the fail-open + fork-helper defect at issue event `0524a4113f2d97fd…` and the respond-to self-lock at `e32837498969b5e7…` (filed 2026-08-02 after Quinn measured that no prior filing existed — zero hits on GitHub `block/buzz` open *or* closed and zero on the relay's kind:1621 issues, against working positive controls). The prescription was itself mutation-tested before being written down: repairing the fork's signature (`Option<&str>` + assertion → `None`) still let the reintroduced production bug ship 274-green — an expressive fork is still a fork; it never executes production. So the `buzz-cli` fix has **three parts and one explicit keep**: drop the production filter; **delete** the helper and point its tests at the real `cmd_set_add_policy` (which self-discriminates by error variant — `Usage` = refused, `Network(BadScheme)` = passed the gate — no relay needed); serialize the env-var tests behind one **`tokio::sync::Mutex::const_new`** lock taken with `.lock().await`, including the pre-existing `:1362` integration test (the fork was silently buying test isolation — without the lock, parallel runs flake nondeterministically; a `std::sync::Mutex` held across `.await` trips `clippy::await_holding_lock` under `-D warnings`); and **keep** the then-dead `!allowed.is_empty()` clause with a comment saying why. It is unreachable-false (`split(',')` never yields an empty vec), but it is the only thing that keeps the reintroduced production bug detectable — mutation-tested: on a tree that deletes the clause, reintroducing the empty-filter bug survives 275/0, because `""`/`","`/`" "` refuse either way and the filter goes semantically inert. Dead code can be load-bearing for tests: "provably unreachable" is an argument about behavior, never about coverage. When a helper forks production, the fix has to delete the fork: any change that leaves two implementations standing can only ever be verified against the one the tests call. *Final shape:* the keep and the broad lock are both artifacts of the fork surviving in some form. The extraction variant (Dawn, mutation-tested at `60007fda4`) removes the tension: extract one `check_channel_add_policy_allowed(Option<&str>, &str)` that **production calls**, with the `Option` placed at the env boundary where the `Result<String, VarError>` bit actually lives. 5/6 mutants killed; the empty-filter survivor is proven **equivalent** (exhaustive 6174-pair check, 0 divergences, with a diverging negative control; independently re-derived by a second generator — different tokens and shape — 0 divergences on admitted policies, 500 on a non-admitted control), not a coverage hole — on a one-implementation tree there is no fork left to witness, so no dead clause needs keeping. One scope line on that equivalence: it is **caller-conditional**, a property of the only current caller, not of the gate function — `cmd_set_add_policy`'s own match at `:1027-1034` admits only three policies before the gate runs; a second caller reaching the gate with arbitrary strings resurrects m1 as a real hole. The lock does not disappear, it narrows (Dawn's own correction, caught by Mari): lock exactly the tests that mutate the process env — three-plus-one on a fork tree, two on the extraction tree — behind one `tokio::sync::Mutex`, and the lock is part of the assertion, not hygiene: with it deleted, the gate test fails 8/8 runs deterministically by receiving `Network(BadScheme)` where it expects `Usage` — the unset test's `remove_var` clobbers the other's `set_var`, and **the gate test passes straight through the gate**, a false negative on the exact authz assertion the test exists to make. State it as an outcome: these two tests must not observe each other's env writes. 276/0 stable across 5 parallel runs, clippy `-D warnings` clean; independently verified (patch applied to a second worktree: result blob `d67e584be` matches the patch index, full mutant matrix reproduces row for row). One new row no earlier prescription covered: collapsing unset into `Some("")` fails **closed** — an unconfigured deployment refuses every policy — killed by the unset test. Patch: `OUTBOX/BUZZ_CLI_ADD_POLICY_GATE_EXTRACT_FIX.patch`. The filed issue (`0524a411…`) carries the fork-shape prescription; whoever picks it up should prefer the extraction shape, drop the dead-clause keep with it, and keep part 3 outcome-shaped: serialize whichever tests mutate the env. ## Verification (final HEAD `60007fda4`) - Full touched-package suites at each integration merge (log in plan file). At candidate parent `00e5b5fe9`: buzz-backend-kubernetes 154, buzz-acp 673, desktop tauri 2100+3, pnpm 3908, workspace clippy/fmt/tsc all clean. The only delta to `60007fda4` is one character in `scripts/test-k8s-sprig-image-live.sh` (heredoc escape so the readlink probe evaluates pod-side, not host-side at render); `crates/` tree hash is byte-identical at both SHAs, so the Rust receipts attach by tree identity. buzz-backend-kubernetes suite re-run in-shell at `HEAD == 60007fda4`: 154 passed. - Adversarial one-HEAD gate (Sami): guard matrix 12/12, predicate mutants 7/7, doomed-invocation finding closed end-to-end; tree-hash carry to `60007fda4` confirmed (crates/buzz-backend-kubernetes blob unchanged). - Live-local pass per TESTING.md + skill-buzz-testing (Perci, at `60007fda4`): explicit `docker-desktop` context, digest-qualified image imported into node containerd `k8s.io` namespace, pull policy `Never`; pod printed `DIGEST_ABI_OK`, `resolved_spec` and `image_id` both the exact requested digest, script exit 0. Dedicated per-run namespace, ownership labels on every object, scoped cleanup verified empty after. - Implementation review (Wren) at `60007fda4`: 9.6 minimalness / 9.4 elegance / 9.3 correctness, no blocker. - `origin/eva/k8s-backend` == `60007fda4` (ls-remote verified; SHA identity is byte identity). --------- Signed-off-by: npub1mprnacetjua2xx3p5eddmhxyk6wv929ymm5py8kd2xfxurxahspqqlgyta <d8473ee32b973aa31a21a65adddcc4b69cc2a8a4dee8121ecd51926e0cddbc02@buzz.block.builderlab.xyz> Signed-off-by: Tyler <109685178+tlongwell-block@users.noreply.github.com> Signed-off-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz> Signed-off-by: tlongwell-block <109685178+tlongwell-block@users.noreply.github.com> Signed-off-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@buzz.block.builderlab.xyz> Signed-off-by: npub1t2tgm7d8f995uqvmnm8h88sg3wnpp9a5xysjf6dg3tjmgt3ltulqdp8ehr <5a968df9a7494b4e019b9ecf739e088ba61097b4312124e9a88ae5b42e3f5f3e@buzz.block.builderlab.xyz> Co-authored-by: npub1mprnacetjua2xx3p5eddmhxyk6wv929ymm5py8kd2xfxurxahspqqlgyta <d8473ee32b973aa31a21a65adddcc4b69cc2a8a4dee8121ecd51926e0cddbc02@buzz.block.builderlab.xyz> Co-authored-by: npub17jjz49l9jjmhhk7cac63j8yt9z555n9cw8vk7v5jz4vzw4ppld5qgj57cc <f4a42a97e594b77bdbd8ee35191c8b28a94a4cb871d96f32921558275421fb68@buzz.block.builderlab.xyz> Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz> Co-authored-by: Dawn (sprout agent) <c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@buzz.block.builderlab.xyz> Co-authored-by: npub1t2tgm7d8f995uqvmnm8h88sg3wnpp9a5xysjf6dg3tjmgt3ltulqdp8ehr <5a968df9a7494b4e019b9ecf739e088ba61097b4312124e9a88ae5b42e3f5f3e@buzz.block.builderlab.xyz>
733 lines
31 KiB
Rust
733 lines
31 KiB
Rust
//! Building the pod environment (spec §Launch data, §Entrypoint mapping table).
|
|
//!
|
|
//! The three tiers are resolved *here*, before serialization, because a
|
|
//! Kubernetes Secret's `data` is a flat map with no precedence of its own: if
|
|
//! two tiers supplied the same key, whichever entry landed in the map would
|
|
//! win silently. Resolving in-provider makes later-wins explicit and testable.
|
|
|
|
use crate::wire::{AgentPayload, LaunchBlock};
|
|
use std::collections::BTreeMap;
|
|
|
|
/// Keys the authoritative tier owns.
|
|
///
|
|
/// Load-bearing, not documentation: tier 3 *clears* every key on this list
|
|
/// before writing its own values, so a key the authoritative tier has no value
|
|
/// for is **removed** rather than left holding a lower-tier value. Plain
|
|
/// overwrite is not enough — most of these are written conditionally
|
|
/// (`BUZZ_ACP_AGENT_ARGS` only when `launch.args` is non-empty,
|
|
/// `BUZZ_ACP_RESPOND_TO` only when set), and without the clear, a lower tier
|
|
/// could supply the value for exactly the cases the authoritative tier stays
|
|
/// silent on. Clearing is also what the local spawn does: the desktop strips
|
|
/// reserved keys from user env before the authoritative layer is written
|
|
/// (`env_vars.rs:54-57`), so absent-means-absent in both paths.
|
|
const AUTHORITATIVE_KEYS: &[&str] = &[
|
|
"BUZZ_RELAY_URL",
|
|
"BUZZ_PRIVATE_KEY",
|
|
"NOSTR_PRIVATE_KEY",
|
|
"BUZZ_AUTH_TAG",
|
|
"BUZZ_ACP_AGENT_OWNER",
|
|
"BUZZ_ACP_AGENT_COMMAND",
|
|
"BUZZ_ACP_AGENT_ARGS",
|
|
"BUZZ_ACP_RESPOND_TO",
|
|
"BUZZ_ACP_RESPOND_TO_ALLOWLIST",
|
|
"BUZZ_ACP_MCP_COMMAND",
|
|
"BUZZ_ACP_EXIT_AFTER_INACTIVITY",
|
|
START_NONCE_KEY,
|
|
];
|
|
|
|
/// The attempt's generation, as the harness sees it. Also the Secret's name
|
|
/// suffix — one generation, one identity — so the reconciler restamps this on
|
|
/// every create attempt rather than letting the caller's value persist across
|
|
/// a retry.
|
|
pub const START_NONCE_KEY: &str = "BUZZ_MANAGED_AGENT_START_NONCE";
|
|
|
|
/// Presence is the only remote liveness signal (I3), so a launch that
|
|
/// suppresses it is non-conforming (L1 item 2) — and unlike a reserved-key
|
|
/// collision, there is no "authoritative value" to overwrite it with. Refuse.
|
|
const FORBIDDEN_KEY: &str = "BUZZ_ACP_NO_PRESENCE";
|
|
|
|
/// Kubernetes' own cap on the summed value bytes of a Secret
|
|
/// (`MaxSecretSize`, `pkg/apis/core/types.go`). Enforced here so an oversized
|
|
/// env surfaces as a named provider error rather than an apiserver rejection
|
|
/// partway through a deploy.
|
|
const MAX_SECRET_BYTES: usize = 1024 * 1024;
|
|
|
|
/// A POSIX-shaped env var name: `[A-Za-z_][A-Za-z0-9_]*`.
|
|
///
|
|
/// Kubernetes validates Secret *keys* as `IsConfigMapKey`
|
|
/// (`[-._a-zA-Z0-9]+`), which is looser — `foo.bar` is a legal Secret key.
|
|
/// What the kubelet then does with such a key **changed between versions**:
|
|
/// through 1.29 it filtered invalid env names out of `envFrom` and emitted an
|
|
/// `InvalidEnvironmentVariableNames` warning event
|
|
/// (`pkg/kubelet/kubelet_pods.go:646,654` at v1.29.0); from 1.30 that filter
|
|
/// is gone (KEP-4369) and the key is injected verbatim. The same manifest
|
|
/// would silently drop a variable on one cluster and set it on another, so we
|
|
/// fail closed on the provider side and get one deterministic behavior.
|
|
fn is_posix_env_key(key: &str) -> bool {
|
|
let mut chars = key.chars();
|
|
match chars.next() {
|
|
Some(c) if c == '_' || c.is_ascii_alphabetic() => {}
|
|
_ => return false,
|
|
}
|
|
chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
|
|
}
|
|
|
|
/// An identity component (L1 item 1) is present only if it is nonempty after
|
|
/// trimming — and the **trimmed form is what gets stored**. The validator and
|
|
/// the writer must never disagree about the value: a guard that accepts
|
|
/// `" wss://relay "` and then writes it with the padding intact has only
|
|
/// moved the failure from a loud refusal to a connect error in the harness.
|
|
fn identity_component(value: &str) -> Option<&str> {
|
|
let trimmed = value.trim();
|
|
(!trimmed.is_empty()).then_some(trimmed)
|
|
}
|
|
|
|
/// The harness's `allowlist` gate mode, spelled as the desktop serializes
|
|
/// `RespondTo` (kebab-case) and as `buzz-acp`'s CLI parses it.
|
|
const RESPOND_TO_ALLOWLIST: &str = "allowlist";
|
|
|
|
/// Every gate mode `buzz-acp` accepts, spelled as its `clap::ValueEnum` parses
|
|
/// them (`config.rs:95-101`, kebab-case via `RespondTo`'s `Display`).
|
|
///
|
|
/// Deliberately the **harness's** four and not the desktop's three: the desktop
|
|
/// rejects `nobody` on purpose (`managed_agents/types.rs:871-880`), but the
|
|
/// harness starts fine with it. This guard exists to cover non-desktop callers,
|
|
/// so inheriting a desktop-only narrowing would refuse a launch that works.
|
|
const RESPOND_TO_MODES: [&str; 4] = ["owner-only", RESPOND_TO_ALLOWLIST, "anyone", "nobody"];
|
|
|
|
/// Refuse a respond-to gate the harness will reject at config parse.
|
|
///
|
|
/// The local spawn path re-validates this before spawning — "doing it here
|
|
/// means we never spawn a doomed process" (`runtime.rs:378`) — but the deploy
|
|
/// path projects the record's fields straight through. Without this, a gate
|
|
/// the harness refuses becomes a pod that exits 1 at startup; `restartPolicy:
|
|
/// Never` turns that into `Terminated` → `Delete` → recreate, and each cycle
|
|
/// leaves a Secret the in-call path never reaps (only a later deploy's orphan
|
|
/// sweep does, at `ORPHAN_SECRET_MIN_AGE_SECS`). The user-visible ending is
|
|
/// "startup not confirmed", indistinguishable from a slow cluster.
|
|
///
|
|
/// Mirrors `buzz-acp`'s own rules exactly (`config.rs:95-101,996-1004,629-641`),
|
|
/// deliberately including their asymmetry: the allowlist is validated **only**
|
|
/// in allowlist mode, and merely warned about otherwise. Validating it in
|
|
/// every mode would refuse a deploy whose identical local spawn succeeds —
|
|
/// and a stale list is already harmless here, since
|
|
/// `BUZZ_ACP_RESPOND_TO_ALLOWLIST` is an authoritative key that tier 3 clears.
|
|
fn validate_respond_to_gate(respond_to: &str, allowlist: Option<&[String]>) -> Result<(), String> {
|
|
// Exact, untrimmed: `clap` does not trim, so `" allowlist "` is `rc=2` at
|
|
// the harness — a parse failure even earlier than the config errors below.
|
|
if !RESPOND_TO_MODES.contains(&respond_to) {
|
|
return Err(format!(
|
|
"deploy refused: respond_to {respond_to:?} is not a mode the \
|
|
harness accepts (expected one of {}) — the pod would fail to \
|
|
parse its arguments, be replaced, and leave a Secret behind on \
|
|
every attempt",
|
|
RESPOND_TO_MODES.join(", ")
|
|
));
|
|
}
|
|
if respond_to != RESPOND_TO_ALLOWLIST {
|
|
return Ok(());
|
|
}
|
|
let entries = allowlist.unwrap_or_default();
|
|
if entries.is_empty() {
|
|
return Err(format!(
|
|
"deploy refused: respond_to is {RESPOND_TO_ALLOWLIST:?} but the \
|
|
allowlist is empty — the harness refuses this at startup, so the \
|
|
pod would fail, be replaced, and leave a Secret behind on every \
|
|
attempt"
|
|
));
|
|
}
|
|
for entry in entries {
|
|
let trimmed = entry.trim();
|
|
if trimmed.len() != 64 || !trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
|
|
return Err(format!(
|
|
"deploy refused: invalid pubkey in respond_to_allowlist: \
|
|
{entry:?} (must be exactly 64 hex characters)"
|
|
));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Inputs the provider itself supplies to the authoritative tier.
|
|
pub struct AuthoritativeInputs<'a> {
|
|
/// The attempt's generation token — also the Secret's name suffix, so the
|
|
/// lifecycle correlator and the Secret generation are one identity.
|
|
pub generation: &'a str,
|
|
/// Resolved from `provider_config.inactivity_seconds`; `None` when the
|
|
/// indefinite opt-in was chosen (which this version refuses elsewhere).
|
|
pub inactivity_seconds: Option<u64>,
|
|
}
|
|
|
|
/// Resolve the full pod environment.
|
|
///
|
|
/// Order is the spec's, and the function body is deliberately three writes in
|
|
/// that order — tier 1, tier 2, tier 3 — so "later wins" is visible rather
|
|
/// than argued.
|
|
pub fn build_env(
|
|
agent: &AgentPayload,
|
|
auth: AuthoritativeInputs<'_>,
|
|
) -> Result<BTreeMap<String, String>, String> {
|
|
let default_launch = LaunchBlock::default();
|
|
let launch = agent.launch.as_ref().unwrap_or(&default_launch);
|
|
|
|
let mut env: BTreeMap<String, String> = BTreeMap::new();
|
|
|
|
// Tier 1 — overridable behavior defaults.
|
|
env.extend(launch.policy_env.clone());
|
|
|
|
// Tier 2 — user/layered env. The descriptor already merged
|
|
// global < persona < agent, so `agent.env_vars` is NOT re-merged on top
|
|
// (§Launch data tier 2) — doing so would resurrect a layer the desktop
|
|
// already resolved. When the desktop predates the `launch` block we fall
|
|
// back to the legacy field, which is the only case it is the truth.
|
|
if agent.launch.is_some() {
|
|
env.extend(launch.env.clone());
|
|
} else {
|
|
env.extend(agent.env_vars.clone());
|
|
}
|
|
|
|
// Validate what the lower tiers contributed, before the authoritative
|
|
// tier overwrites any of it. A reserved-key collision is NOT fatal: the
|
|
// spec's precedence is later-wins, so tier 3 simply overwrites it, which
|
|
// is exactly what a local spawn does. Only a key that has no
|
|
// authoritative counterpart to overwrite it — presence suppression — is
|
|
// a refusal.
|
|
for key in env.keys() {
|
|
if !is_posix_env_key(key) {
|
|
return Err(format!(
|
|
"env key {key:?} is not a POSIX environment variable name \
|
|
([A-Za-z_][A-Za-z0-9_]*); Kubernetes would treat it \
|
|
inconsistently across cluster versions"
|
|
));
|
|
}
|
|
if key.eq_ignore_ascii_case(FORBIDDEN_KEY) {
|
|
return Err(format!(
|
|
"{FORBIDDEN_KEY} must not be set on a remote agent: presence \
|
|
is the only signal that a remote agent is alive"
|
|
));
|
|
}
|
|
}
|
|
|
|
// Tier 3 — authoritative. Every key it owns is cleared first, then the
|
|
// values it has are written, so it wins at a key whether or not it has a
|
|
// value there (see [`AUTHORITATIVE_KEYS`]).
|
|
for key in AUTHORITATIVE_KEYS {
|
|
env.remove(*key);
|
|
}
|
|
// Identity comes from top-level payload fields, never from `env_vars`
|
|
// (§Reserved-key rule). All three components must be nonempty: an agent
|
|
// that cannot reach a relay is the identityless launch L1 item 1 exists to
|
|
// prevent, and a blank field would otherwise sail through into the Secret
|
|
// and produce a pod that starts, fails to connect, and looks like a
|
|
// network problem.
|
|
let Some(relay_url) = identity_component(&agent.relay_url) else {
|
|
return Err("deploy refused: relay_url is empty — the agent would have \
|
|
no relay to connect to"
|
|
.to_string());
|
|
};
|
|
env.insert("BUZZ_RELAY_URL".into(), relay_url.to_string());
|
|
env.insert("BUZZ_PRIVATE_KEY".into(), agent.private_key_nsec.clone());
|
|
// The git credential/signing helpers read NOSTR_PRIVATE_KEY.
|
|
env.insert("NOSTR_PRIVATE_KEY".into(), agent.private_key_nsec.clone());
|
|
|
|
// Owner: at least one of these must resolve, or the harness cannot match
|
|
// `!shutdown` and §Stop describes a mechanism that does not work.
|
|
let auth_tag = agent.auth_tag.as_deref().and_then(identity_component);
|
|
let owner = launch.owner_pubkey.as_deref().and_then(identity_component);
|
|
match (auth_tag, owner) {
|
|
(None, None) => {
|
|
return Err("deploy refused: neither auth_tag nor launch.owner_pubkey \
|
|
resolved — without an owner the agent cannot honor \
|
|
!shutdown"
|
|
.to_string())
|
|
}
|
|
(tag, own) => {
|
|
if let Some(t) = tag {
|
|
env.insert("BUZZ_AUTH_TAG".into(), t.to_string());
|
|
}
|
|
if let Some(o) = own {
|
|
env.insert("BUZZ_ACP_AGENT_OWNER".into(), o.to_string());
|
|
}
|
|
}
|
|
}
|
|
|
|
// The harness and MCP binaries are resolved against the *image's* PATH.
|
|
// A host path forwarded from the desktop is guaranteed absent in the
|
|
// container (§Launch data, host-resolved values).
|
|
if let Some(command) = launch.command.as_deref().filter(|c| !c.is_empty()) {
|
|
env.insert("BUZZ_ACP_AGENT_COMMAND".into(), command.to_string());
|
|
}
|
|
if !launch.args.is_empty() {
|
|
// Comma-joined because that is what the harness's CLI parser decodes,
|
|
// and what the desktop's local spawn does. An argument containing a
|
|
// comma is unrepresentable in both paths; inventing an escaping
|
|
// scheme here would produce args the harness cannot decode.
|
|
env.insert("BUZZ_ACP_AGENT_ARGS".into(), launch.args.join(","));
|
|
}
|
|
env.insert("BUZZ_ACP_MCP_COMMAND".into(), "buzz-dev-mcp".into());
|
|
|
|
if let Some(respond_to) = agent.respond_to.as_deref().filter(|s| !s.is_empty()) {
|
|
validate_respond_to_gate(respond_to, agent.respond_to_allowlist.as_deref())?;
|
|
env.insert("BUZZ_ACP_RESPOND_TO".into(), respond_to.to_string());
|
|
}
|
|
if let Some(list) = agent
|
|
.respond_to_allowlist
|
|
.as_ref()
|
|
.filter(|l| !l.is_empty())
|
|
{
|
|
env.insert("BUZZ_ACP_RESPOND_TO_ALLOWLIST".into(), list.join(","));
|
|
}
|
|
|
|
if let Some(secs) = auth.inactivity_seconds {
|
|
env.insert("BUZZ_ACP_EXIT_AFTER_INACTIVITY".into(), secs.to_string());
|
|
}
|
|
// The generation token doubles as the lifecycle-frame correlator, so pod
|
|
// logs and observer frames share one identity (§K8s Secrets).
|
|
env.insert(START_NONCE_KEY.into(), auth.generation.to_string());
|
|
|
|
let total: usize = env.values().map(String::len).sum();
|
|
if total > MAX_SECRET_BYTES {
|
|
return Err(format!(
|
|
"agent environment is {total} bytes; Kubernetes caps Secret data \
|
|
at {MAX_SECRET_BYTES}"
|
|
));
|
|
}
|
|
|
|
Ok(env)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn payload_json(extra_agent: serde_json::Value) -> AgentPayload {
|
|
let mut agent = serde_json::json!({
|
|
"name": "a",
|
|
"relay_url": "wss://relay.example",
|
|
"private_key_nsec": "nsec1example",
|
|
"auth_tag": "tag-1",
|
|
});
|
|
let (serde_json::Value::Object(base), serde_json::Value::Object(extra)) =
|
|
(&mut agent, extra_agent)
|
|
else {
|
|
panic!("expected objects")
|
|
};
|
|
base.extend(extra);
|
|
serde_json::from_value(agent).unwrap()
|
|
}
|
|
|
|
fn build(agent: &AgentPayload) -> Result<BTreeMap<String, String>, String> {
|
|
build_env(
|
|
agent,
|
|
AuthoritativeInputs {
|
|
generation: "gen0001",
|
|
inactivity_seconds: Some(7200),
|
|
},
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn identity_comes_from_top_level_fields() {
|
|
let env = build(&payload_json(serde_json::json!({}))).unwrap();
|
|
assert_eq!(env["BUZZ_RELAY_URL"], "wss://relay.example");
|
|
assert_eq!(env["BUZZ_PRIVATE_KEY"], "nsec1example");
|
|
assert_eq!(env["NOSTR_PRIVATE_KEY"], "nsec1example");
|
|
assert_eq!(env["BUZZ_AUTH_TAG"], "tag-1");
|
|
}
|
|
|
|
/// Wren's amendment, and the spec's later-wins rule: a lower tier that
|
|
/// spoofs an authoritative key is *overwritten*, not refused. Refusing
|
|
/// would diverge from the local spawn, where the same env is written
|
|
/// before the authoritative layer and simply loses.
|
|
#[test]
|
|
fn lower_tiers_cannot_spoof_authoritative_values() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"launch": {
|
|
"command": "goose",
|
|
"policy_env": {
|
|
"BUZZ_PRIVATE_KEY": "nsec1attacker",
|
|
"BUZZ_MANAGED_AGENT_START_NONCE": "forged",
|
|
},
|
|
"env": {
|
|
"BUZZ_RELAY_URL": "wss://attacker.example",
|
|
"NOSTR_PRIVATE_KEY": "nsec1attacker",
|
|
"BUZZ_AUTH_TAG": "forged-tag",
|
|
"BUZZ_ACP_AGENT_OWNER": "cafe",
|
|
"BUZZ_ACP_AGENT_COMMAND": "/bin/sh",
|
|
"BUZZ_ACP_MCP_COMMAND": "/bin/sh",
|
|
"BUZZ_ACP_EXIT_AFTER_INACTIVITY": "0",
|
|
},
|
|
"owner_pubkey": "beef"
|
|
}
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
assert_eq!(env["BUZZ_PRIVATE_KEY"], "nsec1example");
|
|
assert_eq!(env["NOSTR_PRIVATE_KEY"], "nsec1example");
|
|
assert_eq!(env["BUZZ_RELAY_URL"], "wss://relay.example");
|
|
assert_eq!(env["BUZZ_AUTH_TAG"], "tag-1");
|
|
assert_eq!(env["BUZZ_ACP_AGENT_OWNER"], "beef");
|
|
assert_eq!(env["BUZZ_ACP_AGENT_COMMAND"], "goose");
|
|
assert_eq!(env["BUZZ_ACP_MCP_COMMAND"], "buzz-dev-mcp");
|
|
assert_eq!(env["BUZZ_ACP_EXIT_AFTER_INACTIVITY"], "7200");
|
|
assert_eq!(env["BUZZ_MANAGED_AGENT_START_NONCE"], "gen0001");
|
|
}
|
|
|
|
/// Tier 1 is *overridable* — user env beats policy defaults, matching the
|
|
/// local spawn, where the user layer is written after them. Getting this
|
|
/// backwards would make remote agents ignore overrides local agents honor.
|
|
#[test]
|
|
fn user_env_overrides_policy_defaults() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"launch": {
|
|
"policy_env": {"GOOSE_MODE": "auto", "BUZZ_ACP_MODEL": "sonnet"},
|
|
"env": {"GOOSE_MODE": "chat"},
|
|
"owner_pubkey": "beef"
|
|
}
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
assert_eq!(env["GOOSE_MODE"], "chat");
|
|
assert_eq!(env["BUZZ_ACP_MODEL"], "sonnet");
|
|
}
|
|
|
|
/// `launch.env` already contains the merged user env, so re-merging the
|
|
/// legacy field would undo a layering the desktop already resolved.
|
|
#[test]
|
|
fn legacy_env_vars_are_not_remerged_when_launch_present() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"env_vars": {"STALE": "yes", "SHARED": "legacy"},
|
|
"launch": {"env": {"SHARED": "resolved"}, "owner_pubkey": "beef"}
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
assert_eq!(env["SHARED"], "resolved");
|
|
assert!(!env.contains_key("STALE"), "legacy env_vars re-merged");
|
|
}
|
|
|
|
/// ...but a desktop predating the `launch` block has nothing else to
|
|
/// offer, so the legacy field is the truth in exactly that case.
|
|
#[test]
|
|
fn legacy_env_vars_used_when_launch_absent() {
|
|
let agent = payload_json(serde_json::json!({"env_vars": {"API": "v"}}));
|
|
let env = build(&agent).unwrap();
|
|
assert_eq!(env["API"], "v");
|
|
}
|
|
|
|
#[test]
|
|
fn refuses_when_no_owner_resolves() {
|
|
let agent = payload_json(serde_json::json!({"auth_tag": null}));
|
|
let err = build(&agent).unwrap_err();
|
|
assert!(err.contains("!shutdown"), "unhelpful error: {err}");
|
|
}
|
|
|
|
/// An empty string is not an owner. Without this the refusal is
|
|
/// bypassable by a blank field and the pod launches unable to be stopped.
|
|
#[test]
|
|
fn empty_owner_fields_count_as_absent() {
|
|
for blank in ["", " "] {
|
|
let agent = payload_json(serde_json::json!({
|
|
"auth_tag": blank,
|
|
"launch": {"owner_pubkey": blank}
|
|
}));
|
|
assert!(
|
|
build(&agent).is_err(),
|
|
"whitespace resolved as an owner: {blank:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
/// The other half of every identity guard: what is *stored*. A validator
|
|
/// that trims and a writer that doesn't disagree about the value, and the
|
|
/// padding reaches the harness inside the Secret. Assert on the stored
|
|
/// string — asserting only that the deploy was accepted passes either way.
|
|
#[test]
|
|
fn identity_components_are_stored_trimmed() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"relay_url": " wss://relay.example ",
|
|
"auth_tag": " tag-1 ",
|
|
"launch": {"owner_pubkey": " beefcafe "}
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
assert_eq!(env["BUZZ_RELAY_URL"], "wss://relay.example");
|
|
assert_eq!(env["BUZZ_AUTH_TAG"], "tag-1");
|
|
assert_eq!(env["BUZZ_ACP_AGENT_OWNER"], "beefcafe");
|
|
}
|
|
|
|
/// L1 item 1's third identity component. The nsec arm is enforced in
|
|
/// `naming.rs` and the owner arm above; without this one an agent
|
|
/// deploys with nothing to connect to — a pod that starts, fails at the
|
|
/// relay, and reads as a network fault rather than a refused launch.
|
|
#[test]
|
|
fn refuses_empty_relay_url() {
|
|
for blank in ["", " "] {
|
|
let agent = payload_json(serde_json::json!({"relay_url": blank}));
|
|
let err = build(&agent).unwrap_err();
|
|
assert!(err.contains("relay_url"), "unhelpful error: {err}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn owner_pubkey_alone_is_sufficient() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"auth_tag": null,
|
|
"launch": {"owner_pubkey": "beefcafe"}
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
assert_eq!(env["BUZZ_ACP_AGENT_OWNER"], "beefcafe");
|
|
assert!(!env.contains_key("BUZZ_AUTH_TAG"));
|
|
}
|
|
|
|
#[test]
|
|
fn refuses_presence_suppression() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"launch": {"env": {"BUZZ_ACP_NO_PRESENCE": "1"}, "owner_pubkey": "beef"}
|
|
}));
|
|
let err = build(&agent).unwrap_err();
|
|
assert!(err.contains("BUZZ_ACP_NO_PRESENCE"), "got: {err}");
|
|
}
|
|
|
|
/// `foo.bar` is a legal Secret key but not a legal env name: pre-1.30
|
|
/// kubelets drop it, 1.30+ inject it. Refuse rather than behave
|
|
/// differently depending on the cluster.
|
|
#[test]
|
|
fn refuses_non_posix_env_keys() {
|
|
for bad in ["foo.bar", "foo-bar", "1LEADING", "", "has space"] {
|
|
let agent = payload_json(serde_json::json!({
|
|
"launch": {"env": {bad: "v"}, "owner_pubkey": "beef"}
|
|
}));
|
|
assert!(build(&agent).is_err(), "accepted non-POSIX key {bad:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn args_are_comma_joined_and_omitted_when_empty() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"launch": {"command": "goose", "args": ["run", "--no-session"], "owner_pubkey": "b"}
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
assert_eq!(env["BUZZ_ACP_AGENT_ARGS"], "run,--no-session");
|
|
|
|
let agent = payload_json(serde_json::json!({
|
|
"launch": {"command": "goose", "args": [], "owner_pubkey": "b"}
|
|
}));
|
|
assert!(!build(&agent).unwrap().contains_key("BUZZ_ACP_AGENT_ARGS"));
|
|
}
|
|
|
|
/// The top-level `model`/`provider` fields are display inputs; their
|
|
/// environment consequence is per-runtime and arrives already resolved
|
|
/// inside `launch`. A provider-side mapping is wrong for three of the
|
|
/// four built-in runtimes.
|
|
#[test]
|
|
fn provider_never_maps_model_or_provider_itself() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"model": "claude-opus", "provider": "anthropic",
|
|
"launch": {"owner_pubkey": "beef"}
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
for key in [
|
|
"BUZZ_AGENT_PROVIDER",
|
|
"BUZZ_AGENT_MODEL",
|
|
"GOOSE_PROVIDER",
|
|
"GOOSE_MODEL",
|
|
] {
|
|
assert!(!env.contains_key(key), "provider mapped {key} itself");
|
|
}
|
|
}
|
|
|
|
/// `turn_timeout_seconds` is deprecated and ignored upstream; the local
|
|
/// spawn does not emit it either.
|
|
#[test]
|
|
fn turn_timeout_is_not_mapped() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"turn_timeout_seconds": 30, "launch": {"owner_pubkey": "b"}
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
assert!(!env.keys().any(|k| k.contains("TURN_TIMEOUT")));
|
|
}
|
|
|
|
#[test]
|
|
fn inactivity_omitted_when_unset() {
|
|
let agent = payload_json(serde_json::json!({"launch": {"owner_pubkey": "b"}}));
|
|
let env = build_env(
|
|
&agent,
|
|
AuthoritativeInputs {
|
|
generation: "g",
|
|
inactivity_seconds: None,
|
|
},
|
|
)
|
|
.unwrap();
|
|
assert!(!env.contains_key("BUZZ_ACP_EXIT_AFTER_INACTIVITY"));
|
|
}
|
|
|
|
/// Structural guard over the whole authoritative list at once: whatever
|
|
/// the lower tiers contain, no authoritative key holds a lower-tier value
|
|
/// — including the conditionally-written ones the authoritative tier has
|
|
/// nothing to say about, which must be **absent** rather than spoofed.
|
|
/// This test caught exactly that: `BUZZ_ACP_AGENT_ARGS` is only written
|
|
/// when `launch.args` is non-empty, so plain later-wins overwrite left the
|
|
/// spoofed value in place.
|
|
#[test]
|
|
fn no_authoritative_key_retains_a_lower_tier_value() {
|
|
let spoofed: serde_json::Map<String, serde_json::Value> = AUTHORITATIVE_KEYS
|
|
.iter()
|
|
.map(|k| ((*k).to_string(), serde_json::json!("SPOOFED")))
|
|
.collect();
|
|
// Split across both lower tiers: policy_env and env are separate
|
|
// insertion points, and a fix that only cleared one would pass a
|
|
// single-tier test.
|
|
let agent = payload_json(serde_json::json!({
|
|
"launch": {
|
|
"command": "goose",
|
|
"policy_env": spoofed.clone(),
|
|
"env": spoofed,
|
|
"owner_pubkey": "beef"
|
|
}
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
for key in AUTHORITATIVE_KEYS {
|
|
assert_ne!(
|
|
env.get(*key).map(String::as_str),
|
|
Some("SPOOFED"),
|
|
"{key} kept its lower-tier value"
|
|
);
|
|
}
|
|
// The keys the authoritative tier had no value for are gone, not
|
|
// merely different.
|
|
for absent in [
|
|
"BUZZ_ACP_AGENT_ARGS",
|
|
"BUZZ_ACP_RESPOND_TO",
|
|
"BUZZ_ACP_RESPOND_TO_ALLOWLIST",
|
|
] {
|
|
assert!(!env.contains_key(absent), "{absent} survived the clear");
|
|
}
|
|
}
|
|
|
|
/// A 64-hex pubkey, the only allowlist entry shape the harness accepts.
|
|
fn pubkey(fill: char) -> String {
|
|
std::iter::repeat_n(fill, 64).collect()
|
|
}
|
|
|
|
/// The gate the harness refuses first (`config.rs:996-1004`). Refusing it
|
|
/// here is the difference between one error message and an unbounded
|
|
/// fail-replace loop that leaves a Secret per attempt.
|
|
#[test]
|
|
fn allowlist_mode_with_an_empty_list_is_refused() {
|
|
for empty in [serde_json::json!([]), serde_json::Value::Null] {
|
|
let agent = payload_json(serde_json::json!({
|
|
"respond_to": "allowlist",
|
|
"respond_to_allowlist": empty,
|
|
}));
|
|
let err = build(&agent).unwrap_err();
|
|
assert!(
|
|
err.contains("the allowlist is empty"),
|
|
"unexpected error: {err}"
|
|
);
|
|
}
|
|
}
|
|
|
|
/// `config.rs:629-641` — each entry must be exactly 64 hex characters.
|
|
/// The rejects are the distinct ways to miss that: too short, right length
|
|
/// but not hex, empty, and one character short of valid.
|
|
#[test]
|
|
fn an_allowlist_entry_that_is_not_64_hex_is_refused() {
|
|
for bad in ["abc1234", &"z".repeat(64), "", &pubkey('a')[..63]] {
|
|
let agent = payload_json(serde_json::json!({
|
|
"respond_to": "allowlist",
|
|
"respond_to_allowlist": [pubkey('a'), bad],
|
|
}));
|
|
let err = build(&agent).unwrap_err();
|
|
assert!(
|
|
err.contains("must be exactly 64 hex characters"),
|
|
"{bad:?} was accepted; error was: {err}"
|
|
);
|
|
}
|
|
}
|
|
|
|
/// The positive control: the guard refuses bad gates, not every gate.
|
|
/// Without this, a validator that refused unconditionally would pass both
|
|
/// tests above.
|
|
#[test]
|
|
fn a_valid_allowlist_gate_is_accepted_and_comma_joined() {
|
|
let agent = payload_json(serde_json::json!({
|
|
"respond_to": "allowlist",
|
|
"respond_to_allowlist": [pubkey('a'), pubkey('b')],
|
|
}));
|
|
let env = build(&agent).unwrap();
|
|
assert_eq!(env["BUZZ_ACP_RESPOND_TO"], "allowlist");
|
|
assert_eq!(
|
|
env["BUZZ_ACP_RESPOND_TO_ALLOWLIST"],
|
|
format!("{},{}", pubkey('a'), pubkey('b'))
|
|
);
|
|
}
|
|
|
|
/// The harness validates the allowlist **only** in allowlist mode and
|
|
/// merely warns otherwise (`config.rs:1005-1010`). A stricter provider
|
|
/// would refuse a deploy whose identical local spawn succeeds, so this
|
|
/// pins the asymmetry rather than leaving it to look like an oversight.
|
|
#[test]
|
|
fn a_junk_allowlist_is_tolerated_outside_allowlist_mode() {
|
|
for mode in ["owner-only", "anyone"] {
|
|
let agent = payload_json(serde_json::json!({
|
|
"respond_to": mode,
|
|
"respond_to_allowlist": ["not-a-pubkey"],
|
|
}));
|
|
let env = build(&agent)
|
|
.unwrap_or_else(|e| panic!("{mode} with a stale list must deploy: {e}"));
|
|
assert_eq!(env["BUZZ_ACP_RESPOND_TO"], mode);
|
|
}
|
|
}
|
|
|
|
/// `respond_to` is an opaque `String` on the wire but a `clap::ValueEnum`
|
|
/// at the harness, so an unrecognized mode dies at `rc=2` — before config
|
|
/// parsing runs at all, earlier than either refusal above. Measured
|
|
/// against the built binary: `invalid value 'npub1abc' for '--respond-to'`.
|
|
/// This is the shape our own fixture carried until it was corrected.
|
|
#[test]
|
|
fn a_mode_the_harness_cannot_parse_is_refused() {
|
|
for bad in ["npub1abc", "OWNER-ONLY", "owner_only", "allowlistt", "x"] {
|
|
let agent = payload_json(serde_json::json!({ "respond_to": bad }));
|
|
let err = build(&agent).unwrap_err();
|
|
assert!(
|
|
err.contains("is not a mode the harness accepts"),
|
|
"{bad:?} was accepted; error was: {err}"
|
|
);
|
|
}
|
|
}
|
|
|
|
/// `clap` does not trim its value-enum input, so a padded mode is `rc=2`
|
|
/// even though the same string trimmed is valid. Measured: `invalid value
|
|
/// ' allowlist ' for '--respond-to'`. Trimming here would accept a deploy
|
|
/// the harness refuses — the exact direction this guard exists to prevent.
|
|
#[test]
|
|
fn a_padded_mode_is_refused_because_clap_does_not_trim() {
|
|
for padded in [" allowlist ", "allowlist ", " owner-only", "\tnobody"] {
|
|
let agent = payload_json(serde_json::json!({
|
|
"respond_to": padded,
|
|
"respond_to_allowlist": [pubkey('a')],
|
|
}));
|
|
let err = build(&agent).unwrap_err();
|
|
assert!(
|
|
err.contains("is not a mode the harness accepts"),
|
|
"{padded:?} was accepted; error was: {err}"
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Positive control for the mode check, and the reason it validates the
|
|
/// harness's four rather than the desktop's three: `nobody` is rejected by
|
|
/// `parse_wire` on purpose (`managed_agents/types.rs:871-880`) but starts
|
|
/// fine at the harness. A guard mirroring the desktop enum would refuse a
|
|
/// working launch from a non-desktop caller — the callers this guard is
|
|
/// for. Without this test, refusing `nobody` would pass everything above.
|
|
#[test]
|
|
fn every_mode_the_harness_accepts_is_deployable() {
|
|
for mode in ["owner-only", "allowlist", "anyone", "nobody"] {
|
|
let agent = payload_json(serde_json::json!({
|
|
"respond_to": mode,
|
|
"respond_to_allowlist": [pubkey('a')],
|
|
}));
|
|
let env = build(&agent)
|
|
.unwrap_or_else(|e| panic!("{mode} is valid at the harness but was refused: {e}"));
|
|
assert_eq!(env["BUZZ_ACP_RESPOND_TO"], mode);
|
|
}
|
|
}
|
|
}
|