1use std::collections::BTreeMap;
14
15use agentmux_common::time::now_ms;
16use chrono::NaiveDate;
17use serde::Serialize;
18
19use super::aws_import::{self, Described, Imported, Plan, Source, Target, Via, NO_SUCH_SECRET};
20use super::source_link::{self, CheckPlan, Checked, Link, Outcome, VaultSourceCheck, AWS_SECRET, GITHUB_SECRET, OTHER};
21use super::{expiry, github_secret, history, insert_unrecorded, record_line, record_row, signins, Line, NewEntry, Parts};
22use crate::backend::storage::store::Store;
23use crate::backend::storage::vault::{VaultActivityRow, VaultRow};
24use crate::identity::aws_broker::mint::Runner;
25
26pub const LINK: &str = "link";
28pub const ONLY: &str = "only";
29pub const BACKED: &str = "backed";
32pub const READERS: &str = "readers";
34pub const ROTATED: &str = "rotated";
36pub const COPIES: &str = "copies";
38pub const FIELDS: [&str; 4] = [LINK, READERS, ROTATED, COPIES];
39pub const TITLES: [(&str, &str); 3] = [(READERS, "Read by"), (ROTATED, "Last changed"), (COPIES, "Also kept at")];
41pub const KIND_TITLE: &str = "Linked entry kind";
43pub const MAX_READERS: usize = 8;
44pub const MAX_COPIES: usize = 4;
45const MAX_LINE: usize = 200;
46
47pub const LINKED: &str = "linked";
49pub const CHECKED_COPY: &str = "checked a copy";
52pub const UNCHECKED_DAYS: i64 = 30;
54const DAY_MS: i64 = 24 * 60 * 60 * 1000;
55pub const SET_WHEN_MADE: &str = "whether an entry is a link (it holds no value) is set when it is made: make a new entry instead";
57const NOT_FROM_HERE: &str = "this kind of place can't be described from here: only an AWS secret and a CI secret are";
58const NOT_UNDER_AWS: &str = "an AWS copy is described under the entry's own AWS place, and this entry's place isn't in AWS";
59
60pub fn is_field(name: &str) -> bool {
62 FIELDS.contains(&name)
63}
64
65pub fn is_linked(fields: &BTreeMap<String, String>) -> bool {
67 fields.get(LINK).is_some_and(|v| v == ONLY || v == BACKED)
68}
69
70pub fn mark(fields: &BTreeMap<String, String>) -> Option<&str> {
73 fields.get(LINK).map(|v| v.trim()).filter(|v| !v.is_empty())
74}
75
76pub fn is_backed(fields: &BTreeMap<String, String>) -> bool {
78 fields.get(LINK).is_some_and(|v| v == BACKED)
79}
80
81pub fn is_backed_row(row: &VaultRow) -> bool {
82 is_backed(&fields_of(row))
83}
84
85fn fields_of(row: &VaultRow) -> BTreeMap<String, String> {
86 serde_json::from_str(&row.fields).unwrap_or_default()
87}
88
89pub fn is_linked_row(row: &VaultRow) -> bool {
90 is_linked(&fields_of(row))
91}
92
93pub fn lines(text: &str) -> Vec<&str> {
95 text.lines().map(str::trim).filter(|l| !l.is_empty()).collect()
96}
97
98pub fn place_text(link: &Link) -> String {
100 match link.key.as_str() {
101 "" => format!("{}: {}", link.kind, link.location),
102 key => format!("{}: {}#{key}", link.kind, link.location),
103 }
104}
105
106fn copy_of(line: &str) -> Result<Link, String> {
108 let wrong = |why: &str| format!("a line of {COPIES} is `kind: location#key`, with the kind {AWS_SECRET}, {GITHUB_SECRET} or {OTHER}; {:?} isn't one ({why})", history::one_line(line, 60));
109 let (kind, rest) = line.split_once(':').ok_or_else(|| wrong("it names no kind"))?;
110 let (location, key) = rest.rsplit_once('#').unwrap_or((rest, ""));
111 let named = [(source_link::KIND, kind), (source_link::LOCATION, location), (source_link::KEY, key)];
112 let fields: BTreeMap<String, String> = named.into_iter().map(|(k, v)| (k.to_string(), v.trim().to_string())).filter(|(_, v)| !v.is_empty()).collect();
113 source_link::validate(&fields).map_err(|why| wrong(&why))?;
114 Link::of(&fields).ok_or_else(|| wrong("it names no place"))
115}
116
117pub fn copies(fields: &BTreeMap<String, String>) -> Vec<Link> {
120 lines(fields.get(COPIES).map_or("", String::as_str)).into_iter().filter_map(|l| copy_of(l).ok()).collect()
121}
122
123pub fn validate(fields: &BTreeMap<String, String>, has_value: bool) -> Result<(), String> {
127 let linked = match fields.get(LINK).map(String::as_str) {
128 None => false,
129 Some(ONLY | BACKED) => true,
130 Some(_) => return Err(format!("{LINK} is \"{ONLY}\", for an entry that records where a key lives and holds no value, \"{BACKED}\", for one that reads its value from AWS Secrets Manager at each use, or is left out")),
131 };
132 if linked && Link::of(fields).is_none() {
133 return Err(format!("a linked entry says where the key lives: set {} and {}", source_link::KIND, source_link::LOCATION));
134 }
135 if is_backed(fields) && !Link::of(fields).is_some_and(|l| l.kind == AWS_SECRET) {
136 return Err(format!("a backed entry is read from an AWS secret: set {} to {AWS_SECRET}", source_link::KIND));
137 }
138 if linked && has_value {
139 return Err("a linked entry holds no value: leave the value out, or leave link out to keep the value in the Vault".into());
140 }
141 if linked && fields.contains_key(signins::SITE) {
143 return Err(format!("a linked entry holds no password, so it is not a saved sign-in: leave {} out", signins::SITE));
144 }
145 if let Some(date) = fields.get(ROTATED) {
146 if !linked {
147 return Err(format!("{ROTATED} is for a linked entry: the Vault's own history says when a value it holds was changed"));
148 }
149 expiry::parse(date).map_err(|_| format!("{ROTATED} is the date the key was last changed, as YYYY-MM-DD"))?;
150 }
151 let readers = lines(fields.get(READERS).map_or("", String::as_str));
152 if readers.len() > MAX_READERS || readers.iter().any(|l| l.chars().count() > MAX_LINE) {
153 return Err(format!("{READERS} is who or what reads the key, one line each: at most {MAX_READERS} lines of {MAX_LINE} characters"));
154 }
155 let places = lines(fields.get(COPIES).map_or("", String::as_str));
156 if places.len() > MAX_COPIES {
157 return Err(format!("{COPIES} is the other places the key is kept, one line each: at most {MAX_COPIES}"));
158 }
159 places.into_iter().try_for_each(|line| copy_of(line).map(|_| ()))
160}
161
162pub fn no_value(row: &VaultRow) -> Option<String> {
165 let fields = fields_of(row);
166 if !is_linked(&fields) || is_backed(&fields) {
168 return None;
169 }
170 let place = Link::of(&fields).map(|l| place_text(&l)).unwrap_or_default();
171 Some(format!("This entry holds no value: the key is kept at {place}. Ask the person, or use the access you already have there."))
172}
173
174pub fn takes_no_value(row: &VaultRow, instead: &str) -> Option<String> {
177 if is_backed_row(row) {
178 return Some(format!("{} is backed by AWS Secrets Manager, which holds its value: change the secret there, not here ({instead} is for an entry that keeps its own value)", row.label));
179 }
180 is_linked_row(row).then(|| format!("{} is a linked entry, which holds no value: {instead}", row.label))
181}
182
183pub fn about(fields: &BTreeMap<String, String>) -> String {
187 let joined = |name: &str| lines(fields.get(name).map_or("", String::as_str)).join("; ");
188 let said = [("Read by", joined(READERS)), ("Last changed", joined(ROTATED)), ("Also kept at", joined(COPIES))];
189 said.into_iter().filter(|(_, text)| !text.is_empty()).map(|(what, text)| format!("{what}: {text}.")).collect::<Vec<_>>().join("\n")
190}
191
192pub fn fields_for(source: &Source, said: &BTreeMap<String, String>) -> BTreeMap<String, String> {
196 fields_marked(ONLY, source, said)
197}
198
199pub fn fields_for_backed(source: &Source, said: &BTreeMap<String, String>) -> BTreeMap<String, String> {
201 fields_marked(BACKED, source, said)
202}
203
204fn fields_marked(mark: &str, source: &Source, said: &BTreeMap<String, String>) -> BTreeMap<String, String> {
205 let mut fields: BTreeMap<String, String> = said.iter().filter(|(k, _)| !source_link::is_field(k)).map(|(k, v)| (k.clone(), v.trim().to_string())).filter(|(_, v)| !v.is_empty()).collect();
206 let place = [
207 (LINK, Some(mark)),
208 (source_link::KIND, Some(AWS_SECRET)),
209 (source_link::LOCATION, Some(source.aws_secret_id.as_str())),
210 (source_link::KEY, source.key.as_deref()),
211 (source_link::REGION, source.region.as_deref()),
212 (source_link::PROFILE, source.profile.as_deref()),
213 ];
214 fields.extend(place.into_iter().filter_map(|(k, v)| Some((k.to_string(), v?.to_string()))));
215 fields
216}
217
218pub fn note(store: &Store, plan: &Plan, id: &str, label: &str, agent: &str, outcome: &str) {
220 let place = match &plan.target {
221 Target::Link { fields, .. } => Link::of(fields).map(|l| l.text()).unwrap_or_default(),
222 _ => plan.from_text(),
223 };
224 record_row(
225 store,
226 VaultActivityRow {
227 entry_id: id.into(),
228 entry_label: label.into(),
229 actor: agent.into(),
230 action: LINKED.into(),
231 target: place,
232 outcome: outcome.into(),
233 reason: plan.reason.clone(),
234 refs: history::refs_text(&plan.refs),
235 ..Default::default()
236 },
237 );
238}
239
240pub fn make(store: &Store, plan: &Plan, agent: &str) -> Result<Imported, String> {
243 let Target::Link { kind, label, fields, vault_id } = &plan.target else {
244 return Err(format!("{} is not a link", plan.label()));
245 };
246 let entry = NewEntry { kind: kind.to_string(), label: label.clone(), fields: fields.clone(), tags: Vec::new(), parts: Parts::default() };
247 let (id, label) = insert_unrecorded(store, entry, vault_id)?;
248 note(store, plan, &id, &label, agent, "done");
249 Ok(Imported { id, label, vault: plan.vault_name.clone() })
250}
251
252#[derive(Debug, Clone, PartialEq, Serialize)]
254pub struct CopyChecked {
255 pub place: String,
257 pub outcome: &'static str,
259 #[serde(skip_serializing_if = "String::is_empty")]
260 pub why: String,
261 #[serde(skip_serializing_if = "Option::is_none")]
263 pub stored: Option<VaultSourceCheck>,
264}
265
266#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
268#[ts(export, export_to = "../../../frontend/types/rpc/")]
269pub struct VaultCopyCheck {
270 pub place: String,
272 #[serde(skip_serializing_if = "Option::is_none")]
274 #[ts(optional)]
275 pub checked: Option<VaultSourceCheck>,
276 pub cannot: String,
278}
279
280fn cannot_describe(copy: &Link, own: &str) -> Option<&'static str> {
284 match (copy.kind.as_str(), own) {
285 (GITHUB_SECRET, _) | (AWS_SECRET, AWS_SECRET) => None,
286 (AWS_SECRET, _) => Some(NOT_UNDER_AWS),
287 _ => Some(NOT_FROM_HERE),
288 }
289}
290
291pub fn copy_checks(store: &Store, row: &VaultRow) -> Vec<VaultCopyCheck> {
295 let fields = fields_of(row);
296 let named: Vec<(&str, Link)> = lines(fields.get(COPIES).map_or("", String::as_str)).into_iter().filter_map(|line| Some((line, copy_of(line).ok()?))).collect();
298 if named.is_empty() {
299 return Vec::new();
300 }
301 let own = Link::of(&fields).map(|link| link.kind).unwrap_or_default();
302 let checks = copy_lines(store, row);
303 named
304 .iter()
305 .map(|(written, copy)| match cannot_describe(copy, &own) {
306 Some(why) => VaultCopyCheck { place: written.to_string(), checked: None, cannot: why.into() },
307 None => VaultCopyCheck { place: written.to_string(), checked: newest_of(&checks, copy), cannot: String::new() },
308 })
309 .collect()
310}
311
312fn copy_lines(store: &Store, row: &VaultRow) -> Vec<VaultActivityRow> {
315 store.vault_activity_for_entry(&row.id, &[CHECKED_COPY], row.updated_at, (MAX_COPIES * 4) as i64).unwrap_or_default()
316}
317
318fn newest_of(checks: &[VaultActivityRow], copy: &Link) -> Option<VaultSourceCheck> {
320 checks.iter().find(|line| line.target == copy.text()).map(|line| VaultSourceCheck { at: line.at, outcome: line.outcome.clone() })
321}
322
323pub struct Found {
326 place: Option<Result<Described, String>>,
327 copies: Vec<(Link, Option<Result<Described, String>>)>,
328}
329
330async fn describe_place<R: Runner>(runner: &R, plan: &CheckPlan, link: &Link, via: Via<'_>) -> Option<Result<Described, String>> {
332 Some(match (link.kind.as_str(), link.aws()) {
333 (GITHUB_SECRET, _) if plan.no_github.is_some() => return None,
334 (GITHUB_SECRET, _) => github_secret::describe(runner, link).await,
335 (_, Some(source)) => aws_import::describe_secret(runner, &source, via).await,
336 (_, None) => Err(NOT_FROM_HERE.into()),
337 })
338}
339
340pub async fn describe<R: Runner>(runner: &R, plan: &CheckPlan, via: Via<'_>) -> Found {
345 let copies = plan.copies.iter().map(|copy| async move {
348 let described = match cannot_describe(copy, &plan.link.kind) {
349 Some(why) => Some(Err(why.into())),
350 None if copy.kind == AWS_SECRET => describe_place(runner, plan, &Link { region: plan.link.region.clone(), profile: plan.link.profile.clone(), ..copy.clone() }, via).await,
351 None => describe_place(runner, plan, copy, via).await,
352 };
353 (copy.clone(), described)
354 });
355 let (place, copies) = futures_util::future::join(describe_place(runner, plan, &plan.link, via), futures_util::future::join_all(copies)).await;
356 Found { place, copies }
357}
358
359fn outcome_of(described: &Result<Described, String>, recorded: Option<NaiveDate>) -> Outcome {
361 match (described, recorded) {
362 (Err(why), _) if why == NO_SUCH_SECRET || why == github_secret::NO_SUCH_SECRET => Outcome::Missing(why.clone()),
363 (Err(why), _) => Outcome::CouldNotRead(why.clone()),
364 (Ok(d), _) if d.deleted => Outcome::Missing("the secret is scheduled for deletion".into()),
365 (Ok(Described { changed: Some(changed), .. }), Some(recorded)) if *changed > recorded => Outcome::Changed(format!("the place last changed on {changed}, after the {recorded} recorded")),
366 (Ok(_), _) => Outcome::Present,
367 }
368}
369
370fn not_started(plan: &CheckPlan, stored: &Option<VaultSourceCheck>) -> Outcome {
372 let why = plan.no_github.as_deref().unwrap_or("no read was started");
373 let last = if stored.is_some() { "The newest stored result is in `stored`." } else { "It has not been checked yet." };
374 Outcome::NotStarted(format!("{why} {last}"))
375}
376
377fn overtaken(store: &Store, plan: &CheckPlan, found: &Found, why: String) -> Checked {
380 let outcome = Outcome::CouldNotRead(why);
381 let mut checked = if found.place.is_some() { source_link::conclude(store, plan, &outcome) } else { Checked::of(plan, &outcome) };
382 let read = found.copies.iter().filter(|(copy, described)| described.is_some() && cannot_describe(copy, &plan.link.kind).is_none());
383 checked.copies = read.map(|(copy, _)| CopyChecked { place: place_text(copy), outcome: outcome.word(), why: outcome.why().to_string(), stored: None }).collect();
384 checked
385}
386
387pub fn finish(store: &Store, plan: &CheckPlan, found: Found) -> Checked {
391 let row = match source_link::as_planned(store, plan) {
392 Ok(row) => row,
393 Err(why) => return overtaken(store, plan, &found, why),
394 };
395 let recorded = fields_of(&row).get(ROTATED).and_then(|date| expiry::parse(date).ok());
396 let earlier = copy_lines(store, &row);
397 let mut copies = Vec::with_capacity(found.copies.len());
398 for (copy, described) in &found.copies {
399 let Some(described) = described else {
400 let stored = newest_of(&earlier, copy);
401 let outcome = not_started(plan, &stored);
402 copies.push(CopyChecked { place: place_text(copy), outcome: outcome.word(), why: outcome.why().to_string(), stored });
403 continue;
404 };
405 let outcome = outcome_of(described, recorded);
406 if cannot_describe(copy, &plan.link.kind).is_none() {
407 record_line(store, Line { entry_id: &plan.entry_id, label: &plan.label, actor: &plan.actor, action: CHECKED_COPY, target: ©.text(), outcome: &outcome.line(), reason: &plan.reason });
408 }
409 copies.push(CopyChecked { place: place_text(copy), outcome: outcome.word(), why: outcome.why().to_string(), stored: None });
410 }
411 let mut checked = match &found.place {
412 Some(place) => source_link::conclude(store, plan, &outcome_of(place, recorded)),
413 None => {
414 let stored = source_link::last_check(store, &row, &plan.link);
415 Checked { stored: stored.clone(), ..Checked::of(plan, ¬_started(plan, &stored)) }
416 }
417 };
418 if let Some(Ok(described)) = &found.place {
419 checked.last_changed = described.changed.map(|day| day.to_string());
420 checked.rotation = described.rotation;
421 }
422 checked.copies = copies;
423 checked
424}
425
426#[derive(Debug, Clone, Copy, PartialEq)]
428pub enum Standing {
429 Checked,
431 NeedsALook,
433 Unchecked,
435}
436
437fn stands(checked: Option<&VaultSourceCheck>, now: i64) -> (Standing, bool) {
440 let unchecked = checked.is_none_or(|c| now - c.at > UNCHECKED_DAYS * DAY_MS);
441 let how = match checked {
442 Some(c) if c.outcome.starts_with(source_link::CHANGED) || c.outcome.starts_with(source_link::MISSING) => Standing::NeedsALook,
443 Some(_) if !unchecked => Standing::Checked,
444 _ => Standing::Unchecked,
445 };
446 (how, unchecked)
447}
448
449pub fn standing(store: &Store, row: &VaultRow) -> Option<(Standing, bool)> {
451 let fields = fields_of(row);
452 if !is_linked(&fields) {
453 return None;
454 }
455 let checked = Link::of(&fields).and_then(|link| source_link::last_check(store, row, &link));
456 Some(stands(checked.as_ref(), now_ms()))
457}
458
459#[cfg(test)]
460#[path = "linked_tests.rs"]
461mod tests;