Skip to main content

agentmux_srv/server/
shell_secrets.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Terminal` `run` with `secrets`, `stdin_secret` and `secret_files`: a command
5//! that gets Vault values without the agent ever holding them
6//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §7,
7//! SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §4.3).
8//!
9//! The agent names `{ENV_NAME: entry}` for the environment, one entry for stdin, and
10//! `{ENV_NAME: entry}` for files whose path goes in `ENV_NAME`. srv checks who is
11//! asking, asks the person (every window shows the entry, the agent, the command and
12//! where it runs; "Always" is a grant per entry and agent), and only then reads the
13//! value, straight into that one process. The returned [`Scrubber`] takes the values
14//! back out of the output before it is published.
15
16use std::time::Duration;
17
18use axum::http::StatusCode;
19use futures_util::stream::{FuturesUnordered, StreamExt};
20
21use crate::backend::vault::capture;
22use crate::backend::vault::scrub::{self, Scrubber};
23use crate::backend::vault::uses::{Ended, UseRequest};
24use crate::backend::vault::{self, FillTarget};
25
26use super::AppState;
27
28/// Under the 150 s the Terminal tool waits for the job to be created.
29const ANSWER_WAIT: Duration = Duration::from_secs(120);
30/// Most entries one command may be given.
31const MOST: usize = 16;
32/// The longest command line, and working directory, the prompt shows whole. A
33/// longer one is refused rather than shown cut: the person approves what runs.
34const MAX_COMMAND: usize = 2000;
35const MAX_CWD: usize = 300;
36
37/// The key a command grant is stored under, in the grants table that web forms
38/// use for sites: `command:<agent>:<part>` can't be a site's origin. It is for one
39/// part of an entry: a card's expiry is not its number.
40pub(crate) fn grant_key(agent: &str, part: &str) -> String {
41    format!("command:{agent}:{part}")
42}
43
44/// What the command is given and what to take out of its output.
45pub(super) struct Injected {
46    pub env: Vec<(String, String)>,
47    /// Written to its stdin, then stdin is closed.
48    pub stdin: Option<zeroize::Zeroizing<String>>,
49    /// `(ENV_NAME, value)`: a file each, whose path goes in `ENV_NAME`.
50    pub files: Vec<(String, zeroize::Zeroizing<String>)>,
51    pub scrubber: Scrubber,
52    /// The entries it was given because nobody answered in 30 s: the agent is
53    /// told so.
54    pub went_ahead: Vec<String>,
55}
56
57/// What a command asks to be given, as the request names it.
58#[derive(Default, Clone, Copy)]
59pub(super) struct Wanted<'a> {
60    pub env: Option<&'a std::collections::HashMap<String, String>>,
61    pub stdin: Option<&'a str>,
62    pub files: Option<&'a std::collections::HashMap<String, String>>,
63    /// The agent's reason for the command's secrets, already checked.
64    pub reason: &'a str,
65    /// Who the request is attributed to: a container agent is proven by its token, as `Browser` proves it.
66    pub caller: Option<&'a super::caller::Caller>,
67}
68
69/// Where one value goes.
70#[derive(Debug, Clone, PartialEq)]
71enum Delivery {
72    Env(String),
73    Stdin,
74    File(String),
75}
76
77impl Delivery {
78    /// How the prompt names it, with the part: `STRIPE_KEY (value)`, `stdin (value)`.
79    fn shown(&self, part: &str) -> String {
80        match self {
81            Delivery::Env(n) => format!("{n} ({part})"),
82            Delivery::Stdin => format!("stdin ({part})"),
83            Delivery::File(n) => format!("a file at {n} ({part})"),
84        }
85    }
86}
87
88fn sorted(m: Option<&std::collections::HashMap<String, String>>) -> Vec<(String, String)> {
89    let mut v: Vec<(String, String)> = m.map(|m| m.iter().map(|(k, e)| (k.clone(), e.clone())).collect()).unwrap_or_default();
90    v.sort();
91    v
92}
93
94/// Every value the request names, checked: names usable, none twice, at most [`MOST`].
95fn deliveries(w: Wanted<'_>) -> Result<Vec<(Delivery, String)>, Refusal> {
96    let env = sorted(w.env);
97    let files = sorted(w.files);
98    for (name, _) in env.iter().chain(files.iter()) {
99        if !env_name_ok(name) {
100            return Err(refuse(StatusCode::BAD_REQUEST, format!("{name:?} isn't a usable environment variable name")));
101        }
102    }
103    if let Some((name, _)) = files.iter().find(|(f, _)| env.iter().any(|(n, _)| n == f)) {
104        return Err(refuse(StatusCode::BAD_REQUEST, format!("{name} is named in both secrets and secret_files")));
105    }
106    let mut out: Vec<(Delivery, String)> = env.into_iter().map(|(n, e)| (Delivery::Env(n), e)).collect();
107    if let Some(entry) = w.stdin.map(str::trim).filter(|s| !s.is_empty()) {
108        out.push((Delivery::Stdin, entry.to_string()));
109    }
110    out.extend(files.into_iter().map(|(n, e)| (Delivery::File(n), e)));
111    if out.len() > MOST {
112        return Err(refuse(StatusCode::BAD_REQUEST, format!("a command takes at most {MOST} Vault secrets")));
113    }
114    Ok(out)
115}
116
117type Refusal = (StatusCode, String);
118
119fn refuse(code: StatusCode, why: impl Into<String>) -> Refusal {
120    (code, why.into())
121}
122
123fn env_name_ok(name: &str) -> bool {
124    let mut chars = name.chars();
125    chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') && !name.to_ascii_uppercase().starts_with("AGENTMUX_")
126}
127
128fn clip(s: &str, n: usize) -> String {
129    let mut out: String = s.chars().take(n).collect();
130    if out.len() < s.len() {
131        out.push('…');
132    }
133    out
134}
135
136const DID_NOT_RUN: &str = "the command did not run";
137
138/// Asks the person, in the agent's pane `agent_block_id`, and waits for how it
139/// ended: srv decides on silence after [`ANSWER_WAIT`] at most.
140pub(super) async fn ask(state: &AppState, agent_block_id: &str, mut request: UseRequest, headline: &str) -> Ended {
141    request.block_id = agent_block_id.to_string();
142    super::vault_ask::ask(state, agent_block_id, request, ANSWER_WAIT, headline).await.0
143}
144
145fn refused(ended: Ended) -> Refusal {
146    let code = if ended == Ended::NoAnswer { StatusCode::REQUEST_TIMEOUT } else { StatusCode::FORBIDDEN };
147    refuse(code, ended.refusal(DID_NOT_RUN))
148}
149
150/// The agent asking, proved by its own signature: a prompt names them, and what
151/// they make or are allowed is theirs alone.
152fn agent_of(
153    state: &AppState,
154    caller: Option<&super::caller::Caller>,
155    agent_block_id: &str,
156    auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
157    needs: &str,
158) -> Result<String, Refusal> {
159    let agent = super::app_api::connections::verified_agent_as(state, caller, agent_block_id, auth)
160        .map_err(|e| refuse(StatusCode::FORBIDDEN, format!("{needs} needs to know which agent asks (its token or its signed identity): {}", e.replace("an SSH connection needs", "this needs"))))?;
161    Ok(agent.chars().take(64).collect())
162}
163
164/// Checks a command's `capture` before it runs (spec §4.2 of the generate spec). Nobody is asked: a rule that makes a new
165/// entry holds nothing of the person's yet, and one that replaces an entry's value keeps the old one 7 days and leaves a
166/// history line (docs/specs/SPEC_VAULT_AGENT_ADDS_AND_EDITS_WITHOUT_ASKING_2026_11_25.md), within the agent's pace. `None`
167/// when there is no capture. The labels returned are the entries nobody was asked about and that went ahead: always none
168/// now, kept for the shape every caller reads.
169pub(super) async fn plan_capture(
170    state: &AppState,
171    caller: Option<&super::caller::Caller>,
172    agent_block_id: &str,
173    auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
174    rules: Option<&[agentmux_common::api_types::CaptureRule]>,
175    cmd: &str,
176    _cwd: &str,
177    reason: &str,
178) -> Result<(Option<capture::Job>, Vec<String>), Refusal> {
179    let Some(rules) = rules.filter(|r| !r.is_empty()) else {
180        return Ok((None, Vec::new()));
181    };
182    let agent = agent_of(state, caller, agent_block_id, auth, "capture")?;
183    let (store, rules, a, c) = (state.identity_store.clone(), rules.to_vec(), agent.clone(), cmd.to_string());
184    let mut plan = tokio::task::spawn_blocking(move || capture::plan(&store, &rules, &a, &c))
185        .await
186        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
187        .map_err(|e| refuse(StatusCode::BAD_REQUEST, e))?;
188    plan.reason = reason.to_string();
189    let acts = plan.acts();
190    if let Err(why) = crate::backend::vault::pace::admit(&agent, &acts) {
191        for t in plan.replaces().filter(|_| crate::backend::vault::pace::may_note_refusal(&agent)) {
192            if let capture::Target::Existing { id, label, .. } = t {
193                vault::record_line(&state.identity_store, vault::Line { entry_id: id, label, actor: &agent, action: capture::CAPTURED, target: &clip(cmd, 160), outcome: "refused: pace", reason });
194            }
195        }
196        super::vault_handlers::publish(state);
197        return Err(refuse(StatusCode::TOO_MANY_REQUESTS, why));
198    }
199    let changed_state = state.clone();
200    let job = capture::Job { capture: plan, store: state.identity_store.clone(), changed: Box::new(move || super::vault_handlers::publish(&changed_state)), reservation: crate::backend::vault::pace::Reservation::new(&agent, acts) };
201    Ok((Some(job), Vec::new()))
202}
203
204/// One entry's question for a command: the entry, the parts of it asked for, the
205/// request and its headline.
206type Question<'a> = (&'a FillTarget, Vec<(&'a Delivery, &'a FillTarget)>, UseRequest, String);
207
208/// Asks every question at once and keeps the "Always" grants. The labels of the
209/// entries that went ahead with nobody answering, or the first that didn't go
210/// ahead, and how: the rest are withdrawn then.
211async fn ask_all<'a>(state: &AppState, agent_block_id: &str, agent: &str, questions: Vec<Question<'a>>) -> Result<Vec<String>, (&'a FillTarget, Ended)> {
212    let mut asking: FuturesUnordered<_> = questions.into_iter().map(|(first, waiting_on, request, headline)| async move { (first, waiting_on, ask(state, agent_block_id, request, &headline).await) }).collect();
213    let mut went_ahead = Vec::new();
214    while let Some((first, waiting_on, ended)) = asking.next().await {
215        match ended {
216            Ended::Once => {}
217            Ended::WentAhead => went_ahead.push(first.label.clone()),
218            Ended::Always => {
219                for (_, t) in &waiting_on {
220                    let (store, id, key, created) = (state.identity_store.clone(), t.id.clone(), grant_key(agent, t.part), t.created_at);
221                    let _ = tokio::task::spawn_blocking(move || store.vault_grant_add(&id, &key, agentmux_common::time::now_ms(), created)).await;
222                }
223            }
224            ended => return Err((first, ended)),
225        }
226    }
227    Ok(went_ahead)
228}
229
230/// A rotation's command, approved by the person with the rotation (`Vault`
231/// `rotate`): exactly these secrets (`NEW_SECRET` naming the entry's pending
232/// value, `OLD_SECRET` its current one). Only srv's rotation makes one, and hands
233/// it to [`inject`] directly; nothing an agent sends can.
234pub(super) struct Preapproved {
235    pub env: std::collections::HashMap<String, String>,
236}
237
238/// The question for the person about running `command` (cmd, cwd) with the parts of `first`'s entry that
239/// `waiting_on` names, and what the agent says it is for.
240fn command_request(agent: &str, first: &FillTarget, waiting_on: &[(&Delivery, &FillTarget)], command: (&str, &str), agent_reason: &str) -> UseRequest {
241    let mut whats: Vec<&str> = waiting_on.iter().map(|(_, t)| t.what.as_str()).collect();
242    whats.dedup();
243    UseRequest {
244        id: uuid::Uuid::new_v4().to_string(),
245        agent: agent.to_string(),
246        entry_id: first.id.clone(),
247        entry_label: first.label.clone(),
248        what: whats.join(" and "),
249        origin: String::new(),
250        field: waiting_on.iter().map(|(d, t)| d.shown(t.part)).collect::<Vec<_>>().join(", "),
251        offer_always: true,
252        reason: format!("it is the first time {agent} runs a command with this entry"),
253        agent_reason: agent_reason.to_string(),
254        kind: first.kind.to_string(),
255        command: command.0.to_string(),
256        cwd: command.1.to_string(),
257        requested_ms: agentmux_common::time::now_ms_u64(),
258        ..Default::default()
259    }
260}
261
262/// Resolves, asks for and reads the entries a command was given. `None` when it
263/// was given none.
264pub(super) async fn inject(
265    state: &AppState,
266    agent_block_id: &str,
267    auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
268    wanted: Wanted<'_>,
269    remote: bool,
270    cmd: &str,
271    cwd: &str,
272    preapproved: Option<&Preapproved>,
273) -> Result<Option<Injected>, Refusal> {
274    let (reason, wanted_caller) = (wanted.reason.to_string(), wanted.caller);
275    // A rotation's approval covers exactly the secrets it approved, nothing more.
276    let preapproved = preapproved.is_some_and(|p| {
277        wanted.stdin.is_none_or(|s| s.trim().is_empty()) && wanted.files.is_none_or(|f| f.is_empty()) && wanted.env == Some(&p.env)
278    });
279    let wanted = deliveries(wanted)?;
280    if wanted.is_empty() {
281        return Ok(None);
282    }
283    if remote {
284        return Err(refuse(
285            StatusCode::BAD_REQUEST,
286            "a Vault secret can't be sent to WSL or an SSH host yet: it would have to cross to another machine; run the command here",
287        ));
288    }
289    if cmd.chars().count() > MAX_COMMAND || cwd.chars().count() > MAX_CWD {
290        return Err(refuse(
291            StatusCode::BAD_REQUEST,
292            format!("a command given Vault secrets must fit in the approval prompt ({MAX_COMMAND} characters, folder {MAX_CWD}): put the steps in a script file and run that"),
293        ));
294    }
295    let agent = agent_of(state, wanted_caller, agent_block_id, auth, "a Vault secret")?;
296    let mut targets: Vec<(Delivery, FillTarget)> = Vec::new();
297    for (delivery, entry) in wanted {
298        let (store, who) = (state.identity_store.clone(), agent.clone());
299        let target = tokio::task::spawn_blocking(move || vault::command_target(&store, &entry, Some(&who)))
300            .await
301            .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
302            .map_err(|e| refuse(StatusCode::BAD_REQUEST, e))?;
303        targets.push((delivery, target));
304    }
305    // Only a rotation's own command, approved with it, gets its pending value.
306    if !preapproved && targets.iter().any(|(_, t)| t.version == Some("pending")) {
307        return Err(refuse(StatusCode::BAD_REQUEST, "@pending is a rotation's new value: only that rotation's own commands get it"));
308    }
309    let record = |t: &FillTarget, outcome: &str| {
310        vault::record_line(
311            &state.identity_store,
312            vault::Line { entry_id: &t.id, label: &t.label, actor: &agent, action: "ran a command", target: &clip(cmd, 160), outcome, reason: &reason },
313        );
314        // Every window's Vault pane shows the new line of the record.
315        super::vault_handlers::publish(state);
316    };
317
318    // One question per entry, covering the parts of it the agent hasn't been allowed
319    // to use in commands: a grant is for one part (a card's expiry is not its number).
320    // They are asked at once, each with its own deadline (spec §7), so nobody
321    // answering several waits 30 s for them together, within the Terminal tool's wait.
322    let mut asked: Vec<&str> = Vec::new();
323    let mut questions = Vec::new();
324    for (_, first) in &targets {
325        if preapproved {
326            break;
327        }
328        if asked.contains(&first.id.as_str()) {
329            continue;
330        }
331        asked.push(&first.id);
332        let mut waiting_on: Vec<(&Delivery, &FillTarget)> = Vec::new();
333        for (delivery, t) in targets.iter().filter(|(_, t)| t.id == first.id) {
334            let (store, id, key) = (state.identity_store.clone(), t.id.clone(), grant_key(&agent, t.part));
335            let granted = tokio::task::spawn_blocking(move || store.vault_grant_check(&id, &key).unwrap_or(false)).await.unwrap_or(false);
336            if !granted {
337                waiting_on.push((delivery, t));
338            }
339        }
340        if waiting_on.is_empty() {
341            continue;
342        }
343        let mut whats: Vec<&str> = waiting_on.iter().map(|(_, t)| t.what.as_str()).collect();
344        whats.dedup();
345        let what = whats.join(" and ");
346        let request = command_request(&agent, first, &waiting_on, (cmd, cwd), &reason);
347        questions.push((first, waiting_on, request, format!("{agent} wants to run a command with your {what}")));
348    }
349    let went_ahead = match ask_all(state, agent_block_id, &agent, questions).await {
350        Ok(w) => w,
351        Err((first, ended)) => {
352            record(first, ended.outcome());
353            return Err(refused(ended));
354        }
355    };
356
357    // Allowed: the values leave their sealed rows now, into this process only.
358    let mut env = Vec::new();
359    let mut stdin = None;
360    let mut files = Vec::new();
361    let mut known: Vec<(String, String)> = Vec::new();
362    for (delivery, target) in &targets {
363        let (store, t) = (state.identity_store.clone(), target.clone());
364        let value = match tokio::task::spawn_blocking(move || vault::value_for_command(&store, &t)).await {
365            Ok(Ok(v)) => v,
366            Ok(Err(e)) => {
367                record(target, "failed");
368                return Err(refuse(StatusCode::BAD_REQUEST, e));
369            }
370            Err(e) => return Err(refuse(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
371        };
372        if value.len() < scrub::MIN_LEN {
373            record(target, "failed");
374            return Err(refuse(
375                StatusCode::BAD_REQUEST,
376                format!("{} is too short to hand to a command: its output couldn't be cleaned of it", target.label),
377            ));
378        }
379        known.push(known_value(&target.id, &value));
380        match delivery {
381            Delivery::Env(name) => env.push((name.clone(), value.to_string())),
382            Delivery::Stdin => stdin = Some(value),
383            Delivery::File(name) => files.push((name.clone(), value)),
384        }
385    }
386    for (_, target) in &targets {
387        record(target, "done");
388        let (store, id) = (state.identity_store.clone(), target.id.clone());
389        let _ = tokio::task::spawn_blocking(move || store.vault_touch(&id, agentmux_common::time::now_ms())).await;
390    }
391    Ok(Some(Injected { env, stdin, files, scrubber: Scrubber::new(&known), went_ahead }))
392}
393
394/// A value handed to a command, to be cleaned out of its output. It is never written into a transcript either.
395fn known_value(id: &str, value: &str) -> (String, String) {
396    crate::backend::transcript::withhold::register(value);
397    (id.to_string(), value.to_string())
398}
399
400#[cfg(test)]
401#[path = "shell_secrets/tests.rs"]
402mod tests;