agentmux_srv/server/app_api/
agent_migrate_ids.rs1use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::{Extension, Json};
17use serde::Deserialize;
18use serde_json::json;
19
20use crate::backend::rpc_types::{CommandMigrateForkSlugsData, ForkSlugChoice, ForkSlugMigrationMode};
21use crate::server::agent_handlers::fork_slugs;
22use crate::server::caller::Caller;
23use crate::server::state::AppState;
24
25pub(crate) const AUDIT_ACTION: &str = "agent.ids.update";
27
28#[derive(Debug, Deserialize)]
29pub(crate) struct MigrateIdsRequest {
30 step: String,
32 #[serde(default)]
35 journal: Option<String>,
36 #[serde(default)]
38 choices: Option<Vec<ForkSlugChoice>>,
39}
40
41pub(crate) fn mode_of(step: &str) -> Option<ForkSlugMigrationMode> {
43 match step {
44 "plan" => Some(ForkSlugMigrationMode::Plan),
45 "stop" => Some(ForkSlugMigrationMode::Stop),
46 "apply" => Some(ForkSlugMigrationMode::Apply),
47 "rollback" => Some(ForkSlugMigrationMode::Rollback),
48 _ => None,
49 }
50}
51
52fn refuse(status: StatusCode, message: impl Into<String>) -> Response {
53 (status, Json(json!({ "error": message.into() }))).into_response()
54}
55
56fn audit(state: &AppState, uid: &str, slug: &str, step: &str, error: Option<&str>) {
57 let block_id = state.reactive_handler.block_for_uid(uid).unwrap_or_default();
58 let reason = format!("{slug} (uid {uid}): agent id update, step {step}");
59 state.reactive_handler.log_fleet_action_audit(
60 Some(slug),
61 "all agents",
62 &block_id,
63 AUDIT_ACTION,
64 error.is_none(),
65 error,
66 &uuid::Uuid::new_v4().to_string(),
67 Some(&reason),
68 );
69}
70
71pub(crate) async fn handle_agent_migrate_ids(
72 State(state): State<AppState>,
73 caller: Option<Extension<Caller>>,
74 Json(req): Json<MigrateIdsRequest>,
75) -> Response {
76 let caller = caller.map(|Extension(c)| c);
77 let Some(uid) = caller.as_ref().and_then(Caller::uid) else {
78 return refuse(
79 StatusCode::UNAUTHORIZED,
80 "no agent token: Agents migrate_ids acts as the calling agent; the operator runs the update in Settings › Agents",
81 );
82 };
83 if req.journal.is_some() {
84 return refuse(StatusCode::BAD_REQUEST, "INVALID_ARG: journal is not accepted from an agent: rollback undoes the latest finished run");
85 }
86 let step = req.step.trim().to_string();
87 let Some(mode) = mode_of(&step) else {
88 return refuse(StatusCode::BAD_REQUEST, "INVALID_ARG: step is plan, stop, apply or rollback");
89 };
90 let def = match state.mstore.agent_def_get(uid) {
91 Ok(Some(def)) => def,
92 Ok(None) => return refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"),
93 Err(e) => return refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent id update: {e}")),
94 };
95 let cmd = CommandMigrateForkSlugsData { mode, journal: None, quick: None, choices: req.choices };
96 let stopped_by = format!("{} (Agents migrate_ids)", def.slug);
97 let result = fork_slugs::run(&state, cmd, &stopped_by).await;
98 if mode != ForkSlugMigrationMode::Plan {
99 audit(&state, uid, &def.slug, &step, result.as_ref().err().map(String::as_str));
100 }
101 match result {
102 Ok(r) => Json(r).into_response(),
103 Err(e) => refuse(StatusCode::INTERNAL_SERVER_ERROR, e),
104 }
105}
106
107#[cfg(test)]
108#[path = "tests/agent_migrate_ids_tests.rs"]
109mod tests;