1use 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
28const ANSWER_WAIT: Duration = Duration::from_secs(120);
30const MOST: usize = 16;
32const MAX_COMMAND: usize = 2000;
35const MAX_CWD: usize = 300;
36
37pub(crate) fn grant_key(agent: &str, part: &str) -> String {
41 format!("command:{agent}:{part}")
42}
43
44pub(super) struct Injected {
46 pub env: Vec<(String, String)>,
47 pub stdin: Option<zeroize::Zeroizing<String>>,
49 pub files: Vec<(String, zeroize::Zeroizing<String>)>,
51 pub scrubber: Scrubber,
52 pub went_ahead: Vec<String>,
55}
56
57#[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 pub reason: &'a str,
65 pub caller: Option<&'a super::caller::Caller>,
67}
68
69#[derive(Debug, Clone, PartialEq)]
71enum Delivery {
72 Env(String),
73 Stdin,
74 File(String),
75}
76
77impl Delivery {
78 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
94fn 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
138pub(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
150fn 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
164pub(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
204type Question<'a> = (&'a FillTarget, Vec<(&'a Delivery, &'a FillTarget)>, UseRequest, String);
207
208async 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
230pub(super) struct Preapproved {
235 pub env: std::collections::HashMap<String, String>,
236}
237
238fn 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
262pub(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 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 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 super::vault_handlers::publish(state);
316 };
317
318 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 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
394fn 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;