Skip to main content

agentmux_srv/server/
vault_rotate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Vault` `rotate`: a new value for an entry, set at its service by a command,
5//! without anyone seeing it
6//! (docs/specs/SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §4.4).
7//!
8//! 1. srv generates a new value as a **pending** version that nothing is given yet;
9//! 2. runs `set` with it in `NEW_SECRET` and the current value in `OLD_SECRET`;
10//! 3. runs `verify`, if given, with it in `NEW_SECRET`;
11//! 4. on success makes it the entry's value (the old one kept 7 days); on any
12//!    failure keeps the old one and the pending one, marked with the step that
13//!    failed: if `set` succeeded and `verify` didn't, the service may already
14//!    hold the new value, so nothing is thrown away.
15//!
16//! The person approves the rotation once, naming `set` and `verify` and saying
17//! the value at the service changes; "Always" covers those two command lines for
18//! this agent and entry. The commands run like `Terminal` `run` with secrets (in
19//! the agent's folder, output cleaned of both values), approved with the rotation.
20
21use std::collections::HashMap;
22use std::time::Duration;
23
24use axum::extract::State;
25use axum::http::StatusCode;
26use axum::response::{IntoResponse, Response};
27use axum::Json;
28use serde::Deserialize;
29use serde_json::{json, Value};
30
31use agentmux_common::api_types::{ShellCreateRequest, UiAutomationAuth};
32
33use crate::backend::vault::uses::{Ended, UseRequest};
34use crate::backend::vault::{self, generate, versions, GENERATED_KINDS};
35
36use super::AppState;
37
38/// The activity's action for a rotation.
39pub(crate) const ROTATED: &str = "rotated";
40/// How long `set` or `verify` may run.
41const COMMAND_WAIT: Duration = Duration::from_secs(10 * 60);
42
43#[derive(Debug, Deserialize)]
44pub(crate) struct RotateBody {
45    #[serde(default)]
46    auth: Option<UiAutomationAuth>,
47    id: String,
48    set: String,
49    #[serde(default)]
50    verify: Option<String>,
51    #[serde(default)]
52    cwd: Option<String>,
53    /// Why the agent rotates it: one line of 8 to 300 characters, required.
54    #[serde(default)]
55    reason: Option<String>,
56    /// How the new value is made, as for `generate` (20 characters by default).
57    #[serde(default)]
58    rules: generate::RulesRequest,
59}
60
61fn error(code: StatusCode, why: impl Into<String>) -> Response {
62    (code, Json(json!({ "error": why.into() }))).into_response()
63}
64
65/// The grant "Always" gives: this agent may rotate the entry with these two
66/// command lines without asking again.
67pub(crate) fn grant_key(agent: &str, set: &str, verify: &str) -> String {
68    format!("rotate:{agent}:{set}\n{verify}")
69}
70
71/// What the approval prompt shows as the command.
72fn shown_commands(set: &str, verify: &str) -> String {
73    if verify.is_empty() {
74        format!("set: {set}")
75    } else {
76        format!("set: {set}\nverify: {verify}")
77    }
78}
79
80/// The entry `id` an agent asks to rotate. Before anything is asked or written, one in a Vault the
81/// agent may not use is refused as one that is not there.
82fn rotatable_entry(state: &AppState, id: &str, agent: &str) -> Result<crate::backend::storage::vault::VaultRow, Response> {
83    let none = || error(StatusCode::BAD_REQUEST, format!("no Vault entry {id:?}: Vault's list action shows the entries"));
84    let row = state.identity_store.vault_get(id).map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?.ok_or_else(none)?;
85    match vault::vaults::entry_row_usable(&state.identity_store, &row.vault_id, Some(agent)) {
86        Ok(true) => match vault::linked::takes_no_value(&row, "rotate the key where it lives, then record the date with update (rotated)") {
87            Some(refusal) => Err(error(StatusCode::BAD_REQUEST, refusal)),
88            None => Ok(row),
89        },
90        Ok(false) => Err(none()),
91        Err(e) => Err(error(StatusCode::INTERNAL_SERVER_ERROR, e)),
92    }
93}
94
95/// The person's question about rotating `row`: both commands, that its value changes, and what the agent says it is for.
96fn rotation_request(agent: &str, row: &crate::backend::storage::vault::VaultRow, command: String, cwd: String, agent_reason: &str) -> UseRequest {
97    UseRequest {
98        id: uuid::Uuid::new_v4().to_string(),
99        agent: agent.to_string(),
100        entry_id: row.id.clone(),
101        entry_label: row.label.clone(),
102        what: "value".to_string(),
103        origin: String::new(),
104        field: "NEW_SECRET, OLD_SECRET".to_string(),
105        offer_always: true,
106        reason: "rotating changes this entry's value at the service: the commands give it a new value AgentMux makes".to_string(),
107        agent_reason: agent_reason.to_string(),
108        kind: row.kind.clone(),
109        command,
110        cwd,
111        replaces: true,
112        requested_ms: agentmux_common::time::now_ms_u64(),
113        ..Default::default()
114    }
115}
116
117/// The pane of the agent asking, proven. A rotation runs its `set` and `verify` commands on the host, which a container
118/// agent can't do (`/api/v1/shell/` is refused to it for the same reason), so one is refused before the person is asked.
119fn host_pane(state: &AppState, caller: Option<&super::caller::Caller>, auth: &UiAutomationAuth) -> Result<String, Response> {
120    let pane = super::ui_handlers::verified_block_id(state, caller, auth)
121        .map_err(|e| error(StatusCode::FORBIDDEN, format!("rotate needs to know which agent asks (its token or its signed identity): {e}")))?;
122    if super::browser_identity::in_container(state, &pane) {
123        return Err(error(StatusCode::FORBIDDEN, "rotate runs its commands on the host, which a container agent can't do: ask the person to rotate it, or a native agent"));
124    }
125    Ok(pane)
126}
127
128/// `POST /api/v1/vault/rotate`.
129pub(crate) async fn handle_vault_rotate(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<RotateBody>) -> Response {
130    let Some(auth) = body.auth.clone() else {
131        return error(StatusCode::FORBIDDEN, "rotate needs to know which agent asks (its token or its signed identity)");
132    };
133    let block_id = match host_pane(&state, caller.as_deref(), &auth) {
134        Ok(b) => b,
135        Err(refused) => return refused,
136    };
137    let agent: String = auth.agent_id.chars().take(64).collect();
138    let reason = match vault::history::require_reason(body.reason.as_deref()) {
139        Ok(r) => r,
140        Err(e) => return error(StatusCode::BAD_REQUEST, e),
141    };
142    let (set, verify) = (body.set.trim().to_string(), body.verify.as_deref().unwrap_or("").trim().to_string());
143    if set.is_empty() {
144        return error(StatusCode::BAD_REQUEST, "rotate needs set: the command that gives the service the new value (NEW_SECRET)");
145    }
146    let row = match rotatable_entry(&state, &body.id, &agent) {
147        Ok(r) => r,
148        Err(refused) => return refused,
149    };
150    if !GENERATED_KINDS.iter().any(|(k, _)| *k == row.kind) {
151        return error(StatusCode::BAD_REQUEST, format!("{} is a {}: only an API key, a login's password or a note can be rotated", row.label, row.kind));
152    }
153    let rules = match generate::rules(&body.rules) {
154        Ok(r) => r,
155        Err(e) => return error(StatusCode::BAD_REQUEST, e),
156    };
157
158    // The person approves the rotation once: both commands, and that the value changes.
159    let key = grant_key(&agent, &set, &verify);
160    let (store, id) = (state.identity_store.clone(), row.id.clone());
161    let k = key.clone();
162    let granted = tokio::task::spawn_blocking(move || store.vault_grant_check(&id, &k).unwrap_or(false)).await.unwrap_or(false);
163    let mut went_ahead = false;
164    if !granted {
165        let request = rotation_request(&agent, &row, shown_commands(&set, &verify), body.cwd.clone().unwrap_or_default(), &reason);
166        match super::shell_secrets::ask(&state, &block_id, request, &format!("{agent} wants to rotate {}", row.label)).await {
167            Ended::Once => {}
168            Ended::WentAhead => went_ahead = true,
169            Ended::Always => {
170                let (store, id, created) = (state.identity_store.clone(), row.id.clone(), row.created_at);
171                let _ = tokio::task::spawn_blocking(move || store.vault_grant_add(&id, &key, agentmux_common::time::now_ms(), created)).await;
172            }
173            ended => {
174                let outcome = ended.outcome();
175                vault::record_line(&state.identity_store, vault::Line { entry_id: &row.id, label: &row.label, actor: &agent, action: ROTATED, target: &clip(&set), outcome, reason: &reason });
176                super::vault_handlers::publish(&state);
177                return error(StatusCode::FORBIDDEN, format!("the person didn't allow it ({outcome}): nothing was changed"));
178            }
179        }
180    }
181
182    // 1. The new value, pending.
183    let value = match generate::generate(&rules) {
184        Ok(v) => v,
185        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e),
186    };
187    let (store, id, a) = (state.identity_store.clone(), row.id.clone(), agent.clone());
188    let rotation = match tokio::task::spawn_blocking(move || versions::start_rotation(&store, &id, &value, &a)).await {
189        Ok(Ok(r)) => r,
190        Ok(Err(e)) => return error(StatusCode::CONFLICT, e),
191        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
192    };
193    super::vault_handlers::publish(&state);
194
195    // 2. set, with the pending value and the current one.
196    let cwd = body.cwd.as_deref();
197    let pending = format!("{}@pending", row.id);
198    let set_env = HashMap::from([("NEW_SECRET".to_string(), pending.clone()), ("OLD_SECRET".to_string(), row.id.clone())]);
199    let set_ran = run(&state, caller.as_deref(), &block_id, &auth, &agent, &set, cwd, set_env, &reason).await;
200    // 3. verify, with the pending value.
201    let verify_ran = match (&set_ran, verify.is_empty()) {
202        (Ok(r), false) if r.ok() => Some(run(&state, caller.as_deref(), &block_id, &auth, &agent, &verify, cwd, HashMap::from([("NEW_SECRET".to_string(), pending)]), &reason).await),
203        _ => None,
204    };
205    // A set that never started gave no service the value: it is dropped, not kept.
206    // One that started and was stopped, or lost, may have: it is kept (step 2).
207    if let Err(RunError { started: false, why }) = &set_ran {
208        let (store, r) = (state.identity_store.clone(), rotation);
209        let _ = tokio::task::spawn_blocking(move || versions::abandon_rotation(&store, &r)).await;
210        vault::record_line(&state.identity_store, vault::Line { entry_id: &row.id, label: &row.label, actor: &agent, action: ROTATED, target: &clip(&set), outcome: "failed: set couldn't start", reason: &reason });
211        super::vault_handlers::publish(&state);
212        return Json(json!({
213            "id": row.id,
214            "label": row.label,
215            "rotated": false,
216            "failed_step": 2,
217            "set": ran_json(&set_ran),
218            "note": format!("set couldn't start ({why}), so nothing changed: the entry keeps its value and the new one was dropped."),
219        }))
220        .into_response();
221    }
222    let failed = step_failed(&set_ran, verify_ran.as_ref());
223
224    // 4. Current on success; kept, marked, on failure.
225    let (store, id, a) = (state.identity_store.clone(), row.id.clone(), agent.clone());
226    let finished = tokio::task::spawn_blocking(move || versions::finish_rotation(&store, &id, &rotation, failed.map_or(Ok(()), Err), &a))
227        .await
228        .map_err(|e| e.to_string())
229        .and_then(|r| r);
230    let outcome = match (&failed, &finished) {
231        (None, Ok(())) => "done".to_string(),
232        (Some(step), _) => format!("failed at step {step}"),
233        (None, Err(_)) => "failed: the entry changed meanwhile".to_string(),
234    };
235    vault::record_line(&state.identity_store, vault::Line { entry_id: &row.id, label: &row.label, actor: &agent, action: ROTATED, target: &clip(&set), outcome: &outcome, reason: &reason });
236    super::vault_handlers::publish(&state);
237
238    let rotated = failed.is_none() && finished.is_ok();
239    let note = match (failed, &finished) {
240        (None, Ok(())) => "Rotated: the entry holds the new value; the old one is kept 7 days (Terminal run can name it as id@previous).".to_string(),
241        (Some(2), _) => "set failed, so the entry keeps its old value. The new one is kept 7 days as a version, marked \"rotation failed at step 2\", in case the service took it anyway.".to_string(),
242        (Some(_), _) => "verify failed after set succeeded: the service may already hold the new value. The entry keeps its old value, and the new one is kept 7 days as a version, marked \"rotation failed at step 3\"; the person can put it in from the Vault pane.".to_string(),
243        (None, Err(e)) => e.clone(),
244    };
245    let ran = (ran_json(&set_ran), verify_ran.as_ref().map(ran_json));
246    let out = json!({ "id": row.id, "label": row.label, "rotated": rotated, "failed_step": failed, "set": ran.0, "verify": ran.1, "note": note });
247    Json(super::vault_ask::with_approval(out, went_ahead)).into_response()
248}
249
250/// What a command did: its exit code and its last lines, already cleaned of the
251/// values it was given.
252#[derive(Debug)]
253struct Ran {
254    exit_code: Option<i32>,
255    output: Vec<String>,
256}
257
258impl Ran {
259    fn ok(&self) -> bool {
260        self.exit_code == Some(0)
261    }
262}
263
264/// Why a command has no exit code: it never started (nothing ran), or it started
265/// and was stopped or lost track of (it may have done its work).
266#[derive(Debug)]
267struct RunError {
268    started: bool,
269    why: String,
270}
271
272/// The step a rotation failed at: 2 when `set` didn't succeed (it exited non-zero,
273/// or was stopped or lost after it started), 3 when `verify` didn't; `None` when
274/// both succeeded.
275fn step_failed(set: &Result<Ran, RunError>, verify: Option<&Result<Ran, RunError>>) -> Option<u8> {
276    if !set.as_ref().is_ok_and(Ran::ok) {
277        return Some(2);
278    }
279    match verify {
280        Some(v) if !v.as_ref().is_ok_and(Ran::ok) => Some(3),
281        _ => None,
282    }
283}
284
285fn ran_json(r: &Result<Ran, RunError>) -> Value {
286    match r {
287        Ok(r) => json!({ "exit_code": r.exit_code, "output": r.output }),
288        Err(e) => json!({ "error": e.why, "started": e.started }),
289    }
290}
291
292fn clip(s: &str) -> String {
293    let mut out: String = s.chars().take(160).collect();
294    if s.chars().count() > 160 {
295        out.push('…');
296    }
297    out
298}
299
300/// Runs `cmd` as `Terminal` `run` would with `secrets`, approved with the
301/// rotation, and waits for it to end.
302#[allow(clippy::too_many_arguments)]
303async fn run(
304    state: &AppState,
305    caller: Option<&super::caller::Caller>,
306    block_id: &str,
307    auth: &UiAutomationAuth,
308    agent: &str,
309    cmd: &str,
310    cwd: Option<&str>,
311    secrets: HashMap<String, String>,
312    reason: &str,
313) -> Result<Ran, RunError> {
314    let not_started = |why: String| RunError { started: false, why };
315    let req: ShellCreateRequest = serde_json::from_value(json!({
316        "agent_block_id": block_id,
317        "cmd": cmd,
318        "cwd": cwd,
319        "title": format!("rotate: {}", clip(cmd)),
320        "auth": auth,
321        "secrets": &secrets,
322        "reason": reason,
323    }))
324    .map_err(|e| not_started(e.to_string()))?;
325    let approved = super::shell_secrets::Preapproved { env: secrets };
326    let resp = super::http_shell::create_shell(state.clone(), caller, req, Some(&approved)).await;
327    let status = resp.status();
328    // A success means the shell was spawned: from here on it may have run.
329    let lost = |why: String| RunError { started: status.is_success(), why };
330    let body = axum::body::to_bytes(resp.into_body(), 1 << 20).await.map_err(|e| lost(e.to_string()))?;
331    let v: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
332    if !status.is_success() {
333        return Err(not_started(v.get("error").and_then(Value::as_str).unwrap_or("the command couldn't start").to_string()));
334    }
335    let shell_id = v.get("shell_id").and_then(Value::as_str).ok_or_else(|| lost("srv lost track of the command".to_string()))?.to_string();
336    let deadline = tokio::time::Instant::now() + COMMAND_WAIT;
337    loop {
338        if let Some(s) = state.shell_sessions.get_status_if_known(&shell_id).filter(|s| !s.running) {
339            let output = s.tail.map(|t| t.lock().iter().cloned().collect()).unwrap_or_default();
340            return Ok(Ran { exit_code: s.exit_code, output });
341        }
342        if tokio::time::Instant::now() >= deadline {
343            state.shell_sessions.stop(&shell_id);
344            return Err(RunError { started: true, why: format!("{} was still running after {} minutes, so it was stopped", clip(cmd), COMMAND_WAIT.as_secs() / 60) });
345        }
346        tokio::time::sleep(Duration::from_millis(250)).await;
347    }
348}
349
350#[cfg(test)]
351#[path = "vault_rotate_tests.rs"]
352mod tests;