agentmux_srv/server/app_api/
app_update.rs1use super::*;
19
20pub fn register(engine: &Arc<WshRpcEngine>, _state: &AppState) {
21 engine.register_typed(COMMAND_APP_UPDATE_STATUS, move |_req: Option<NoArgsReq>, _ctx| async move {
22 Ok::<_, String>(crate::backend::update::check::current_status())
23 });
24 engine.register_typed(COMMAND_APP_UPDATE_CHECK, move |_req: Option<NoArgsReq>, _ctx| async move {
26 crate::backend::update::check::check_now().await
27 });
28 engine.register_typed(COMMAND_APP_UPGRADE_REQUESTS, move |_req: Option<NoArgsReq>, _ctx| async move {
29 Ok::<_, String>(crate::backend::upgrade_request::UpgradeRequestsEvent {
30 requests: crate::backend::upgrade_request::list(),
31 })
32 });
33}
34
35#[derive(Debug, serde::Deserialize)]
37pub(crate) struct HostAppUpdateAction {
38 action: String,
40 #[serde(default)]
42 now: bool,
43}
44
45pub(crate) async fn handle_host_app_update(
49 axum::extract::State(state): axum::extract::State<AppState>,
50 headers: axum::http::HeaderMap,
51 axum::Json(body): axum::Json<HostAppUpdateAction>,
52) -> axum::response::Response {
53 use axum::http::StatusCode;
54 use axum::response::IntoResponse;
55 use axum::Json;
56 if !crate::server::ui_handlers::from_host(&state, &headers).await {
57 return (StatusCode::FORBIDDEN, Json(json!({ "ok": false, "error": "only the AgentMux host can do that" })))
58 .into_response();
59 }
60 let result = match body.action.as_str() {
61 "download" => crate::backend::update::download::start(),
62 "restart" => crate::backend::update::restart::start(body.now, Vec::new()),
63 "cancel" => crate::backend::update::restart::cancel(),
64 other => Err(format!("unknown action {other:?}")),
65 };
66 match result {
67 Ok(status) => Json(json!({ "ok": true, "data": status })).into_response(),
68 Err(e) => (StatusCode::CONFLICT, Json(json!({ "ok": false, "error": e }))).into_response(),
69 }
70}
71
72pub(crate) async fn handle_host_upgrade_request(
76 axum::extract::State(state): axum::extract::State<AppState>,
77 headers: axum::http::HeaderMap,
78 axum::Json(body): axum::Json<crate::backend::upgrade_request::UpgradeRequestAnswer>,
79) -> axum::response::Response {
80 use axum::http::StatusCode;
81 use axum::response::IntoResponse;
82 use axum::Json;
83 if !crate::server::ui_handlers::from_host(&state, &headers).await {
84 return (StatusCode::FORBIDDEN, Json(json!({ "ok": false, "error": "only the AgentMux host can answer an upgrade request" })))
85 .into_response();
86 }
87 match crate::backend::upgrade_request::answer(&state.broker, &state.mstore, &body.id, &body.version, body.accept) {
88 Ok(()) => Json(json!({ "ok": true })).into_response(),
89 Err(e) => (StatusCode::CONFLICT, Json(json!({ "ok": false, "error": e }))).into_response(),
90 }
91}
92
93#[derive(Debug, Default, serde::Deserialize)]
95pub(crate) struct UpdateStatusQuery {
96 #[serde(default)]
99 check: Option<String>,
100}
101
102pub(crate) async fn handle_update_status(
105 axum::extract::Query(q): axum::extract::Query<UpdateStatusQuery>,
106) -> axum::Json<crate::backend::update::check::AppUpdateStatus> {
107 if matches!(q.check.as_deref(), Some("1" | "true")) {
108 if let Ok(status) = crate::backend::update::check::check_now().await {
109 return axum::Json(status);
110 }
111 }
112 axum::Json(crate::backend::update::check::current_status())
113}
114
115pub(crate) async fn handle_request_upgrade(
120 axum::extract::State(state): axum::extract::State<AppState>,
121 caller: Option<axum::Extension<crate::server::caller::Caller>>,
122 axum::Json(req): axum::Json<agentmux_common::api_types::RequestUpgradeRequest>,
123) -> axum::response::Response {
124 use crate::backend::upgrade_request::{self, Outcome};
125 use axum::http::StatusCode;
126 use axum::response::IntoResponse;
127 use axum::Json;
128
129 let block_id = match crate::server::ui_handlers::verified_block_id(&state, caller.as_deref(), &req.auth) {
130 Ok(b) => b,
131 Err(e) => return (StatusCode::UNAUTHORIZED, Json(json!({ "error": e }))).into_response(),
132 };
133 let reason = req.reason.trim();
134 if reason.is_empty() {
135 return (StatusCode::BAD_REQUEST, Json(json!({ "error": "a reason is required" }))).into_response();
136 }
137 let status = crate::backend::update::check::check_now()
139 .await
140 .unwrap_or_else(|_| crate::backend::update::check::current_status());
141 let version = match upgrade_request::installable(&status, req.version.as_deref()) {
142 Ok(v) => v,
143 Err(outcome) => return Json(outcome).into_response(),
144 };
145 let agent = req.auth.agent_id.as_str();
146 let provenance = crate::backend::blockcontroller::get_controller(&block_id).and_then(|c| c.turn_provenance());
147 let outcome = match crate::sagas::self_quit::gate_upgrade(provenance.as_ref(), &req.user_instruction) {
148 Ok(()) => {
149 tracing::info!(agent, version = %version, reason, "upgrade: the user's own turn asked; starting");
150 let mut askers = upgrade_request::resolve_started(&state.broker, &state.mstore, &version);
153 crate::sagas::sensitive_window::answered_by_another(&state, "upgrade", "version", &version, "The person's own request started this upgrade");
154 askers.push(block_id.clone());
155 upgrade_request::start_upgrade(version.clone(), askers);
156 Outcome::Started { version, stopping: crate::backend::update::restart::stopping_now().await }
157 }
158 Err(refusal) => {
159 tracing::info!(agent, version = %version, reason, why = refusal.as_str(), "upgrade: asking as a sensitive request");
160 let uid = caller
163 .as_deref()
164 .and_then(crate::server::caller::Caller::uid)
165 .map(str::to_string)
166 .or_else(|| crate::backend::reactive::get_global_handler().get_agent(agent).and_then(|r| r.uid))
167 .unwrap_or_default();
168 if uid.is_empty() {
169 return (StatusCode::FORBIDDEN, Json(json!({ "error": "FORBIDDEN: this acts for an agent, so the request must carry that agent's token" }))).into_response();
170 }
171 let facts = std::collections::BTreeMap::from([("version".to_string(), version.clone())]);
172 match crate::server::sensitive_handlers::file_request(&state, &uid, agent, "upgrade", &facts, reason).await {
173 Ok(filed) => Outcome::Requested {
174 version,
175 id: filed["id"].as_str().unwrap_or_default().to_string(),
176 review: filed["review"].as_str().unwrap_or_default().to_string(),
177 },
178 Err(e) => return (StatusCode::CONFLICT, Json(json!({ "error": e }))).into_response(),
179 }
180 }
181 };
182 Json(outcome).into_response()
183}
184
185#[cfg(test)]
186mod tests {
187 use axum::body::Body;
188 use axum::http::{Request, StatusCode};
189 use serde_json::json;
190 use tower::ServiceExt;
191
192 async fn post(app: &axum::Router, host_token: Option<&str>, body: serde_json::Value) -> (StatusCode, serde_json::Value) {
193 let mut b = Request::builder()
194 .uri("/api/v1/host/app_update")
195 .method("POST")
196 .header("X-AuthKey", "test-secret-key")
197 .header("Content-Type", "application/json");
198 if let Some(token) = host_token {
199 b = b.header("X-Host-Token", token);
200 }
201 let resp = app.clone().oneshot(b.body(Body::from(body.to_string())).unwrap()).await.unwrap();
202 let status = resp.status();
203 let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
204 (status, serde_json::from_slice(&body).unwrap_or_default())
205 }
206
207 #[tokio::test]
210 async fn only_the_host_can_click_in_the_version_panel() {
211 let state = crate::server::tests::test_state();
212 *state.host_ipc.lock().await = Some(crate::server::state::HostIpc { port: 1, token: "host-ipc-token".into() });
213 let app = crate::server::build_router(state);
214 for action in ["download", "restart", "cancel"] {
215 let (s, body) = post(&app, None, json!({ "action": action })).await;
216 assert_eq!(s, StatusCode::FORBIDDEN, "{action}: {body}");
217 let (s, _) = post(&app, Some("not-the-token"), json!({ "action": action, "now": true })).await;
218 assert_eq!(s, StatusCode::FORBIDDEN, "{action}");
219 }
220 let (s, body) = post(&app, Some("host-ipc-token"), json!({ "action": "launch" })).await;
222 assert_eq!(s, StatusCode::CONFLICT, "{body}");
223 assert!(body["error"].as_str().unwrap_or_default().contains("unknown action"), "{body}");
224 }
225}