1use std::time::Duration;
13
14use axum::extract::State;
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Response};
17use axum::Json;
18use serde::Deserialize;
19use serde_json::{json, Value};
20
21use super::AppState;
22use crate::backend::vault::aws_import::{self, ImportRequest, Plan, Target, Via, SERVICE};
23use crate::backend::vault::uses::{Decision, Ended, UseImport, UseRequest};
24use crate::identity::aws_broker::mint::HostRunner;
25use crate::identity::aws_broker::request::{credentials_for, Ask};
26use crate::identity::aws_broker::{policy, sessions};
27
28pub(super) const ANSWER_WAIT: Duration = Duration::from_secs(120);
30pub(super) const ANSWER_WAIT_MAX: Duration = Duration::from_secs(600);
31
32#[derive(Debug, Deserialize)]
33pub(crate) struct ImportBody {
34 #[serde(flatten)]
35 request: ImportRequest,
36 #[serde(default)]
37 auth: Option<agentmux_common::api_types::UiAutomationAuth>,
38 #[serde(default)]
39 wait_secs: Option<u64>,
40}
41
42pub(super) fn error(status: StatusCode, message: impl Into<String>) -> Response {
43 (status, Json(json!({ "error": message.into() }))).into_response()
44}
45
46pub(super) struct Who {
49 pub(super) agent: String,
50 pub(super) pane: String,
51 pub(super) slug: String,
52 pub(super) uid: String,
53 pub(super) container: bool,
54}
55
56pub(super) fn asker(
58 state: &AppState,
59 caller: Option<&super::caller::Caller>,
60 auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
61 what: &str,
62 records: &str,
63) -> Result<Who, Response> {
64 let refuse = |why: String| error(StatusCode::FORBIDDEN, format!("{what} needs to know which agent asks (its token or its signed identity): {why}"));
65 let Some(auth) = auth else { return Err(refuse(format!("the Vault records {records}"))) };
66 let pane = super::ui_handlers::verified_block_id(state, caller, auth).map_err(refuse)?;
67 let agent: String = auth.agent_id.chars().take(64).collect();
68 let uid = crate::backend::reactive::handler::get_global_handler().get_agent(&auth.agent_id).and_then(|r| r.uid);
69 let def = uid.as_deref().and_then(|u| state.mstore.agent_def_get(u).ok().flatten());
70 let Some(def) = def else { return Err(error(StatusCode::FORBIDDEN, format!("{what} couldn't tell which agent this is"))) };
71 Ok(Who { agent, pane, slug: def.slug.clone(), uid: uid.unwrap_or_default(), container: def.runtime().is_container() })
72}
73
74pub(super) fn ticked_share(request: &UseRequest, share: Option<&Value>, decision: Decision) -> Option<bool> {
77 if decision == Decision::Deny || !request.import.as_ref().is_some_and(|i| i.share) {
78 return None;
79 }
80 Some(share.and_then(Value::as_bool).unwrap_or(false))
81}
82
83pub(super) async fn share_made(state: &AppState, who: &Who, id: &str, ticked: bool) -> (bool, String) {
86 if !ticked {
87 return (false, "the share was not ticked (left unticked, or the approval sent no tick): the login is saved and not shared with you".into());
88 }
89 let (store, id, uid) = (state.identity_store.clone(), id.to_string(), who.uid.clone());
90 match tokio::task::spawn_blocking(move || crate::backend::vault::shares::add(&store, &id, &uid)).await {
91 Ok(Ok(_)) => (true, "shared with you: sign in to the site with Browser signin, which asks the person the first time".into()),
92 Ok(Err(why)) => (false, format!("the login is saved and not shared: {why}")),
93 Err(e) => (false, format!("the login is saved and not shared: {e}")),
94 }
95}
96
97pub(super) fn act_of(target: &Target) -> crate::backend::vault::pace::Act {
99 use crate::backend::vault::pace::Act;
100 match target {
101 Target::Replace { id, .. } => Act::Replace(id.clone()),
102 Target::New { .. } | Target::Link { .. } => Act::New,
103 }
104}
105
106fn card(plan: &Plan, who: &Who) -> UseRequest {
109 let replaces = matches!(plan.target, Target::Replace { .. });
110 UseRequest {
111 id: uuid::Uuid::new_v4().to_string(),
112 agent: who.agent.clone(),
113 block_id: who.pane.clone(),
114 entry_id: plan.entry_id().to_string(),
115 entry_label: plan.label().to_string(),
116 what: "secret".into(),
117 offer_always: false,
118 reason: "an agent asked to copy a secret into your Vault".into(),
119 agent_reason: plan.reason.clone(),
120 kind: plan.kind().to_string(),
121 requested_ms: agentmux_common::time::now_ms_u64(),
122 import: Some(UseImport {
123 service: SERVICE.into(),
124 secret: plan.source.aws_secret_id.clone(),
125 key: plan.source.key.clone().unwrap_or_default(),
126 region: plan.source.region.clone().unwrap_or_default(),
127 profile: plan.source.profile.clone().unwrap_or_default(),
128 grant: who.container,
129 vault: plan.vault_name.clone(),
130 replaces,
131 user_key: plan.source.user_key.clone().unwrap_or_default(),
132 site: plan.site().to_string(),
133 share: plan.share,
134 }),
135 ..Default::default()
136 }
137}
138
139fn headline(plan: &Plan, who: &Who) -> String {
140 format!("{} wants to copy a secret from {SERVICE} into your Vault as {}", who.agent, plan.label())
141}
142
143pub(super) fn not_allowed(ended: Ended) -> String {
145 match ended {
146 Ended::Expired => "nobody answered, and a copy of a secret needs a yes: nothing was copied; ask the person".to_string(),
147 other => other.refusal("nothing was copied"),
148 }
149}
150
151async fn checked(state: &AppState, body: &ImportBody, who: &Who) -> Result<Plan, Response> {
153 let (store, agent) = (state.identity_store.clone(), who.agent.clone());
154 let req = body.request.clone();
155 let plan = tokio::task::spawn_blocking(move || aws_import::check(&store, &req, &agent))
156 .await
157 .map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
158 .map_err(|e| error(StatusCode::BAD_REQUEST, e))?;
159 if who.container {
160 let current = tokio::task::spawn_blocking(policy::current).await.unwrap_or_else(|e| Err(e.to_string()));
161 aws_import::check_grant(¤t, plan.source.profile.as_deref(), &who.slug).map_err(|e| error(StatusCode::FORBIDDEN, e))?;
162 }
163 Ok(plan)
164}
165
166pub(super) fn pace_refused(state: &AppState, plan: &Plan, who: &Who, why: String) -> Response {
169 if crate::backend::vault::pace::may_note_refusal(&who.agent) {
170 return refused(state, plan, who, "refused: pace", StatusCode::TOO_MANY_REQUESTS, why);
171 }
172 error(StatusCode::TOO_MANY_REQUESTS, why)
173}
174
175fn refused(state: &AppState, plan: &Plan, who: &Who, outcome: &str, status: StatusCode, said: String) -> Response {
177 aws_import::note(&state.identity_store, plan, plan.entry_id(), plan.label(), &who.agent, outcome);
178 super::vault_handlers::publish(state);
179 error(status, said)
180}
181
182pub(super) async fn credentials(state: &AppState, who: &Who, profile: &str, reason: &str) -> Result<Option<crate::identity::aws_broker::mint::Minted>, String> {
185 if !who.container {
186 return Ok(None);
187 }
188 let current = tokio::task::spawn_blocking(policy::current).await.unwrap_or_else(|e| Err(e.to_string()));
189 let ask = Ask { agent_uid: &who.uid, agent_slug: &who.slug, in_container: true, profile, reason: Some(reason), tag: None, seconds: None };
190 match credentials_for(current, sessions::global(), &HostRunner, &ask, chrono::Utc::now()).await {
191 Ok(granted) => {
192 super::app_api::aws_credentials::audit_granted(state, &who.slug, &who.uid, &granted);
193 Ok(Some(granted.creds))
194 }
195 Err(refusal) => {
196 super::app_api::aws_credentials::audit_refused(state, &who.slug, &who.uid, ask.profile, &refusal);
197 Err(refusal.text())
198 }
199 }
200}
201
202pub(crate) async fn handle_vault_import(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<ImportBody>) -> Response {
204 let who = match asker(&state, caller.as_deref(), body.auth.as_ref(), "import", "who copied each secret") {
205 Ok(who) => who,
206 Err(refusal) => return refusal,
207 };
208 let plan = match checked(&state, &body, &who).await {
209 Ok(plan) => plan,
210 Err(refusal) => return refusal,
211 };
212 let spent = [act_of(&plan.target)];
213 if let Err(why) = crate::backend::vault::pace::admit(&who.agent, &spent) {
214 return pace_refused(&state, &plan, &who, why);
215 }
216 let response = import_admitted(&state, &body, &who, &plan).await;
217 if !response.status().is_success() {
218 crate::backend::vault::pace::refund(&who.agent, &spent);
220 }
221 response
222}
223
224async fn import_admitted(state: &AppState, body: &ImportBody, who: &Who, plan: &Plan) -> Response {
226 let mut answer = None;
229 if plan.share {
230 let wait = body.wait_secs.map(Duration::from_secs).unwrap_or(ANSWER_WAIT).min(ANSWER_WAIT_MAX);
231 let (ended, said) = super::vault_ask::ask(state, &who.pane, card(plan, who), wait, &headline(plan, who)).await;
232 if !ended.allowed() {
233 return refused(state, plan, who, ended.outcome(), StatusCode::FORBIDDEN, not_allowed(ended));
234 }
235 answer = said;
236 }
237 let minted = match credentials(state, who, plan.source.profile.as_deref().unwrap_or_default(), &plan.reason).await {
238 Ok(minted) => minted,
239 Err(why) => return refused(state, plan, who, "failed", StatusCode::SERVICE_UNAVAILABLE, why),
240 };
241 let via = minted.as_ref().map_or(Via::Host, Via::Session);
242 match aws_import::perform(&state.identity_store, &HostRunner, plan, via, &who.agent).await {
243 Ok(done) => {
244 let mut out = json!({ "status": "imported", "id": done.id, "label": done.label, "vault": done.vault });
245 if plan.share {
246 let ticked = answer.as_ref().and_then(|a| a.share) == Some(true);
247 let (shared, said) = share_made(state, who, &done.id, ticked).await;
248 out["shared"] = json!(shared);
249 out["share_note"] = json!(said);
250 }
251 super::vault_handlers::publish(state);
252 Json(out).into_response()
253 }
254 Err(why) => refused(state, plan, who, "failed", StatusCode::BAD_GATEWAY, why),
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261 use crate::backend::vault::aws_import::{Source, Target};
262
263 fn plan(replaces: bool) -> Plan {
264 let target = if replaces {
265 Target::Replace { id: "api-key-stripe".into(), created_at: 1, kind: "api-key", part: "value", label: "Stripe".into(), vault_id: "personal".into() }
266 } else {
267 Target::New { kind: "api-key", part: "value", label: "Staging database".into(), fields: Default::default(), vault_id: "personal".into() }
268 };
269 Plan {
270 source: Source { aws_secret_id: "staging/db".into(), key: Some("db.password".into()), user_key: None, region: Some("eu-west-1".into()), profile: Some("work-read".into()) },
271 target,
272 vault_name: "Personal".into(),
273 reason: "copy the staging database password for task 28071".into(),
274 refs: vec![],
275 share: false,
276 }
277 }
278
279 fn who() -> Who {
280 Who { agent: "builder".into(), pane: "block-1".into(), slug: "builder".into(), uid: "uid-1".into(), container: false }
281 }
282
283 #[test]
284 fn the_card_names_the_secret_the_vault_and_what_the_agent_says_and_offers_no_always() {
285 let in_container = super::card(&plan(false), &Who { container: true, ..who() });
286 let card = card(&plan(false), &who());
287 let import = card.import.as_ref().unwrap();
288 assert_eq!((import.service.as_str(), import.secret.as_str(), import.key.as_str(), import.region.as_str(), import.vault.as_str()), (SERVICE, "staging/db", "db.password", "eu-west-1", "Personal"));
289 assert!(!import.replaces && !card.offer_always && !card.needs_value);
290 assert_eq!((import.profile.as_str(), import.grant), ("work-read", false), "the card says which AWS login the read runs under");
291 assert!(in_container.import.unwrap().grant, "a container agent's profile is a grant");
292 assert_eq!((card.agent_reason.as_str(), card.block_id.as_str(), card.entry_id.as_str()), ("copy the staging database password for task 28071", "block-1", ""));
293 }
294
295 #[test]
296 fn a_login_imports_card_names_its_user_key_and_its_share_and_only_a_share_has_a_tick_to_answer() {
297 let mut login = plan(false);
298 login.source.user_key = Some("db.user".into());
299 login.share = true;
300 if let Target::New { kind, part, fields, .. } = &mut login.target {
301 *kind = "login";
302 *part = "password";
303 fields.insert("site".into(), "https://intranet.example.com".into());
304 }
305 let card = card(&login, &who());
306 let import = card.import.as_ref().unwrap();
307 assert_eq!((import.user_key.as_str(), import.site.as_str(), import.share), ("db.user", "https://intranet.example.com", true));
308 let tick = |card: &UseRequest, share: Option<bool>, decision| ticked_share(card, share.map(|s| json!(s)).as_ref(), decision);
309 assert_eq!(tick(&card, None, Decision::Once), Some(false), "an approval that sends no tick shares nothing");
310 assert_eq!(tick(&card, Some(true), Decision::Once), Some(true));
311 assert_eq!(tick(&card, Some(false), Decision::Once), Some(false));
312 assert_eq!(tick(&card, Some(false), Decision::Deny), None, "a no shares nothing and has no tick");
313 let plain = super::card(&plan(false), &who());
314 assert_eq!((plain.import.as_ref().unwrap().share, tick(&plain, Some(false), Decision::Once)), (false, None), "an import with no share has nothing to untick");
315 }
316
317 #[test]
318 fn silence_on_an_import_says_it_needed_a_yes_not_that_an_id_or_card_did() {
319 let said = not_allowed(Ended::Expired);
320 assert!(said.contains("needs a yes") && said.contains("nothing was copied") && !said.contains("ID or card"), "{said}");
321 assert_eq!(not_allowed(Ended::Denied), "the person said no: nothing was copied");
322 }
323
324 #[test]
325 fn an_import_is_a_new_entry_or_a_replacement_for_the_pace_and_a_share_card_never_goes_ahead_on_silence() {
326 use crate::backend::vault::pace::Act;
327 assert_eq!(act_of(&plan(false).target), Act::New);
328 assert_eq!(act_of(&plan(true).target), Act::Replace("api-key-stripe".into()));
329 assert!(crate::backend::vault::uses::goes_ahead_on_silence("api-key", false));
331 for plan in [plan(false), plan(true)] {
332 assert!(!crate::backend::vault::uses::goes_ahead(&card(&plan, &who())));
333 }
334 }
335}