Skip to main content

agentmux_srv/server/
vault_import_batch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/vault/import_batch`: an agent has the Vault copy a named list of secrets from AWS Secrets Manager
5//! under one approval (docs/specs/SPEC_VAULT_LINKED_ENTRIES_FLEET_VAULT_AND_BATCH_IMPORT_2026_11_15.md ยง4).
6//!
7//! The whole list is checked first. Nobody is asked: srv reads every row, under one AWS session, and writes a history line
8//! for each (docs/specs/SPEC_VAULT_AGENT_ADDS_AND_EDITS_WITHOUT_ASKING_2026_11_25.md). It answers with a row per secret: its
9//! entry's id, or why nothing was kept. Never a value. A batch counts one write per row against the agent's pace.
10
11use axum::extract::State;
12use axum::http::StatusCode;
13use axum::response::{IntoResponse, Response};
14use axum::Json;
15use serde::Deserialize;
16use serde_json::{json, Value};
17
18use super::vault_import::{asker, credentials, error, Who};
19use super::AppState;
20use crate::backend::vault::aws_import::{self, Via};
21use crate::backend::vault::pace::{self, Act};
22use crate::backend::vault::aws_import_batch::{self, Approved, BatchPlan, BatchRequest, ItemResult, BUDGET};
23use crate::identity::aws_broker::mint::HostRunner;
24use crate::identity::aws_broker::policy;
25
26#[derive(Debug, Deserialize)]
27pub(crate) struct BatchBody {
28    #[serde(flatten)]
29    request: BatchRequest,
30    #[serde(default)]
31    auth: Option<agentmux_common::api_types::UiAutomationAuth>,
32}
33
34/// Whether any row of `plan` is read from AWS: a row that is a link is not.
35fn reads_aws(plan: &BatchPlan) -> bool {
36    plan.items.iter().any(|p| !p.is_link())
37}
38
39/// The list checked, and for a container agent the grant it names, before anything is read.
40async fn checked(state: &AppState, request: &BatchRequest, who: &Who) -> Result<BatchPlan, Response> {
41    let (store, agent, req) = (state.identity_store.clone(), who.agent.clone(), request.clone());
42    let plan = tokio::task::spawn_blocking(move || aws_import_batch::check(&store, &req, &agent))
43        .await
44        .map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
45        .map_err(|e| error(StatusCode::BAD_REQUEST, e))?;
46    // A link is made without a read: a container agent needs a grant only for a batch that copies something.
47    if who.container && reads_aws(&plan) {
48        let current = tokio::task::spawn_blocking(policy::current).await.unwrap_or_else(|e| Err(e.to_string()));
49        aws_import::check_grant(&current, plan.profile.as_deref(), &who.slug).map_err(|e| error(StatusCode::FORBIDDEN, e))?;
50    }
51    Ok(plan)
52}
53
54/// What is said of a batch that did nothing. A list of links only copies nothing to begin with: nothing was recorded.
55fn nothing(plan: &BatchPlan) -> &'static str {
56    if plan.links_only() {
57        "nothing was recorded"
58    } else {
59        "nothing was copied"
60    }
61}
62
63/// Records what became of a batch that read nothing, and tells the agent.
64fn refused(state: &AppState, plan: &BatchPlan, who: &Who, outcome: &str, status: StatusCode, said: String) -> Response {
65    aws_import_batch::note(&state.identity_store, plan, &who.agent, outcome, &plan.asked_text());
66    super::vault_handlers::publish(state);
67    error(status, said)
68}
69
70/// What the agent is told of a batch that ran: a row per approved secret, and the rows the person left out.
71fn answer(plan: &BatchPlan, approved: &Approved, results: &[ItemResult], outcome: &str) -> Value {
72    let stored = results.iter().filter(|r| r.id.is_some()).count();
73    json!({
74        "status": outcome,
75        "batch": plan.id,
76        "name": plan.name,
77        "vault": plan.vault_name,
78        "list": approved.list,
79        "stored": stored,
80        "failed": results.len() - stored,
81        "items": results,
82        "not_approved": approved.left_out,
83    })
84}
85
86/// Reads the approved rows under one AWS session (one broker mint for a container agent, whatever the rows), and
87/// records the batch's own line.
88async fn run(state: &AppState, plan: &BatchPlan, approved: &Approved, who: &Who, spent: &[Act]) -> Response {
89    // A link is made without a read, so a list of links only asks the broker for nothing.
90    let minted = match approved.items.iter().any(|p| !p.is_link()) {
91        true => match credentials(state, who, plan.profile.as_deref().unwrap_or_default(), &plan.reason).await {
92            Ok(minted) => minted,
93            Err(why) => {
94                pace::refund(&who.agent, spent);
95                return refused(state, plan, who, "failed", StatusCode::SERVICE_UNAVAILABLE, why);
96            }
97        },
98        false => None,
99    };
100    let via = minted.as_ref().map_or(Via::Host, Via::Session);
101    let results = aws_import_batch::perform(&state.identity_store, &HostRunner, &approved.items, via, &who.agent, BUDGET).await;
102    // A row that stored nothing does not use up the agent's pace.
103    let failed: Vec<Act> = spent.iter().enumerate().filter(|(i, _)| results.get(*i).map_or(true, |r| r.error.is_some())).map(|(_, a)| a.clone()).collect();
104    pace::refund(&who.agent, &failed);
105    let (outcome, what) = plan.ran_text(approved, &results);
106    aws_import_batch::note(&state.identity_store, plan, &who.agent, outcome, &what);
107    super::vault_handlers::publish(state);
108    Json(answer(plan, approved, &results, outcome)).into_response()
109}
110
111/// `POST /api/v1/vault/import_batch`
112pub(crate) async fn handle_vault_import_batch(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<BatchBody>) -> Response {
113    let who = match asker(&state, caller.as_deref(), body.auth.as_ref(), "import_batch", "who copied each secret") {
114        Ok(who) => who,
115        Err(refusal) => return refusal,
116    };
117    let plan = match checked(&state, &body.request, &who).await {
118        Ok(plan) => plan,
119        Err(refusal) => return refusal,
120    };
121    let acts: Vec<Act> = plan.items.iter().map(|p| super::vault_import::act_of(&p.target)).collect();
122    if let Err(why) = pace::admit(&who.agent, &acts) {
123        // A line records it only within the allowance of such lines: an agent that keeps asking cannot fill an entry's history.
124        if !pace::may_note_refusal(&who.agent) {
125            return error(StatusCode::TOO_MANY_REQUESTS, why);
126        }
127        return refused(&state, &plan, &who, "refused: pace", StatusCode::TOO_MANY_REQUESTS, why);
128    }
129    // Every row of the list, as the agent named it: nobody ticks rows.
130    let every_row: Vec<usize> = (0..plan.items.len()).collect();
131    let approved = plan.approved(&every_row);
132    run(&state, &plan, &approved, &who, &acts).await
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::backend::vault::aws_import::{Plan, Source, Target};
139
140    fn item(secret: &str, key: Option<&str>, label: &str, replaces: bool) -> Plan {
141        let target = if replaces {
142            Target::Replace { id: "api-key-stripe".into(), created_at: 1, kind: "api-key", part: "value", label: label.into(), vault_id: "fleet".into() }
143        } else {
144            Target::New { kind: "login", part: "password", label: label.into(), fields: Default::default(), vault_id: "fleet".into() }
145        };
146        Plan {
147            source: Source { aws_secret_id: secret.into(), key: key.map(String::from), user_key: None, region: Some("eu-west-1".into()), profile: Some("work-read".into()) },
148            target,
149            vault_name: "Fleet".into(),
150            reason: "copy the build hosts' passwords for task 31007".into(),
151            refs: vec!["batch:0123456789ab".into()],
152            share: false,
153        }
154    }
155
156    fn plan() -> BatchPlan {
157        BatchPlan {
158            id: "0123456789ab".into(),
159            name: "host passwords".into(),
160            vault_id: "fleet".into(),
161            vault_name: "Fleet".into(),
162            reason: "copy the build hosts' passwords for task 31007".into(),
163            region: Some("eu-west-1".into()),
164            profile: Some("work-read".into()),
165            refs: vec!["batch:0123456789ab".into()],
166            items: vec![item("hosts/alpha", Some("password"), "Alpha", false), item("pay/stripe", None, "Stripe", true)],
167        }
168    }
169
170    #[test]
171    fn a_batch_of_links_only_reads_nothing_in_aws_and_says_so() {
172        // What a container agent's grant is asked for: a batch that copies anything. A link is made without a read.
173        assert!(reads_aws(&plan()));
174        let link = |label: &str| Plan { target: Target::Link { kind: "api-key", label: label.into(), fields: Default::default(), vault_id: "fleet".into() }, ..item("prod/mailer", None, label, false) };
175        let links = BatchPlan { items: vec![link("Mail provider key"), link("Invoice provider key")], ..plan() };
176        assert!(!reads_aws(&links));
177        let mixed = BatchPlan { items: vec![link("Mail provider key"), item("hosts/alpha", Some("password"), "Alpha", false)], ..plan() };
178        assert!(reads_aws(&mixed));
179        // A list of links only copies nothing, so a refusal leaves nothing recorded; any other list, nothing copied.
180        assert_eq!((nothing(&links), nothing(&plan())), ("nothing was recorded", "nothing was copied"));
181    }
182
183    #[test]
184    fn a_batch_counts_a_write_a_row_for_the_pace_a_replacement_as_one_and_a_link_as_a_new_entry() {
185        use crate::backend::vault::pace::Act;
186        let acts: Vec<Act> = plan().items.iter().map(|p| super::super::vault_import::act_of(&p.target)).collect();
187        assert_eq!(acts, [Act::New, Act::Replace("api-key-stripe".into())]);
188        // Every row is read: nobody ticks rows, so the approval is the whole list.
189        let every: Vec<usize> = (0..plan().items.len()).collect();
190        assert_eq!(plan().approved(&every).items.len(), 2);
191    }
192
193    #[test]
194    fn the_answer_is_a_row_per_approved_secret_and_the_rows_left_out() {
195        let plan = plan();
196        let approved = plan.approved(&[0]);
197        let results = [ItemResult { label: "Alpha".into(), id: Some("login-alpha".into()), error: None }];
198        let (outcome, _) = plan.ran_text(&approved, &results);
199        let said = answer(&plan, &approved, &results, outcome);
200        assert_eq!(said["items"], json!([{ "label": "Alpha", "id": "login-alpha" }]));
201        assert_eq!((said["status"].as_str(), said["stored"].as_u64(), said["failed"].as_u64()), (Some("done"), Some(1), Some(0)));
202        assert_eq!((said["not_approved"].clone(), said["vault"].as_str(), said["batch"].as_str()), (json!(["Stripe"]), Some("Fleet"), Some("0123456789ab")));
203        assert_eq!(said["list"].as_str(), Some(approved.list.as_str()));
204    }
205}