Skip to main content

agentmux_srv_core/backend/vault/
aws_import.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Vault` `import`: an agent has the Vault copy a secret from AWS Secrets Manager, so the person never types it and
5//! the agent never sees it (docs/specs/SPEC_VAULT_PARITY_ENTRY_HISTORY_REASONS_AND_IMPORT_2026_11_06.md §7).
6//!
7//! This is the part with no server in it: checking what the agent asked for (before anything is asked of the person),
8//! reading the secret with the host's AWS CLI, picking the value out and keeping it. The value lives in `Zeroizing`
9//! buffers from the CLI's stdout to the sealed row. The CLI's stdout is never logged, kept or put in an error; the
10//! error sentences are fixed ones, with at most a cleaned first line of the CLI's stderr (AWS's own words, which hold
11//! no value).
12
13use 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
27/// The Activity action, and what a version replaced by an import is marked with.
28pub const IMPORTED: &str = "imported";
29/// The service the card names.
30pub const SERVICE: &str = "AWS Secrets Manager";
31const MAX_SECRET_ID: usize = 512;
32const MAX_KEY: usize = 200;
33const MAX_PROFILE: usize = 128;
34/// How much of AWS's own error line an unknown failure shows.
35const SAID_KEPT: usize = 200;
36
37/// Where the secret is: its id (or ARN), the field of a JSON secret to take, and how to reach AWS.
38#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
39pub struct Source {
40    pub aws_secret_id: String,
41    /// A field of a JSON secret, as a dotted path (`db.password`); the whole secret when left out.
42    #[serde(default)]
43    pub key: Option<String>,
44    /// For a new login: the field of the same secret that holds its user name, as a dotted path. `key` is then the
45    /// password's field.
46    #[serde(default)]
47    pub user_key: Option<String>,
48    #[serde(default)]
49    pub region: Option<String>,
50    /// A container agent: the AWS grant to read under. A native agent: the host's AWS profile (its default when left out).
51    #[serde(default)]
52    pub profile: Option<String>,
53}
54
55/// What an agent asks `import` for.
56#[derive(Debug, Clone, Deserialize)]
57pub struct ImportRequest {
58    pub source: Source,
59    /// The kind of the new entry; not needed with `id`.
60    #[serde(default)]
61    pub kind: String,
62    #[serde(default)]
63    pub label: String,
64    #[serde(default)]
65    pub fields: BTreeMap<String, String>,
66    /// The Vault for a new entry, by name or id; the agent's first when left out.
67    #[serde(default)]
68    pub vault: Option<String>,
69    /// Replace this entry's main value instead of making a new entry.
70    #[serde(default)]
71    pub id: Option<String>,
72    #[serde(default)]
73    pub reason: Option<String>,
74    /// Task numbers, PRs and the like, kept with the history row.
75    #[serde(default)]
76    pub refs: Vec<String>,
77    /// For a new login saved for a site: share it with the agent that asks, if the person leaves that ticked.
78    #[serde(default)]
79    pub share: bool,
80}
81
82/// Where the value goes.
83#[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    /// A linked entry (`super::linked`): the place is recorded and no value is read. Only a batch makes one.
88    Link { kind: &'static str, label: String, fields: BTreeMap<String, String>, vault_id: String },
89}
90
91/// An import that has been checked: nothing in it needs the store again, except to put the value in.
92#[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    /// The new login is shared with the agent that asked, unless the person unticks it on the card.
100    pub share: bool,
101}
102
103impl Plan {
104    /// The Activity line's target: `aws-secret:<id>` and `#<key>` when a field is picked (`#<key>+<user_key>` for a login's
105    /// two), as a link's line and a check's line name an AWS place (`source_link`), so the history's Where column names
106    /// it one way.
107    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    /// The site of the new login, when it has one.
116    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    /// The entry replaced, if the import replaces one.
130    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    /// Whether this is a link: an entry that records where the key lives, made without reading it.
144    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
153/// An AWS region's name: `us-east-1`, `eu-central-2`, `us-gov-west-1`.
154fn 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
163/// `source` with its optional parts trimmed, or why it can't be used. Narrow character sets: the id and key go to the
164/// CLI as arguments and to the person's card, so nothing else is let through.
165pub 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
191/// A field of a JSON secret named by a dotted path.
192fn 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
196/// The region and the profile a read runs under, trimmed, or why one can't be used.
197pub 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
210/// Every check of an import, before the person is asked: the reason, the source, and the entry or Vault the value goes
211/// in, for an agent that may use only the Vaults it is let into.
212pub 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
228/// What a login import asks beyond any other: a new login (not a replacement, not another kind), a user name that comes
229/// from `user_key` and not from the fields, and for a share a login saved for an exact https site that can be shared.
230fn 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        // An import's share is the form login's (B3): a sign-in the browser answers a prompt with is asked for on its
240        // own card, which says what that share does (A11).
241        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
284/// Whether a container agent may read under the grant `profile`, before the person is asked (the broker checks again
285/// when it mints): the grant exists, is on, and is open to the agent.
286pub 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/// How the CLI is given its credentials.
311#[derive(Clone, Copy)]
312pub enum Via<'a> {
313    /// The host's own AWS setup (a native agent), under `profile` if one is named.
314    Host,
315    /// A broker session minted for a container agent's grant.
316    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
333/// What AWS says of a secret that isn't there.
334pub const NO_SUCH_SECRET: &str = "AWS has no secret by that id, in that region";
335/// What a description asks for: when the secret last changed, whether it rotates, and whether it is being deleted.
336const DESCRIPTION: &str = "{changed: LastChangedDate, rotation: RotationEnabled, deleted: DeletedDate}";
337
338/// [`argv`] for the secret's description instead of its value: the same secret, region and profile.
339fn 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/// A secret as its description gives it: dates and a setting, nothing of its value.
347#[derive(Debug, Clone, Default, PartialEq)]
348pub struct Described {
349    /// The day (UTC) it last changed, when AWS says.
350    pub changed: Option<chrono::NaiveDate>,
351    pub rotation: Option<bool>,
352    /// It is scheduled for deletion.
353    pub deleted: bool,
354}
355
356/// A timestamp as the CLI prints one: RFC 3339 text (v2), or seconds since 1970 (v1).
357fn 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
365/// Reads a secret's description: metadata only, so the value never leaves AWS. A secret that isn't there fails with
366/// [`NO_SUCH_SECRET`].
367pub 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
373/// Runs the AWS CLI's Secrets Manager read and returns the secret's text. The CLI's stdout is the secret: it is wiped
374/// when this returns, and nothing of it goes into an error.
375pub 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    // `null` is a secret kept as binary: SecretString is empty then.
378    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
383/// The value at `source`, for a caller that isn't async: the secret's text, or the string or number at `source.key` in a
384/// JSON one, read with the host's own AWS login. This is the one reader of Secrets Manager the Vault's backed entries
385/// and the identity model's `SecretRef::SecretsManager` share. Call it on a blocking thread (a use already runs on one);
386/// with no runtime (a test) it makes its own for the one call. The value is wiped when dropped and nothing of it goes
387/// into an error.
388pub 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
399/// Runs the AWS CLI with `args` as `via` says and returns its stdout, which may be a secret: it is wiped when dropped,
400/// and nothing of it goes into an error.
401async 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    // The CLI is Python: on Windows it writes its output in the console's code page, which fails on a character outside
406    // it ('charmap' codec can't encode) in any field of the secret, before the one wanted is picked. The child's
407    // environment is rebuilt from an allowlist, so UTF-8 is set here, and stdout is read as UTF-8 below.
408    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
427/// 12-digit runs (account numbers) cut out of a line of AWS's.
428fn 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
444/// What went wrong, from the CLI's stderr, in a sentence the agent is told.
445fn 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
467/// Overwrites every string in `v`.
468fn 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
477/// The string or number at the dotted `key` in `json`.
478fn 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
490/// The value to keep: the whole secret, or the string or number at `key` in a JSON one. What is parsed and not kept is
491/// wiped before it is dropped.
492pub 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
511/// A login's two values out of one JSON secret: the password at `key` and the user name at `user_key`. Both are picked
512/// before anything is written, and a key that is missing, holds no text or holds nothing is refused by name. What is
513/// parsed and not kept is wiped. With no `user_key` this is [`pick`].
514pub 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/// What an import made or changed.
548#[derive(Debug, PartialEq, serde::Serialize)]
549pub struct Imported {
550    pub id: String,
551    pub label: String,
552    pub vault: String,
553}
554
555/// Puts `value` in: a new entry, or the main value of the one named, whose old value is kept 7 days as a version. The
556/// `imported` line goes in with the agent's reason and references; it holds no value.
557pub 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            // A login's user name is a plain field of the entry, the one the Vault pane shows to the person.
564            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    // Nobody was asked, so the value is the agent's until the person has seen it (`agent_set`).
578    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        // A site the agent chose, too: a use there never goes ahead on silence either (R9).
581        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
604/// The record of an import's outcome (`done`, `denied`, `failed`): who, from where, why. No value.
605pub 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
622/// Reads the secret, picks the value and keeps it. The store is written on the blocking pool.
623pub 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;