no behaviour change: a pure move of items and tests into new modules, plus visibility edits (pub(crate)) and path updates in sibling modules that named crate-root items. same routes, same OpenAPI, 561 tests before and after. why: #5470, new features stop landing in one 6.4k-line file by default. files outside swarm-controller/src: docs/agent-lifecycle/agent-roster.md, swarm-ui JobsPage.tsx and AgentsPage.tsx, nix/host-modules/swarm-controller.nix and swarm-grafana.nix hold comments that named main.rs for items that moved.
236 lines
9.1 KiB
Rust
236 lines
9.1 KiB
Rust
//! Forge site admins and an agent's forge token, on request.
|
|
|
|
use anyhow::Result;
|
|
use axum::{
|
|
Json,
|
|
extract::{Path, State},
|
|
};
|
|
use swarm_controller_api::agents::MintAgentForgeTokenResponse;
|
|
use swarm_controller_api::forge::{ForgeAdminChange, MakeForgeAdminResponse};
|
|
|
|
use crate::forge;
|
|
use crate::jobq::queue_forge_token_mints;
|
|
use crate::routes::agents::in_roster;
|
|
use crate::routes::{AppState, error_problem};
|
|
|
|
/// Check an agent's forge token now, and mint one if it is missing or stale.
|
|
///
|
|
/// The periodic pass (`forge::agent_token::spawn`) does the same every five
|
|
/// minutes for every agent with a store identity; this is for an operator who
|
|
/// does not want to wait, or for an agent the pass skipped. Queues the same
|
|
/// node agent creation does. Idempotent: a current token is left alone.
|
|
#[utoipa::path(
|
|
post,
|
|
path = "/api/agents/{name}/forge-token",
|
|
params(("name" = String, Path, description = "agent name")),
|
|
responses(
|
|
(status = 200, description = "mint queued", body = MintAgentForgeTokenResponse),
|
|
(status = 400, description = "`name` is not a valid identifier (problem+json)", body = String),
|
|
(status = 500, description = "the job could not be queued (problem+json)", body = String),
|
|
),
|
|
tag = "agents"
|
|
)]
|
|
pub(crate) async fn mint_agent_forge_token(
|
|
State(state): State<AppState>,
|
|
Path(name): Path<String>,
|
|
) -> Result<Json<MintAgentForgeTokenResponse>, problem_details::ProblemDetails> {
|
|
let agent = hive_types::Ident::parse(&name)
|
|
.map_err(|reason| error_problem(axum::http::StatusCode::BAD_REQUEST, reason))?
|
|
.into_string();
|
|
let ids = queue_forge_token_mints(&state.jobq, vec![agent]).map_err(|e| {
|
|
error_problem(
|
|
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
|
&e.to_string(),
|
|
)
|
|
})?;
|
|
let [id] = ids[..] else {
|
|
unreachable!("exactly one handle was asked for");
|
|
};
|
|
Ok(Json(MintAgentForgeTokenResponse { node_id: id.get() }))
|
|
}
|
|
|
|
/// Make an existing human forge account a site admin. Idempotent.
|
|
///
|
|
/// Never creates the account: a human's is made by their first SSO login to
|
|
/// the forge, and until then this answers 404. Refuses an agent's name: a
|
|
/// site admin can create repos whatever its `max_repo_creation`, and an
|
|
/// agent's account is locked to 0 so its token cannot create a repo and
|
|
/// self-merge in it.
|
|
#[utoipa::path(
|
|
post,
|
|
path = "/api/forge/users/{name}/admin",
|
|
params(("name" = String, Path, description = "forge username")),
|
|
responses(
|
|
(status = 200, description = "the account is a site admin", body = MakeForgeAdminResponse),
|
|
(status = 400, description = "`name` is not a valid identifier (problem+json)", body = String),
|
|
(status = 404, description = "no such account: the user has not logged in via SSO yet (problem+json)", body = String),
|
|
(status = 409, description = "`name` is an agent (problem+json)", body = String),
|
|
(status = 500, description = "the forge refused the read or the edit (problem+json)", body = String),
|
|
(status = 503, description = "no forge configured, or the agent roster could not be read (problem+json)", body = String),
|
|
),
|
|
tag = "forge"
|
|
)]
|
|
pub(crate) async fn make_forge_admin(
|
|
State(state): State<AppState>,
|
|
Path(name): Path<String>,
|
|
) -> Result<Json<MakeForgeAdminResponse>, problem_details::ProblemDetails> {
|
|
let name = hive_types::Ident::parse(&name)
|
|
.map_err(|reason| error_problem(axum::http::StatusCode::BAD_REQUEST, reason))?
|
|
.into_string();
|
|
let Some(forge) = state.forge.get().cloned() else {
|
|
return Err(error_problem(
|
|
axum::http::StatusCode::SERVICE_UNAVAILABLE,
|
|
"no forge is configured on this host",
|
|
));
|
|
};
|
|
let is_agent = in_roster(state.auth.as_deref(), &name).await;
|
|
admin_unless_agent(&name, is_agent, || async {
|
|
forge.make_site_admin(&name).await
|
|
})
|
|
.await
|
|
}
|
|
|
|
/// Run `promote` only if `name` is known not to be an agent, and answer with
|
|
/// what it found.
|
|
///
|
|
/// An unreadable roster refuses too: a site admin is the one thing an agent's
|
|
/// account must never become, so "could not tell" is not "no".
|
|
pub(crate) async fn admin_unless_agent<F, Fut>(
|
|
name: &str,
|
|
is_agent: Result<bool, String>,
|
|
promote: F,
|
|
) -> Result<Json<MakeForgeAdminResponse>, problem_details::ProblemDetails>
|
|
where
|
|
F: FnOnce() -> Fut,
|
|
Fut: std::future::Future<Output = Result<forge::site_admin::Plan>>,
|
|
{
|
|
match is_agent {
|
|
Ok(false) => {}
|
|
Ok(true) => {
|
|
return Err(error_problem(
|
|
axum::http::StatusCode::CONFLICT,
|
|
&format!("{name:?} is an agent; an agent's forge account is never a site admin"),
|
|
));
|
|
}
|
|
Err(e) => {
|
|
return Err(error_problem(
|
|
axum::http::StatusCode::SERVICE_UNAVAILABLE,
|
|
&format!("cannot tell whether {name:?} is an agent, so refusing: {e}"),
|
|
));
|
|
}
|
|
}
|
|
let plan = promote().await.map_err(|e| {
|
|
error_problem(
|
|
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
|
&format!("{e:#}"),
|
|
)
|
|
})?;
|
|
let change = match plan {
|
|
forge::site_admin::Plan::NoSuchUser => {
|
|
return Err(error_problem(
|
|
axum::http::StatusCode::NOT_FOUND,
|
|
&format!(
|
|
"the forge has no user {name:?}: the user has not logged in via SSO yet. \
|
|
The forge creates the account on their first authelia login; run this \
|
|
again after it"
|
|
),
|
|
));
|
|
}
|
|
forge::site_admin::Plan::AlreadyAdmin => ForgeAdminChange::AlreadyAdmin,
|
|
forge::site_admin::Plan::Promote => ForgeAdminChange::Promoted,
|
|
};
|
|
Ok(Json(MakeForgeAdminResponse { change }))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
/// `admin_unless_agent` with a `promote` that records whether it ran and
|
|
/// answers `plan`.
|
|
async fn forge_admin_route(
|
|
is_agent: Result<bool, String>,
|
|
plan: crate::forge::site_admin::Plan,
|
|
) -> (
|
|
Result<axum::Json<super::MakeForgeAdminResponse>, problem_details::ProblemDetails>,
|
|
bool,
|
|
) {
|
|
let ran = std::sync::atomic::AtomicBool::new(false);
|
|
let result = super::admin_unless_agent("atlas", is_agent, || async {
|
|
ran.store(true, std::sync::atomic::Ordering::SeqCst);
|
|
Ok(plan)
|
|
})
|
|
.await;
|
|
(result, ran.into_inner())
|
|
}
|
|
|
|
/// An agent's name never reaches the forge.
|
|
#[tokio::test]
|
|
async fn the_forge_admin_route_refuses_an_agent() {
|
|
let (result, ran) =
|
|
forge_admin_route(Ok(true), crate::forge::site_admin::Plan::Promote).await;
|
|
let Err(problem) = result else {
|
|
panic!("an agent's name must be refused");
|
|
};
|
|
assert!(!ran, "the account must not be touched");
|
|
assert_eq!(problem.status, Some(axum::http::StatusCode::CONFLICT));
|
|
}
|
|
|
|
/// A roster that can't be read can't vouch for the name, so the route
|
|
/// refuses rather than guessing "not an agent".
|
|
#[tokio::test]
|
|
async fn the_forge_admin_route_refuses_on_an_unreadable_roster() {
|
|
let (result, ran) = forge_admin_route(
|
|
Err("bridge down".to_owned()),
|
|
crate::forge::site_admin::Plan::Promote,
|
|
)
|
|
.await;
|
|
let Err(problem) = result else {
|
|
panic!("an unreadable roster must refuse");
|
|
};
|
|
assert!(!ran, "the account must not be touched");
|
|
assert_eq!(
|
|
problem.status,
|
|
Some(axum::http::StatusCode::SERVICE_UNAVAILABLE)
|
|
);
|
|
}
|
|
|
|
/// A missing account is a 404 that tells the operator what to wait for.
|
|
#[tokio::test]
|
|
async fn the_forge_admin_route_names_the_missing_sso_login() {
|
|
let (result, ran) =
|
|
forge_admin_route(Ok(false), crate::forge::site_admin::Plan::NoSuchUser).await;
|
|
let Err(problem) = result else {
|
|
panic!("a missing account must not report success");
|
|
};
|
|
assert!(ran);
|
|
assert_eq!(problem.status, Some(axum::http::StatusCode::NOT_FOUND));
|
|
let rendered = format!("{problem:?}");
|
|
assert!(
|
|
rendered.contains("has not logged in via SSO yet"),
|
|
"{rendered}"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_forge_admin_route_promotes_a_non_agent() {
|
|
let (result, ran) =
|
|
forge_admin_route(Ok(false), crate::forge::site_admin::Plan::Promote).await;
|
|
let Ok(axum::Json(resp)) = result else {
|
|
panic!("a non-agent must be promoted");
|
|
};
|
|
assert!(ran);
|
|
assert_eq!(resp.change, super::ForgeAdminChange::Promoted);
|
|
}
|
|
|
|
/// Idempotent: a second run succeeds and says nothing changed.
|
|
#[tokio::test]
|
|
async fn the_forge_admin_route_succeeds_for_an_admin() {
|
|
let (result, _) =
|
|
forge_admin_route(Ok(false), crate::forge::site_admin::Plan::AlreadyAdmin).await;
|
|
let Ok(axum::Json(resp)) = result else {
|
|
panic!("an existing admin must succeed");
|
|
};
|
|
assert_eq!(resp.change, super::ForgeAdminChange::AlreadyAdmin);
|
|
}
|
|
}
|