From 5e81895a3be53f7d3e93efc85bdcda383fc7e57e Mon Sep 17 00:00:00 2001 From: atlas Date: Sat, 28 Nov 2026 01:36:20 +0100 Subject: [PATCH] swarm-controller: accounts handlers take their own sub-state via FromRef --- .../src/accounts/forge_account.rs | 17 +++--- .../src/accounts/github_account.rs | 17 +++--- .../src/accounts/gitlab_account.rs | 17 +++--- swarm-controller/src/accounts/link_egress.rs | 35 ++++++----- .../src/accounts/linked_accounts.rs | 39 ++++++------ .../src/accounts/matrix_account.rs | 19 +++--- swarm-controller/src/accounts/mod.rs | 61 +++++++++++++++++++ swarm-controller/src/agents/routes.rs | 10 ++- swarm-controller/src/agents/schedules.rs | 9 ++- 9 files changed, 147 insertions(+), 77 deletions(-) diff --git a/swarm-controller/src/accounts/forge_account.rs b/swarm-controller/src/accounts/forge_account.rs index 7a88418c9..34184b194 100644 --- a/swarm-controller/src/accounts/forge_account.rs +++ b/swarm-controller/src/accounts/forge_account.rs @@ -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, + State(state): State, axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>, Json(req): Json, ) -> Result, 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) -> 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) -> crate::accounts::AccountsState { + crate::accounts::AccountsState::for_test(Accounts::Fake(Arc::clone(store))) } async fn put( diff --git a/swarm-controller/src/accounts/github_account.rs b/swarm-controller/src/accounts/github_account.rs index b7aaeb0a0..f09846e2d 100644 --- a/swarm-controller/src/accounts/github_account.rs +++ b/swarm-controller/src/accounts/github_account.rs @@ -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, + State(state): State, axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>, Json(req): Json, ) -> Result { - 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) -> 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) -> crate::accounts::AccountsState { + crate::accounts::AccountsState::for_test(Accounts::Fake(Arc::clone(store))) } async fn put( diff --git a/swarm-controller/src/accounts/gitlab_account.rs b/swarm-controller/src/accounts/gitlab_account.rs index 2f29ca7b7..54022177d 100644 --- a/swarm-controller/src/accounts/gitlab_account.rs +++ b/swarm-controller/src/accounts/gitlab_account.rs @@ -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, + State(state): State, axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>, Json(req): Json, ) -> Result, 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) -> 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) -> crate::accounts::AccountsState { + crate::accounts::AccountsState::for_test(Accounts::Fake(Arc::clone(store))) } async fn put( diff --git a/swarm-controller/src/accounts/link_egress.rs b/swarm-controller/src/accounts/link_egress.rs index cc923cbdd..b653e475c 100644 --- a/swarm-controller/src/accounts/link_egress.rs +++ b/swarm-controller/src/accounts/link_egress.rs @@ -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, @@ -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 { 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")), ) diff --git a/swarm-controller/src/accounts/linked_accounts.rs b/swarm-controller/src/accounts/linked_accounts.rs index a59cc7b84..4142ed081 100644 --- a/swarm-controller/src/accounts/linked_accounts.rs +++ b/swarm-controller/src/accounts/linked_accounts.rs @@ -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, + State(state): State, axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>, ) -> Result>, 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, + State(state): State, axum::extract::Path((hive, agent, account)): axum::extract::Path<(String, String, String)>, axum::extract::Query(query): axum::extract::Query, ) -> Result { - 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, + State(state): State, axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>, ) -> Result { - 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, + State(state): State, axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>, ) -> Result { - 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, + State(state): State, axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>, ) -> Result { - 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, + State(state): State, axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>, ) -> Result { - 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) -> 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) -> 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 { 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 diff --git a/swarm-controller/src/accounts/matrix_account.rs b/swarm-controller/src/accounts/matrix_account.rs index ea2d3a8d9..6705caa33 100644 --- a/swarm-controller/src/accounts/matrix_account.rs +++ b/swarm-controller/src/accounts/matrix_account.rs @@ -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, + State(state): State, axum::extract::Path((hive, agent, account)): axum::extract::Path<(String, String, String)>, Json(req): Json, ) -> Result, 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) -> 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) -> crate::accounts::AccountsState { + crate::accounts::AccountsState::for_test(Accounts::Fake(Arc::clone(store))) } /// Refused before the store is reached. diff --git a/swarm-controller/src/accounts/mod.rs b/swarm-controller/src/accounts/mod.rs index 2c349b7a0..1e0a5cf65 100644 --- a/swarm-controller/src/accounts/mod.rs +++ b/swarm-controller/src/accounts/mod.rs @@ -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>, + pub(crate) status: Option>, +} + +impl FromRef 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 { + 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 { + 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()) + } + } +} diff --git a/swarm-controller/src/agents/routes.rs b/swarm-controller/src/agents/routes.rs index 8fa5e4334..8f4a0e7a6 100644 --- a/swarm-controller/src/agents/routes.rs +++ b/swarm-controller/src/agents/routes.rs @@ -100,6 +100,14 @@ pub(crate) fn render(declaration: &swarm_wire::wanted::HiveWanted) -> Vec Result { + 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 { 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"), diff --git a/swarm-controller/src/agents/schedules.rs b/swarm-controller/src/agents/schedules.rs index 94daf218e..3841ba2b9 100644 --- a/swarm-controller/src/agents/schedules.rs +++ b/swarm-controller/src/agents/schedules.rs @@ -628,7 +628,14 @@ pub(crate) fn spawn_reconcile( /// The connected queue client, or the problem. pub(crate) fn queue(state: &AppState) -> Result { - 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>, +) -> Result { + let status = status.ok_or_else(|| { ( StatusCode::SERVICE_UNAVAILABLE, "no swarm queue is configured on this host".to_owned(),