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:
parent
c9204ad0e0
commit
33fdd5205e
1 changed files with 737 additions and 107 deletions
224
swarm-controller/src/backend_secrets.rs
Normal file
224
swarm-controller/src/backend_secrets.rs
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
//! An agent's backend secrets: an operator hands us the text of a systemd
|
||||
//! `EnvironmentFile` that holds credentials (`ANTHROPIC_API_KEY=…`), and we put
|
||||
//! it in a leaf of its own in the swarm's secret store, apart from the
|
||||
//! configuration in [`crate::backend_env`].
|
||||
//!
|
||||
//! The agent end is `nix/agent-modules/backend-env.nix`, which reads both under
|
||||
//! the agent's own certificate into the file its harness loads as
|
||||
//! `EnvironmentFile=`, the configuration first and these secrets after it. An
|
||||
//! agent whose environment then holds `ANTHROPIC_API_KEY` bills the API and
|
||||
//! tries it instead of waiting for a Claude login. No route hands the text
|
||||
//! back; [`get_backend_secrets`] says only whether the leaf holds any.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_secret_client::backend_secrets::{self, BackendSecrets};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use super::linked_accounts::AccountStore;
|
||||
use crate::backend_env::validated;
|
||||
use crate::routes::agents::swarm_hive;
|
||||
use crate::routes::{AppState, error_problem};
|
||||
|
||||
/// The secrets to store for one agent.
|
||||
///
|
||||
/// No `Debug` derive: this carries live credentials.
|
||||
#[derive(Deserialize, ToSchema)]
|
||||
pub struct PutBackendSecretsRequest {
|
||||
/// The file text, `NAME=VALUE` per line, as for the backend environment.
|
||||
/// Never logged, and never returned by any route.
|
||||
env: String,
|
||||
}
|
||||
|
||||
/// Whether an agent has backend secrets stored.
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct BackendSecretsStatus {
|
||||
/// `true` when the leaf holds text; the text is never returned.
|
||||
stored: bool,
|
||||
}
|
||||
|
||||
/// Whether an agent has backend secrets stored.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/hives/{hive}/agents/{agent}/backend-secrets",
|
||||
params(
|
||||
("hive" = String, Path, description = "hive the agent runs on"),
|
||||
("agent" = String, Path, description = "agent the secrets belong to"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "whether secrets are stored; never the secrets", body = BackendSecretsStatus),
|
||||
(status = 400, description = "the agent is not an identifier, or the hive is not in this swarm (problem+json)", body = String),
|
||||
(status = 500, description = "the store could not be read (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub async fn get_backend_secrets(
|
||||
State(state): State<AppState>,
|
||||
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
|
||||
) -> Result<Json<BackendSecretsStatus>, 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_secrets::secrets_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::<BackendSecrets>(&path)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(%hive, %agent, error = %e, "reading the backend secrets failed");
|
||||
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
})?;
|
||||
Ok(Json(BackendSecretsStatus {
|
||||
stored: stored.is_some_and(|s| !s.env.trim().is_empty()),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Store an agent's backend secrets, replacing any stored ones.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/hives/{hive}/agents/{agent}/backend-secrets",
|
||||
params(
|
||||
("hive" = String, Path, description = "hive the agent runs on"),
|
||||
("agent" = String, Path, description = "agent the secrets belong to"),
|
||||
),
|
||||
request_body = PutBackendSecretsRequest,
|
||||
responses(
|
||||
(status = 204, description = "stored"),
|
||||
(status = 400, description = "the agent is not an identifier, the text is empty, too large or not `NAME=VALUE` lines, or the hive is not in this swarm (problem+json)", body = String),
|
||||
(status = 500, description = "the store could not be written (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub async fn put_backend_secrets(
|
||||
State(state): State<AppState>,
|
||||
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
|
||||
Json(req): Json<PutBackendSecretsRequest>,
|
||||
) -> Result<StatusCode, 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_secrets::secrets_path(&agent)
|
||||
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
|
||||
let stored = BackendSecrets {
|
||||
env: validated(&req.env).map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e))?,
|
||||
};
|
||||
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())
|
||||
})?;
|
||||
store.write(&path, &stored).await.map_err(|e| {
|
||||
// The path names the agent; the value is not in it.
|
||||
tracing::warn!(%path, error = %e, "storing the backend secrets failed");
|
||||
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
})?;
|
||||
tracing::info!(%hive, %agent, "backend secrets stored");
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
use swarm_secret_client::backend_secrets::BackendSecrets;
|
||||
|
||||
use super::super::backend_env::tests::state;
|
||||
use super::super::linked_accounts::{AccountStore, tests::FakeStore};
|
||||
use super::PutBackendSecretsRequest;
|
||||
|
||||
const SECRET: &str = "sk-ant-live-0123";
|
||||
|
||||
async fn put(
|
||||
store: &Arc<FakeStore>,
|
||||
agent: &str,
|
||||
env: &str,
|
||||
) -> Result<StatusCode, problem_details::ProblemDetails> {
|
||||
super::put_backend_secrets(
|
||||
axum::extract::State(state(store)),
|
||||
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned())),
|
||||
axum::Json(PutBackendSecretsRequest {
|
||||
env: env.to_owned(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn stored(store: &FakeStore, agent: &str) -> Option<String> {
|
||||
store
|
||||
.read_optional::<BackendSecrets>(&format!("swarm/agents/{agent}/backend-secrets"))
|
||||
.await
|
||||
.expect("store answers")
|
||||
.map(|s| s.env)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn secrets_are_stored_under_the_agent_and_replace_earlier_ones() {
|
||||
let store = Arc::new(FakeStore::default().with(
|
||||
"swarm/agents/atlas/backend-secrets",
|
||||
json!({"env": "OLD=1\n"}),
|
||||
));
|
||||
let status = put(&store, "atlas", &format!("ANTHROPIC_API_KEY={SECRET}"))
|
||||
.await
|
||||
.expect("stored");
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(store.written(), ["swarm/agents/atlas/backend-secrets"]);
|
||||
assert_eq!(
|
||||
stored(&store, "atlas").await.as_deref(),
|
||||
Some("ANTHROPIC_API_KEY=sk-ant-live-0123\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bad_agent_or_text_is_refused_before_the_store_and_never_echoed() {
|
||||
let store = Arc::default();
|
||||
let leaky = format!("{SECRET}-no-equals");
|
||||
for (agent, env) in [
|
||||
("Atlas", "A=1"),
|
||||
("../x", "A=1"),
|
||||
("atlas", " "),
|
||||
("atlas", leaky.as_str()),
|
||||
] {
|
||||
let problem = put(&store, agent, env).await.expect_err("refused");
|
||||
assert_eq!(problem.status, Some(StatusCode::BAD_REQUEST), "{problem:?}");
|
||||
assert!(!format!("{problem:?}").contains(SECRET), "{problem:?}");
|
||||
}
|
||||
assert!(store.written().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_store_failure_does_not_echo_the_secrets() {
|
||||
let store = Arc::new(FakeStore::denying());
|
||||
let problem = put(&store, "atlas", &format!("ANTHROPIC_API_KEY={SECRET}"))
|
||||
.await
|
||||
.expect_err("refused");
|
||||
assert_eq!(problem.status, Some(StatusCode::INTERNAL_SERVER_ERROR));
|
||||
assert!(!format!("{problem:?}").contains(SECRET), "{problem:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_status_says_whether_secrets_are_stored_and_never_what_they_are() {
|
||||
let store = Arc::new(FakeStore::default().with(
|
||||
"swarm/agents/atlas/backend-secrets",
|
||||
json!({"env": format!("ANTHROPIC_API_KEY={SECRET}\n")}),
|
||||
));
|
||||
for (agent, want) in [("atlas", true), ("red", false)] {
|
||||
let got = super::get_backend_secrets(
|
||||
axum::extract::State(state(&store)),
|
||||
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned())),
|
||||
)
|
||||
.await
|
||||
.expect("answers");
|
||||
assert_eq!(got.0.stored, want, "{agent}");
|
||||
assert!(!format!("{got:?}").contains(SECRET));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue