Watch
0
0
Fork
You've already forked hyperhive
0

swarm-controller: accounts handlers take their own sub-state via FromRef

This commit is contained in:
atlas 2026-11-28 01:36:20 +01:00 • committed by mara
commit 5e81895a3b
9 changed files with 147 additions and 77 deletions

View file

@ -12,9 +12,9 @@ use serde::{Deserialize, Serialize};
use swarm_secret_client::forge;
use utoipa::ToSchema;
use super::AccountsState;
use super::linked_accounts::link;
use crate::routes::agents::swarm_hive;
use crate::routes::{AppState, error_problem};
use crate::routes::error_problem;
/// The account to store for one agent's external forge.
///
@ -56,11 +56,11 @@ pub struct PutForgeAccountResponse {
tag = "agents"
)]
pub async fn put_forge_account(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>,
Json(req): Json<PutForgeAccountRequest>,
) -> Result<Json<PutForgeAccountResponse>, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -150,12 +150,9 @@ mod tests {
assert!(account(request("https://forge.example.org", " ")).is_err());
}
/// Bare-minimum `AppState`, as `matrix_account`'s tests build it.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
accounts: Accounts::Fake(Arc::clone(store)),
..crate::routes::AppState::for_test()
}
/// A handler test's state: one hive, no queue, `store` as the account store.
fn state(store: &Arc<FakeStore>) -> crate::accounts::AccountsState {
crate::accounts::AccountsState::for_test(Accounts::Fake(Arc::clone(store)))
}
async fn put(

View file

@ -12,9 +12,9 @@ use serde::Deserialize;
use swarm_secret_client::github;
use utoipa::ToSchema;
use super::AccountsState;
use super::linked_accounts::link;
use crate::routes::agents::swarm_hive;
use crate::routes::{AppState, error_problem};
use crate::routes::error_problem;
/// The token to store for one agent.
///
@ -44,11 +44,11 @@ pub struct PutGithubAccountRequest {
tag = "agents"
)]
pub async fn put_github_account(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
Json(req): Json<PutGithubAccountRequest>,
) -> Result<StatusCode, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -112,12 +112,9 @@ mod tests {
assert!(credential(&request("")).is_err());
}
/// Bare-minimum `AppState`, as `forge_account`'s tests build it.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
accounts: Accounts::Fake(Arc::clone(store)),
..crate::routes::AppState::for_test()
}
/// A handler test's state: one hive, no queue, `store` as the account store.
fn state(store: &Arc<FakeStore>) -> crate::accounts::AccountsState {
crate::accounts::AccountsState::for_test(Accounts::Fake(Arc::clone(store)))
}
async fn put(

View file

@ -12,10 +12,10 @@ use serde::{Deserialize, Serialize};
use swarm_secret_client::gitlab;
use utoipa::ToSchema;
use super::AccountsState;
use super::linked_accounts::link;
use crate::backend_egress::host_of;
use crate::routes::agents::swarm_hive;
use crate::routes::{AppState, error_problem};
use crate::routes::error_problem;
/// The account to store for one agent's GitLab instance.
///
@ -58,11 +58,11 @@ pub struct PutGitlabAccountResponse {
tag = "agents"
)]
pub async fn put_gitlab_account(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>,
Json(req): Json<PutGitlabAccountRequest>,
) -> Result<Json<PutGitlabAccountResponse>, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -203,12 +203,9 @@ mod tests {
assert!(account(request("https://gitlab.example.org", " ")).is_err());
}
/// Bare-minimum `AppState`, as `forge_account`'s tests build it.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
accounts: Accounts::Fake(Arc::clone(store)),
..crate::routes::AppState::for_test()
}
/// A handler test's state: one hive, no queue, `store` as the account store.
fn state(store: &Arc<FakeStore>) -> crate::accounts::AccountsState {
crate::accounts::AccountsState::for_test(Accounts::Fake(Arc::clone(store)))
}
async fn put(

View file

@ -30,11 +30,11 @@ use std::collections::{BTreeMap, BTreeSet};
use problem_details::ProblemDetails;
use swarm_wire::egress_allow::{AllowList, Entry, LINK_SOURCE_PREFIX, MAX_ENTRIES};
use super::AccountsState;
use crate::backend_egress::host_of;
use crate::egress_allow::{base_domains, checked, current, modify};
use crate::linked_accounts::{AccountKind, AccountStore, linked_accounts};
use crate::routes::{AppState, error_problem, wanted_error_status};
use crate::schedules::queue;
use crate::routes::{error_problem, wanted_error_status};
/// What the GitHub token is used against: `gh`'s API, git over HTTPS, and the
/// raw file, archive and release-asset downloads.
@ -151,7 +151,7 @@ fn is_of(e: &Entry, agent: &str, source: &str) -> bool {
/// Replace `agent`'s entries of `source` with `entries`. A host without a
/// queue (`state.status` unset) has no allow list, so nothing happens.
async fn follow(
state: &AppState,
state: &AccountsState,
agent: &str,
source: &str,
entries: Vec<Entry>,
@ -161,7 +161,7 @@ async fn follow(
return Ok(());
}
let updated = async {
let client = queue(state).map_err(|(_, why)| anyhow::anyhow!(why))?;
let client = state.queue().map_err(|(_, why)| anyhow::anyhow!(why))?;
modify(&client, |list| {
replaced(list, |e| is_of(e, agent, source), &entries)
})
@ -190,7 +190,7 @@ async fn follow(
/// # Errors
/// A problem naming that the account is linked but the list was not updated.
pub(crate) async fn added(
state: &AppState,
state: &AccountsState,
agent: &str,
link: &Link<'_>,
) -> Result<(), ProblemDetails> {
@ -204,7 +204,7 @@ pub(crate) async fn added(
/// # Errors
/// A problem naming that the account is deleted but the list was not updated.
pub(crate) async fn removed(
state: &AppState,
state: &AccountsState,
agent: &str,
source: &str,
) -> Result<(), ProblemDetails> {
@ -320,7 +320,9 @@ mod tests {
use super::*;
use crate::agent_limits::tests::declared;
use crate::linked_accounts::tests::FakeStore;
use crate::routes::AppState;
use crate::test_nats::TestNats;
use axum::extract::FromRef as _;
fn base() -> Vec<String> {
vec!["api.anthropic.com".to_owned()]
@ -508,6 +510,11 @@ mod tests {
.collect()
}
/// The accounts handlers' view of `state`.
fn acc(state: &AppState) -> AccountsState {
AccountsState::from_ref(state)
}
fn path(parts: &str) -> Path<(String, String)> {
Path(("pr1ma".to_owned(), parts.to_owned()))
}
@ -515,7 +522,7 @@ mod tests {
/// Link `atlas`'s GitLab account `work` through the route.
async fn link_gitlab(state: &AppState) {
let _ = crate::gitlab_account::put_gitlab_account(
State(state.clone()),
State(acc(state)),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "work".to_owned())),
axum::Json(
serde_json::from_value(
@ -536,14 +543,14 @@ mod tests {
let state = swarm(&client, &store).await;
let _ = crate::github_account::put_github_account(
State(state.clone()),
State(acc(&state)),
path("atlas"),
axum::Json(serde_json::from_value(json!({"token": "t"})).expect("a body")),
)
.await
.expect("linked");
let _ = crate::forge_account::put_forge_account(
State(state.clone()),
State(acc(&state)),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "oss".to_owned())),
axum::Json(
serde_json::from_value(
@ -556,7 +563,7 @@ mod tests {
.expect("linked");
link_gitlab(&state).await;
let _ = crate::matrix_account::put_matrix_account(
State(state.clone()),
State(acc(&state)),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "work".to_owned())),
axum::Json(
serde_json::from_value(json!({
@ -592,7 +599,7 @@ mod tests {
.expect("deleted");
assert_eq!(list_of(&client).await.len(), 3 + GITHUB_HOSTS.len());
crate::linked_accounts::delete_github_account(State(state.clone()), path("atlas"))
crate::linked_accounts::delete_github_account(State(acc(&state)), path("atlas"))
.await
.expect("deleted");
assert_eq!(
@ -600,7 +607,7 @@ mod tests {
sorted(vec![forge.clone(), gitlab.clone(), matrix.clone()])
);
crate::linked_accounts::delete_forge_account(
State(state.clone()),
State(acc(&state)),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "oss".to_owned())),
)
.await
@ -610,14 +617,14 @@ mod tests {
sorted(vec![gitlab.clone(), matrix.clone()])
);
crate::linked_accounts::delete_gitlab_account(
State(state.clone()),
State(acc(&state)),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "work".to_owned())),
)
.await
.expect("deleted");
assert_eq!(list_of(&client).await, [matrix]);
crate::linked_accounts::delete_matrix_account(
State(state.clone()),
State(acc(&state)),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "work".to_owned())),
axum::extract::Query(serde_json::from_value(json!({})).expect("a query")),
)

View file

@ -39,6 +39,7 @@ use swarm_secret_client::{
};
use utoipa::{IntoParams, ToSchema};
use super::AccountsState;
use crate::routes::agents::swarm_hive;
use crate::routes::{AppState, error_problem};
@ -292,10 +293,10 @@ pub(crate) async fn linked_accounts(
tag = "agents"
)]
pub async fn get_linked_accounts(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
) -> Result<Json<Vec<LinkedAccount>>, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -525,11 +526,11 @@ pub struct DeleteMatrixAccountQuery {
tag = "agents"
)]
pub async fn delete_matrix_account(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent, account)): axum::extract::Path<(String, String, String)>,
axum::extract::Query(query): axum::extract::Query<DeleteMatrixAccountQuery>,
) -> Result<StatusCode, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -594,10 +595,10 @@ pub async fn delete_matrix_account(
tag = "agents"
)]
pub async fn delete_forge_account(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>,
) -> Result<StatusCode, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -641,10 +642,10 @@ pub async fn delete_forge_account(
tag = "agents"
)]
pub async fn delete_gitlab_account(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>,
) -> Result<StatusCode, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -687,10 +688,10 @@ pub async fn delete_gitlab_account(
tag = "agents"
)]
pub async fn delete_github_account(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
) -> Result<StatusCode, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -774,10 +775,10 @@ pub async fn delete_backend_env(
tag = "agents"
)]
pub async fn delete_backend_secrets(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
) -> Result<StatusCode, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -1228,12 +1229,9 @@ pub(crate) mod tests {
assert!(store.written().is_empty());
}
/// Bare-minimum `AppState`, as `matrix_account`'s tests build it.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
accounts: super::Accounts::Fake(Arc::clone(store)),
..crate::routes::AppState::for_test()
}
/// A handler test's state: one hive, no queue, `store` as the account store.
fn state(store: &Arc<FakeStore>) -> crate::accounts::AccountsState {
crate::accounts::AccountsState::for_test(super::Accounts::Fake(Arc::clone(store)))
}
async fn delete_matrix(
@ -1280,7 +1278,10 @@ pub(crate) mod tests {
agent: &str,
) -> Result<axum::http::StatusCode, problem_details::ProblemDetails> {
super::delete_backend_env(
axum::extract::State(state(store)),
axum::extract::State(crate::routes::AppState {
accounts: super::Accounts::Fake(Arc::clone(store)),
..crate::routes::AppState::for_test()
}),
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned())),
)
.await

View file

@ -32,9 +32,9 @@ use serde::{Deserialize, Serialize};
use swarm_secret_client::matrix;
use utoipa::ToSchema;
use super::AccountsState;
use super::linked_accounts::{AccountStore, Linking, link, refuse_linked};
use crate::routes::agents::swarm_hive;
use crate::routes::{AppState, error_problem};
use crate::routes::error_problem;
pub mod agent_token;
pub mod operator_admin;
@ -143,11 +143,11 @@ pub struct PutMatrixAccountResponse {
tag = "agents"
)]
pub async fn put_matrix_account(
State(state): State<AppState>,
State(state): State<AccountsState>,
axum::extract::Path((hive, agent, account)): axum::extract::Path<(String, String, String)>,
Json(req): Json<PutMatrixAccountRequest>,
) -> Result<Json<PutMatrixAccountResponse>, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let hive = state.hive(&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();
@ -450,14 +450,9 @@ mod tests {
);
}
/// Bare-minimum `AppState` for a handler test: one hive, nothing
/// queue-backed, an empty in-memory job graph the endpoint under test
/// never touches, and `store` as the account store.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
accounts: Accounts::Fake(Arc::clone(store)),
..crate::routes::AppState::for_test()
}
/// A handler test's state: one hive, no queue, `store` as the account store.
fn state(store: &Arc<FakeStore>) -> crate::accounts::AccountsState {
crate::accounts::AccountsState::for_test(Accounts::Fake(Arc::clone(store)))
}
/// Refused before the store is reached.

View file

@ -7,3 +7,64 @@ pub(crate) mod gitlab_account;
pub(crate) mod link_egress;
pub(crate) mod linked_accounts;
pub(crate) mod matrix_account;
use std::sync::Arc;
use axum::extract::FromRef;
use crate::routes::AppState;
use crate::routes::hives::HiveEntry;
use crate::status::StatusReader;
/// What the accounts handlers may reach of [`AppState`]: the secret store,
/// the hive list to validate a hive name against, and the queue reader whose
/// connection carries the egress allow list.
///
/// Derived per request from [`AppState`] (`FromRef`), so each field is a clone
/// of the same `Arc` or cheap handle and nothing is held twice.
#[derive(Clone)]
pub(crate) struct AccountsState {
pub(crate) accounts: linked_accounts::Accounts,
pub(crate) hives: Arc<Vec<HiveEntry>>,
pub(crate) status: Option<Arc<StatusReader>>,
}
impl FromRef<AppState> for AccountsState {
fn from_ref(state: &AppState) -> Self {
Self {
accounts: state.accounts.clone(),
hives: Arc::clone(&state.hives),
status: state.status.clone(),
}
}
}
impl AccountsState {
/// The hive name `hive` names, or the status and detail refusing it.
///
/// # Errors
/// A 400 when it is not shaped like a hive name or names no hive here.
pub(crate) fn hive(&self, hive: &str) -> Result<String, (axum::http::StatusCode, String)> {
crate::routes::agents::hive_in(&self.hives, hive)
}
/// The connected queue client, or the problem.
///
/// # Errors
/// A 503 when no queue is configured or it is not connected.
pub(crate) fn queue(&self) -> Result<async_nats::Client, (axum::http::StatusCode, String)> {
crate::schedules::queue_of(self.status.as_ref())
}
}
#[cfg(test)]
impl AccountsState {
/// A handler test's state: the one hive `pr1ma`, no queue, and `accounts`
/// as the store.
pub(crate) fn for_test(accounts: linked_accounts::Accounts) -> Self {
Self {
accounts,
..Self::from_ref(&AppState::for_test())
}
}
}

View file

@ -100,6 +100,14 @@ pub(crate) fn render(declaration: &swarm_wire::wanted::HiveWanted) -> Vec<AgentD
pub(crate) fn swarm_hive(
state: &AppState,
hive: &str,
) -> Result<String, (axum::http::StatusCode, String)> {
hive_in(&state.hives, hive)
}
/// [`swarm_hive`] over the hive list alone, for a caller that holds only that.
pub(crate) fn hive_in(
hives: &[crate::routes::hives::HiveEntry],
hive: &str,
) -> Result<String, (axum::http::StatusCode, String)> {
let hive = hive_types::Ident::parse(hive)
.map_err(|reason| (axum::http::StatusCode::BAD_REQUEST, reason.to_owned()))?
@ -107,7 +115,7 @@ pub(crate) fn swarm_hive(
// Shaped like a hive name, and actually one. Same two checks
// `create_agent` makes, for the same reason: a typo otherwise publishes a
// declaration under a key no hive will ever read.
if !state.hives.iter().any(|h| h.name == hive) {
if !hives.iter().any(|h| h.name == hive) {
return Err((
axum::http::StatusCode::BAD_REQUEST,
format!("{hive:?} is not a hive in this swarm"),

View file

@ -628,7 +628,14 @@ pub(crate) fn spawn_reconcile(
/// The connected queue client, or the problem.
pub(crate) fn queue(state: &AppState) -> Result<async_nats::Client, (StatusCode, String)> {
let status = state.status.as_ref().ok_or_else(|| {
queue_of(state.status.as_ref())
}
/// [`queue`] over the status reader alone, for a caller that holds only that.
pub(crate) fn queue_of(
status: Option<&Arc<crate::status::StatusReader>>,
) -> Result<async_nats::Client, (StatusCode, String)> {
let status = status.ok_or_else(|| {
(
StatusCode::SERVICE_UNAVAILABLE,
"no swarm queue is configured on this host".to_owned(),