1use std::collections::BTreeMap;
14use std::sync::Arc;
15
16use agentmux_common::time::now_ms;
17use serde::Deserialize;
18use zeroize::{Zeroize, Zeroizing};
19
20use super::source_link::AWS_SECRET;
21use super::{history, kinds, record_row, seal, validate, vaults, versions, NewEntry, Parts};
22use crate::backend::storage::store::Store;
23use crate::backend::storage::vault::{VaultActivityRow, VaultRow};
24use crate::identity::aws_broker::mint::{login_lapsed, Minted, RunError, RunSpec, Runner, RECIPE_TIMEOUT};
25use crate::identity::aws_broker::policy::Policy;
26
27pub const IMPORTED: &str = "imported";
29pub const SERVICE: &str = "AWS Secrets Manager";
31const MAX_SECRET_ID: usize = 512;
32const MAX_KEY: usize = 200;
33const MAX_PROFILE: usize = 128;
34const SAID_KEPT: usize = 200;
36
37#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
39pub struct Source {
40 pub aws_secret_id: String,
41 #[serde(default)]
43 pub key: Option<String>,
44 #[serde(default)]
47 pub user_key: Option<String>,
48 #[serde(default)]
49 pub region: Option<String>,
50 #[serde(default)]
52 pub profile: Option<String>,
53}
54
55#[derive(Debug, Clone, Deserialize)]
57pub struct ImportRequest {
58 pub source: Source,
59 #[serde(default)]
61 pub kind: String,
62 #[serde(default)]
63 pub label: String,
64 #[serde(default)]
65 pub fields: BTreeMap<String, String>,
66 #[serde(default)]
68 pub vault: Option<String>,
69 #[serde(default)]
71 pub id: Option<String>,
72 #[serde(default)]
73 pub reason: Option<String>,
74 #[serde(default)]
76 pub refs: Vec<String>,
77 #[serde(default)]
79 pub share: bool,
80}
81
82#[derive(Debug, Clone, PartialEq)]
84pub enum Target {
85 New { kind: &'static str, part: &'static str, label: String, fields: BTreeMap<String, String>, vault_id: String },
86 Replace { id: String, created_at: i64, kind: &'static str, part: &'static str, label: String, vault_id: String },
87 Link { kind: &'static str, label: String, fields: BTreeMap<String, String>, vault_id: String },
89}
90
91#[derive(Debug, Clone, PartialEq)]
93pub struct Plan {
94 pub source: Source,
95 pub target: Target,
96 pub vault_name: String,
97 pub reason: String,
98 pub refs: Vec<String>,
99 pub share: bool,
101}
102
103impl Plan {
104 pub fn from_text(&self) -> String {
108 match (&self.source.key, &self.source.user_key) {
109 (Some(key), Some(user)) => format!("{AWS_SECRET}:{}#{key}+{user}", self.source.aws_secret_id),
110 (Some(key), None) => format!("{AWS_SECRET}:{}#{key}", self.source.aws_secret_id),
111 _ => format!("{AWS_SECRET}:{}", self.source.aws_secret_id),
112 }
113 }
114
115 pub fn site(&self) -> &str {
117 match &self.target {
118 Target::New { fields, .. } => fields.get(super::signins::SITE).map_or("", String::as_str),
119 _ => "",
120 }
121 }
122
123 pub fn label(&self) -> &str {
124 match &self.target {
125 Target::New { label, .. } | Target::Replace { label, .. } | Target::Link { label, .. } => label,
126 }
127 }
128
129 pub fn entry_id(&self) -> &str {
131 match &self.target {
132 Target::New { .. } | Target::Link { .. } => "",
133 Target::Replace { id, .. } => id,
134 }
135 }
136
137 pub fn kind(&self) -> &'static str {
138 match &self.target {
139 Target::New { kind, .. } | Target::Replace { kind, .. } | Target::Link { kind, .. } => kind,
140 }
141 }
142
143 pub fn is_link(&self) -> bool {
145 matches!(self.target, Target::Link { .. })
146 }
147}
148
149fn plain(s: &str, max: usize, allowed: impl Fn(char) -> bool) -> bool {
150 !s.is_empty() && s.chars().count() <= max && !s.starts_with('-') && s.chars().all(allowed)
151}
152
153fn is_region(s: &str) -> bool {
155 let parts: Vec<&str> = s.split('-').collect();
156 s.len() <= 25
157 && parts.len() >= 3
158 && parts[0].len() == 2
159 && parts.iter().take(parts.len() - 1).all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_lowercase()))
160 && parts.last().is_some_and(|n| !n.is_empty() && n.len() <= 2 && n.bytes().all(|b| b.is_ascii_digit()))
161}
162
163pub fn check_source(source: &Source) -> Result<Source, String> {
166 let clean = |s: &Option<String>| s.as_deref().map(str::trim).filter(|v| !v.is_empty()).map(str::to_string);
167 let id = source.aws_secret_id.trim();
168 if !plain(id, MAX_SECRET_ID, |c| c.is_ascii_alphanumeric() || "/_+=.@:-".contains(c)) {
169 return Err("aws_secret_id is the secret's name or ARN: letters, digits and /_+=.@:- only, at most 512 characters".into());
170 }
171 let key = clean(&source.key);
172 if key.as_deref().is_some_and(|k| !is_dotted(k)) {
173 return Err("key is a field of a JSON secret, as a dotted path (db.password): letters, digits, _ and - only".into());
174 }
175 let user_key = clean(&source.user_key);
176 if let Some(user) = &user_key {
177 if !is_dotted(user) {
178 return Err("user_key is the field of a JSON secret that holds the user name, as a dotted path (db.user): letters, digits, _ and - only".into());
179 }
180 if key.is_none() {
181 return Err("user_key picks the user name out of a JSON secret: name key too, the field that holds the password".into());
182 }
183 if key.as_deref() == Some(user.as_str()) {
184 return Err("key and user_key are the same field: the password and the user name are two fields of the secret".into());
185 }
186 }
187 let (region, profile) = check_place(&source.region, &source.profile)?;
188 Ok(Source { aws_secret_id: id.to_string(), key, user_key, region, profile })
189}
190
191fn is_dotted(k: &str) -> bool {
193 k.split('.').all(|seg| plain(seg, MAX_KEY, |c| c.is_ascii_alphanumeric() || c == '_' || c == '-')) && k.chars().count() <= MAX_KEY
194}
195
196pub fn check_place(region: &Option<String>, profile: &Option<String>) -> Result<(Option<String>, Option<String>), String> {
198 let clean = |s: &Option<String>| s.as_deref().map(str::trim).filter(|v| !v.is_empty()).map(str::to_string);
199 let region = clean(region);
200 if region.as_deref().is_some_and(|r| !is_region(r)) {
201 return Err("region is an AWS region such as us-east-1".into());
202 }
203 let profile = clean(profile);
204 if profile.as_deref().is_some_and(|p| !plain(p, MAX_PROFILE, |c| c.is_ascii_alphanumeric() || "_.@:/+=-".contains(c))) {
205 return Err("profile is the name of an AWS grant (a container agent) or of a profile on this computer (a native one)".into());
206 }
207 Ok((region, profile))
208}
209
210pub fn check(store: &Store, req: &ImportRequest, agent: &str) -> Result<Plan, String> {
213 let reason = history::require_reason(req.reason.as_deref())?;
214 let source = check_source(&req.source)?;
215 let refs = req.refs.iter().map(|r| r.trim().to_string()).filter(|r| !r.is_empty()).collect();
216 let id = req.id.as_deref().map(str::trim).filter(|i| !i.is_empty());
217 let (target, vault_id) = match id {
218 Some(id) => replace_target(store, id, &req.kind, agent)?,
219 None => new_target(store, req, agent)?,
220 };
221 if source.user_key.is_some() || req.share {
222 check_login_import(&target, &source, req.share)?;
223 }
224 let vault_name = store.vault_info(&vault_id).map_err(|e| e.to_string())?.map(|v| v.name).unwrap_or_default();
225 Ok(Plan { source, target, vault_name, reason, refs, share: req.share })
226}
227
228fn check_login_import(target: &Target, source: &Source, share: bool) -> Result<(), String> {
231 let Target::New { kind: "login", fields, .. } = target else {
232 return Err("user_key and share are for a new login: give kind login and leave id out".into());
233 };
234 if source.user_key.is_some() && fields.contains_key(super::signins::USERNAME) {
235 return Err("the user name comes from user_key: leave fields.username out".into());
236 }
237 if share {
238 super::shares::check_shareable("login", fields)?;
239 if super::shares::answers_prompt(fields) {
242 return Err("a sign-in for a site's HTTP prompt or a proxy can't be shared with its import: ask for it afterwards with Vault share".into());
243 }
244 let site = fields.get(super::signins::SITE).map_or("", String::as_str);
245 if !agentmux_common::allowed_origins::target_origin(site).is_some_and(|o| o == site && o.starts_with("https://")) {
246 return Err("a login to share names its site as an exact https origin, such as https://example.com".into());
247 }
248 }
249 Ok(())
250}
251
252fn replace_target(store: &Store, id: &str, kind: &str, agent: &str) -> Result<(Target, String), String> {
253 let no_entry = || format!("no entry {id}");
254 let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(no_entry)?;
255 if !vaults::entry_row_usable(store, &row.vault_id, Some(agent))? {
256 return Err(no_entry());
257 }
258 let info = kinds::kind(&row.kind).ok_or_else(|| format!("entry {id} has an unknown kind"))?;
259 if let Some(refusal) = super::linked::takes_no_value(&row, "import the value as a new entry") {
260 return Err(refusal);
261 }
262 if !kind.trim().is_empty() && kind.trim() != row.kind {
263 return Err(format!("{id} is a {} entry: leave kind out to replace its value", row.kind));
264 }
265 let vault_id = row.vault_id.clone();
266 Ok((Target::Replace { id: row.id, created_at: row.created_at, kind: info.name, part: info.parts[0], label: row.label, vault_id: vault_id.clone() }, vault_id))
267}
268
269fn new_target(store: &Store, req: &ImportRequest, agent: &str) -> Result<(Target, String), String> {
270 let kind = kinds::kind(&req.kind).ok_or_else(|| {
271 let names: Vec<&str> = kinds::KINDS.iter().map(|k| k.name).collect();
272 format!("import makes a new entry of a kind: one of {}, or give id to replace an entry's value", names.join(", "))
273 })?;
274 let label = req.label.trim().to_string();
275 let fields: BTreeMap<String, String> = req.fields.iter().map(|(k, v)| (k.clone(), v.trim().to_string())).filter(|(_, v)| !v.is_empty()).collect();
276 validate(kind, &label, &fields, &[], &Parts::default())?;
277 let vault_id = match req.vault.as_deref().map(str::trim).filter(|v| !v.is_empty()) {
278 Some(which) => vaults::resolve(store, which, Some(Some(agent)))?.id,
279 None => vaults::default_for(store, Some(agent))?,
280 };
281 Ok((Target::New { kind: kind.name, part: kind.parts[0], label, fields, vault_id: vault_id.clone() }, vault_id))
282}
283
284pub fn check_grant(policy: &Result<Option<Arc<Policy>>, String>, profile: Option<&str>, slug: &str) -> Result<(), String> {
287 let Some(profile) = profile else {
288 return Err("a container agent names the AWS grant to read under: source.profile (aws configure list-profiles lists yours)".into());
289 };
290 let policy = match policy {
291 Ok(Some(p)) if !p.grants.is_empty() => p,
292 Ok(_) => return Err("AWS isn't shared with container agents on this machine, so there is nothing to read with".into()),
293 Err(_) => return Err("the AWS grants file on this machine doesn't parse, so AWS can't be shared until a person fixes it".into()),
294 };
295 let Some(grant) = policy.grants.get(profile) else {
296 return Err(format!("No AWS grant named '{profile}'. This machine shares: {}.", policy.names().join(", ")));
297 };
298 if grant.disabled {
299 return Err(format!("The grant '{profile}' is switched off on this machine."));
300 }
301 if grant.hold.is_some() {
302 return Err(format!("The grant '{profile}' was added or widened in the grants file and has not been allowed yet. A native agent can allow it (Identity aws_grants)."));
303 }
304 if !grant.open_to(slug) {
305 return Err(format!("The grant '{profile}' isn't open to you. Ask the person to add you to it."));
306 }
307 Ok(())
308}
309
310#[derive(Clone, Copy)]
312pub enum Via<'a> {
313 Host,
315 Session(&'a Minted),
317}
318
319fn argv(source: &Source, via: &Via<'_>) -> Vec<String> {
320 let mut args: Vec<String> = ["secretsmanager", "get-secret-value", "--secret-id", source.aws_secret_id.as_str(), "--query", "SecretString", "--output", "json"]
321 .iter()
322 .map(|s| s.to_string())
323 .collect();
324 if let Some(region) = &source.region {
325 args.extend(["--region".to_string(), region.clone()]);
326 }
327 if let (Via::Host, Some(profile)) = (via, &source.profile) {
328 args.extend(["--profile".to_string(), profile.clone()]);
329 }
330 args
331}
332
333pub const NO_SUCH_SECRET: &str = "AWS has no secret by that id, in that region";
335const DESCRIPTION: &str = "{changed: LastChangedDate, rotation: RotationEnabled, deleted: DeletedDate}";
337
338fn describe_argv(source: &Source, via: &Via<'_>) -> Vec<String> {
340 let mut args = argv(source, via);
341 args[1] = "describe-secret".to_string();
342 args[5] = DESCRIPTION.to_string();
343 args
344}
345
346#[derive(Debug, Clone, Default, PartialEq)]
348pub struct Described {
349 pub changed: Option<chrono::NaiveDate>,
351 pub rotation: Option<bool>,
352 pub deleted: bool,
354}
355
356fn day_of(v: &serde_json::Value) -> Option<chrono::NaiveDate> {
358 match v {
359 serde_json::Value::String(s) => chrono::DateTime::parse_from_rfc3339(s.trim()).ok().map(|t| t.with_timezone(&chrono::Utc).date_naive()),
360 serde_json::Value::Number(n) => chrono::DateTime::from_timestamp(n.as_f64()? as i64, 0).map(|t| t.date_naive()),
361 _ => None,
362 }
363}
364
365pub async fn describe_secret<R: Runner>(runner: &R, source: &Source, via: Via<'_>) -> Result<Described, String> {
368 let stdout = run_cli(runner, describe_argv(source, &via), source, via).await?;
369 let said: serde_json::Value = serde_json::from_slice(stdout.as_slice()).map_err(|_| "AWS answered with something that isn't a secret's description".to_string())?;
370 Ok(Described { changed: day_of(&said["changed"]), rotation: said["rotation"].as_bool(), deleted: !said["deleted"].is_null() })
371}
372
373pub async fn read_secret<R: Runner>(runner: &R, source: &Source, via: Via<'_>) -> Result<Zeroizing<String>, String> {
376 let stdout = run_cli(runner, argv(source, &via), source, via).await?;
377 let text: Option<String> = serde_json::from_slice(stdout.as_slice()).map_err(|_| "AWS answered with something that isn't a secret's text".to_string())?;
379 let text = Zeroizing::new(text.ok_or("that secret is binary, not text: import copies text secrets only")?);
380 Ok(text)
381}
382
383pub fn read_value_blocking<R: Runner>(runner: &R, source: &Source) -> Result<Zeroizing<String>, String> {
389 let read = async {
390 let secret = read_secret(runner, source, Via::Host).await?;
391 pick(secret, source.key.as_deref())
392 };
393 match tokio::runtime::Handle::try_current() {
394 Ok(handle) => handle.block_on(read),
395 Err(_) => tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())?.block_on(read),
396 }
397}
398
399async fn run_cli<R: Runner>(runner: &R, args: Vec<String>, source: &Source, via: Via<'_>) -> Result<Zeroizing<Vec<u8>>, String> {
402 let Some(program) = runner.which("aws") else {
403 return Err("this computer has no AWS CLI (v2.9 or newer), which an import reads with".into());
404 };
405 let mut env = vec![("AWS_PAGER".to_string(), String::new()), ("PYTHONUTF8".to_string(), "1".to_string()), ("PYTHONIOENCODING".to_string(), "utf-8".to_string())];
409 if let Via::Session(s) = &via {
410 env.push(("AWS_ACCESS_KEY_ID".into(), s.access_key_id.to_string()));
411 env.push(("AWS_SECRET_ACCESS_KEY".into(), s.secret_access_key.to_string()));
412 env.push(("AWS_SESSION_TOKEN".into(), s.session_token.to_string()));
413 }
414 let spec = RunSpec { program, args, env, timeout: RECIPE_TIMEOUT };
415 let out = match runner.run(spec).await {
416 Ok(out) => out,
417 Err(RunError::TimedOut) => return Err(format!("AWS took too long to answer ({} s). Try again in a minute.", RECIPE_TIMEOUT.as_secs())),
418 Err(RunError::Spawn(_)) => return Err("couldn't run the AWS CLI on this computer".into()),
419 };
420 let stdout = Zeroizing::new(out.stdout);
421 if !out.success {
422 return Err(aws_said(&out.stderr, source));
423 }
424 Ok(stdout)
425}
426
427fn without_accounts(line: &str) -> String {
429 let mut out = String::with_capacity(line.len());
430 let mut digits = String::new();
431 for c in line.chars().chain(std::iter::once(' ')) {
432 if c.is_ascii_digit() {
433 digits.push(c);
434 continue;
435 }
436 out.push_str(if digits.len() >= 12 { "…" } else { &digits });
437 digits.clear();
438 out.push(c);
439 }
440 out.pop();
441 out
442}
443
444fn aws_said(stderr: &str, source: &Source) -> String {
446 let s = stderr.to_lowercase();
447 if s.contains("accessdenied") || s.contains("not authorized") || s.contains("explicit deny") {
448 "AWS refused: this identity can't read that secret".into()
449 } else if s.contains("resourcenotfound") || s.contains("can't find the specified secret") {
450 NO_SUCH_SECRET.into()
451 } else if s.contains("decryptionfailure") || (s.contains("kms") && s.contains("denied")) {
452 "AWS refused: this identity can't decrypt that secret".into()
453 } else if login_lapsed(stderr) {
454 let profile = source.profile.as_deref().map(|p| format!(" --profile {p}")).unwrap_or_default();
455 format!("The host's AWS login has lapsed. A person runs `aws sso login{profile}` on this computer.")
456 } else if s.contains("unable to locate credentials") || (s.contains("could not be found") && s.contains("profile")) {
457 "there is no AWS login on this computer for that profile".into()
458 } else if s.contains("could not connect") || s.contains("could not resolve") || s.contains("timed out") {
459 "couldn't reach AWS from this computer".into()
460 } else {
461 let first = stderr.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("it exited with an error and said nothing");
462 let cut: String = without_accounts(first).chars().take(SAID_KEPT).collect();
463 format!("AWS said: {cut}")
464 }
465}
466
467fn wipe(v: &mut serde_json::Value) {
469 match v {
470 serde_json::Value::String(s) => s.zeroize(),
471 serde_json::Value::Array(items) => items.iter_mut().for_each(wipe),
472 serde_json::Value::Object(map) => map.iter_mut().for_each(|(_, item)| wipe(item)),
473 _ => {}
474 }
475}
476
477fn at_key(json: &serde_json::Value, key: &str) -> Result<Zeroizing<String>, String> {
479 let mut at = json;
480 for step in key.split('.') {
481 at = at.get(step).ok_or_else(|| format!("that secret has no key {key}"))?;
482 }
483 match at {
484 serde_json::Value::String(s) => Ok(Zeroizing::new(s.clone())),
485 serde_json::Value::Number(n) => Ok(Zeroizing::new(n.to_string())),
486 _ => Err(format!("{key} is not a string or a number, which is all a Vault entry holds")),
487 }
488}
489
490pub fn pick(secret: Zeroizing<String>, key: Option<&str>) -> Result<Zeroizing<String>, String> {
493 let value = match key {
494 None => secret,
495 Some(key) => {
496 let mut json: serde_json::Value = serde_json::from_str(&secret).map_err(|_| "that secret isn't JSON, so a key can't be picked from it".to_string())?;
497 let picked = at_key(&json, key);
498 wipe(&mut json);
499 picked?
500 }
501 };
502 if value.trim().is_empty() {
503 return Err("that secret is empty".into());
504 }
505 if value.len() > super::MAX_PART {
506 return Err("that secret is longer than 1 MiB, which a Vault entry can't hold".into());
507 }
508 Ok(value)
509}
510
511pub fn pick_both(secret: Zeroizing<String>, key: Option<&str>, user_key: Option<&str>) -> Result<(Zeroizing<String>, Option<Zeroizing<String>>), String> {
515 let Some(user_key) = user_key else { return Ok((pick(secret, key)?, None)) };
516 let key = key.ok_or("user_key needs key, the field that holds the password")?;
517 let mut json: serde_json::Value = serde_json::from_str(&secret).map_err(|_| "that secret isn't JSON, so keys can't be picked from it".to_string())?;
518 let picked = at_key(&json, key).and_then(|password| password_at(password, key)).and_then(|password| at_key(&json, user_key).and_then(|user| user_name_at(user, user_key)).map(|user| (password, Some(user))));
519 wipe(&mut json);
520 picked
521}
522
523fn password_at(value: Zeroizing<String>, key: &str) -> Result<Zeroizing<String>, String> {
524 if value.trim().is_empty() {
525 return Err(format!("{key} is empty"));
526 }
527 if value.len() > super::MAX_PART {
528 return Err(format!("{key} is longer than 1 MiB, which a Vault entry can't hold"));
529 }
530 Ok(value)
531}
532
533fn user_name_at(value: Zeroizing<String>, key: &str) -> Result<Zeroizing<String>, String> {
534 let user = Zeroizing::new(value.trim().to_string());
535 if user.is_empty() {
536 return Err(format!("{key} is empty: a login needs a user name"));
537 }
538 if user.len() > super::MAX_FIELD {
539 return Err(format!("{key} is longer than {} bytes, which a user name can't be", super::MAX_FIELD));
540 }
541 if user.chars().any(char::is_control) {
542 return Err(format!("{key} holds a control character, which a user name can't"));
543 }
544 Ok(user)
545}
546
547#[derive(Debug, PartialEq, serde::Serialize)]
549pub struct Imported {
550 pub id: String,
551 pub label: String,
552 pub vault: String,
553}
554
555pub fn store_value(store: &Store, plan: &Plan, value: &Zeroizing<String>, username: Option<&Zeroizing<String>>, agent: &str) -> Result<Imported, String> {
558 let (id, label) = match &plan.target {
559 Target::New { kind, part, label, fields, vault_id } => {
560 let mut parts = Parts::default();
561 parts.0.insert(part.to_string(), value.to_string());
562 let mut fields = fields.clone();
563 if let Some(user) = username {
565 fields.insert(super::signins::USERNAME.to_string(), user.to_string());
566 }
567 let entry = NewEntry { kind: kind.to_string(), label: label.clone(), fields, tags: Vec::new(), parts };
568 super::insert_unrecorded(store, entry, vault_id)?
569 }
570 Target::Replace { id, created_at, part, label, .. } => {
571 replace_main(store, id, *created_at, part, value, agent)?;
572 (id.clone(), label.clone())
573 }
574 Target::Link { label, .. } => return Err(format!("{label} is a link, which holds no value")),
575 };
576 note(store, plan, &id, &label, agent, "done");
577 super::agent_set::mark(store, &id, agent);
579 if matches!(&plan.target, Target::New { kind: "login", fields, .. } if fields.contains_key(super::signins::SITE)) {
580 super::agent_set::mark_site(store, &id, agent);
582 }
583 Ok(Imported { id, label, vault: plan.vault_name.clone() })
584}
585
586fn replace_main(store: &Store, id: &str, created_at: i64, part: &str, value: &Zeroizing<String>, agent: &str) -> Result<(), String> {
587 let key = seal::key(false)?;
588 let gone = || "the entry was deleted while the secret was read, so nothing was saved".to_string();
589 let row = store.vault_get(id).map_err(|e| e.to_string())?.filter(|r| r.created_at == created_at).ok_or_else(gone)?;
590 let mut parts = seal::open(&key, &row.id, &row.sealed)?;
591 if let Some(mut old) = parts.0.insert(part.to_string(), value.to_string()) {
592 old.zeroize();
593 }
594 let kept = versions::of(&row, agent, IMPORTED);
595 versions::prune(store);
596 let (was, was_fields) = (row.sealed.clone(), row.fields.clone());
597 let changed = VaultRow { sealed: seal::seal(&key, &row.id, &parts)?, updated_at: now_ms(), ..row };
598 if !store.vault_update_kept(&changed, &was, &was_fields, Some(&kept)).map_err(|e| e.to_string())? {
599 return Err(format!("{} changed while the secret was read, so nothing was saved", changed.label));
600 }
601 Ok(())
602}
603
604pub fn note(store: &Store, plan: &Plan, id: &str, label: &str, agent: &str, outcome: &str) {
606 record_row(
607 store,
608 VaultActivityRow {
609 entry_id: id.into(),
610 entry_label: label.into(),
611 actor: agent.into(),
612 action: IMPORTED.into(),
613 target: plan.from_text(),
614 outcome: outcome.into(),
615 reason: plan.reason.clone(),
616 refs: history::refs_text(&plan.refs),
617 ..Default::default()
618 },
619 );
620}
621
622pub async fn perform<R: Runner>(store: &Arc<Store>, runner: &R, plan: &Plan, via: Via<'_>, agent: &str) -> Result<Imported, String> {
624 let secret = read_secret(runner, &plan.source, via).await?;
625 let (value, username) = pick_both(secret, plan.source.key.as_deref(), plan.source.user_key.as_deref())?;
626 let (store, plan, agent) = (Arc::clone(store), plan.clone(), agent.to_string());
627 tokio::task::spawn_blocking(move || store_value(&store, &plan, &value, username.as_ref(), &agent)).await.map_err(|e| e.to_string())?
628}
629
630#[cfg(test)]
631#[path = "aws_import_tests.rs"]
632mod tests;