Watch
0
0
Fork
You've already forked hyperhive
0

swarm: an agent's backend secrets get a store leaf of their own, and its backend environment reads back

The credentials of an agent's backend (ANTHROPIC_API_KEY and the like) move to their own leaf, swarm/agents/<agent>/backend-secrets, written through new PUT, GET and DELETE routes on /api/hives/{hive}/agents/{agent}/backend-secrets. GET says only whether any are stored. The backend environment at backend-env now reads back as stored through GET on its route, so it holds configuration only.

The agent's hive-agent-backend-env unit now runs on every agent with a store, reads both leaves and writes the configuration and then the secrets into the one file the harness and the subagent daemon load, so a secret wins over a variable of the same name. It removes the file when the store holds neither. The harness counts an agent whose environment holds ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN as API-billed, so it tries the key instead of waiting for a Claude login; a real 401 still sets needs-login. The controller's policy may delete the new leaf.

Tests: the secret-client path, the controller routes, the script test of the unit with a stub bao, the module-eval cases and the harness's mode check. Docs: the swarm UI routes, the credentials reference and the API-key provider page.
This commit is contained in:
iris 2026-11-20 20:18:43 +01:00
commit 33fdd5205e

View file

@ -7,11 +7,15 @@
//! whatever the leaf holds, including a value the agent wrote itself while the
//! leaf was empty, and the store's value wins over the agent's
//! `backendEnvironmentFile`.
//!
//! This is the agent's *configuration* (the provider's base URL, a model name),
//! and it reads back as stored. Credentials belong in the write-only
//! [`crate::backend_secrets`] leaf, which the agent's unit loads after this one.
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use swarm_secret_client::backend_env::{self, BackendEnv};
use utoipa::ToSchema;
@ -33,6 +37,55 @@ pub struct PutBackendEnvRequest {
env: String,
}
/// An agent's stored backend environment.
#[derive(Serialize, ToSchema)]
pub struct BackendEnvText {
/// The file text, as stored.
env: String,
}
/// Read an agent's backend environment as stored.
#[utoipa::path(
get,
path = "/api/hives/{hive}/agents/{agent}/backend-env",
params(
("hive" = String, Path, description = "hive the agent runs on"),
("agent" = String, Path, description = "agent the environment belongs to"),
),
responses(
(status = 200, description = "the stored text", body = BackendEnvText),
(status = 400, description = "the agent is not an identifier, or the hive is not in this swarm (problem+json)", body = String),
(status = 404, description = "no backend environment is stored (problem+json)", body = String),
(status = 500, description = "the store could not be read (problem+json)", body = String),
),
tag = "agents"
)]
pub async fn get_backend_env(
State(state): State<AppState>,
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
) -> Result<Json<BackendEnvText>, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let agent = hive_types::Ident::parse(&agent)
.map_err(|reason| error_problem(StatusCode::BAD_REQUEST, reason))?
.into_string();
let path = backend_env::env_path(&agent)
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
let store = state.accounts.open().await.map_err(|e| {
tracing::warn!(error = %e, "connecting to the swarm secret store failed");
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
})?;
let stored = store
.read_optional::<BackendEnv>(&path)
.await
.map_err(|e| {
tracing::warn!(%hive, %agent, error = %e, "reading the backend env failed");
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
})?;
stored
.map(|b| Json(BackendEnvText { env: b.env }))
.ok_or_else(|| error_problem(StatusCode::NOT_FOUND, "no backend environment is stored"))
}
/// Store an agent's backend environment, replacing any stored one.
#[utoipa::path(
put,
@ -84,10 +137,12 @@ pub async fn put_backend_env(
/// The text as it is stored, or why it cannot be.
///
/// Shared with [`crate::backend_secrets`], whose text has the same shape.
///
/// systemd skips a line it cannot parse and goes on, so a typo would load as
/// a missing key. A quote that is not closed would swallow the lines after it
/// into one value. The reasons name a line number and never its text.
fn validated(text: &str) -> Result<String, String> {
pub(crate) fn validated(text: &str) -> Result<String, String> {
let text = text.trim();
if text.is_empty() {
return Err("env is required".to_owned());
@ -132,7 +187,7 @@ fn valid_line(line: &str) -> bool {
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use std::sync::Arc;
use axum::http::StatusCode;
@ -145,7 +200,7 @@ mod tests {
const SECRET: &str = "sk-live-0123";
/// Bare-minimum `AppState`, as `github_account`'s tests build it.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
pub(crate) fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
hives: std::sync::Arc::new(vec![crate::routes::hives::HiveEntry {
name: "pr1ma".to_owned(),
@ -295,4 +350,23 @@ mod tests {
assert_eq!(problem.status, Some(StatusCode::INTERNAL_SERVER_ERROR));
assert!(!format!("{problem:?}").contains(SECRET), "{problem:?}");
}
#[tokio::test]
async fn the_stored_text_reads_back_as_stored_and_nothing_stored_is_a_404() {
let store = Arc::default();
let get = |store: &Arc<FakeStore>| {
super::get_backend_env(
axum::extract::State(state(store)),
axum::extract::Path(("pr1ma".to_owned(), "atlas".to_owned())),
)
};
let problem = get(&store).await.err().expect("nothing stored");
assert_eq!(problem.status, Some(StatusCode::NOT_FOUND));
put(&store, "atlas", "ANTHROPIC_BASE_URL=https://x.example")
.await
.expect("saved");
let read = get(&store).await.expect("read");
assert_eq!(read.0.env, "ANTHROPIC_BASE_URL=https://x.example\n");
}
}