1use std::collections::BTreeMap;
15use std::sync::{Arc, Mutex};
16
17use agentmux_common::time::now_ms;
18use serde::Serialize;
19use sha2::{Digest, Sha256};
20use zeroize::Zeroizing;
21
22use super::aws_import::{self, Source, Via};
23use super::{history, kinds, linked, record_line, seal, vaults, Line, PERSON};
24use crate::backend::storage::store::Store;
25use crate::backend::storage::vault::VaultRow;
26use crate::identity::aws_broker::mint::Runner;
27
28pub const KIND: &str = "source_kind";
30pub const LOCATION: &str = "source_location";
32pub const KEY: &str = "source_key";
34pub const REGION: &str = "source_region";
36pub const PROFILE: &str = "source_profile";
37pub const FIELDS: [&str; 5] = [KIND, LOCATION, KEY, REGION, PROFILE];
38
39pub const AWS_SECRET: &str = "aws-secret";
41pub const GITHUB_SECRET: &str = "github-secret";
44pub const OTHER: &str = "other";
46
47pub const TITLES: [(&str, &str); 5] = [
49 (KIND, "Machine copy kind"),
50 (LOCATION, "Machine copy location"),
51 (KEY, "Machine copy key"),
52 (REGION, "Machine copy region"),
53 (PROFILE, "Machine copy profile"),
54];
55
56pub const CHECKED: &str = "checked";
58pub const SAME: &str = "same";
59pub const DIFFERENT: &str = "different";
60pub const COULD_NOT_READ: &str = "could not read";
61pub const PRESENT: &str = "present";
63pub const CHANGED: &str = "changed since recorded";
64pub const MISSING: &str = "missing";
65pub const NOT_STARTED: &str = "not started";
67
68pub const AGENT_CHECKS_PER_HOUR: usize = 6;
71const HOUR_MS: i64 = 60 * 60 * 1000;
72const MAX_OTHER: usize = 300;
73
74pub fn is_field(name: &str) -> bool {
76 FIELDS.contains(&name)
77}
78
79#[derive(Debug, Clone, Default, PartialEq, Serialize)]
81pub struct Link {
82 pub kind: String,
83 pub location: String,
84 #[serde(skip_serializing_if = "String::is_empty")]
85 pub key: String,
86 #[serde(skip_serializing_if = "String::is_empty")]
87 pub region: String,
88 #[serde(skip_serializing_if = "String::is_empty")]
89 pub profile: String,
90}
91
92impl Link {
93 pub fn of(fields: &BTreeMap<String, String>) -> Option<Link> {
95 if !fields.keys().any(|k| is_field(k)) {
96 return None;
97 }
98 let get = |k: &str| fields.get(k).map(|v| v.trim().to_string()).unwrap_or_default();
99 Some(Link { kind: get(KIND), location: get(LOCATION), key: get(KEY), region: get(REGION), profile: get(PROFILE) })
100 }
101
102 pub fn of_row(row: &VaultRow) -> Option<Link> {
104 Link::of(&serde_json::from_str(&row.fields).unwrap_or_default())
105 }
106
107 pub fn text(&self) -> String {
109 if self.key.is_empty() {
110 format!("{}:{}", self.kind, self.location)
111 } else {
112 format!("{}:{}#{}", self.kind, self.location, self.key)
113 }
114 }
115
116 pub fn describe(&self) -> String {
118 let mut out = match self.kind.as_str() {
119 AWS_SECRET => format!("the AWS secret {}", self.location),
120 GITHUB_SECRET => return format!("the GitHub secret {} of {}", self.key, self.location),
121 _ => self.location.clone(),
122 };
123 for (name, value) in [("key", &self.key), ("region", &self.region), ("profile", &self.profile)] {
124 if !value.is_empty() {
125 out.push_str(&format!(", {name} {value}"));
126 }
127 }
128 out
129 }
130
131 pub(super) fn aws(&self) -> Option<Source> {
133 let some = |s: &String| (!s.is_empty()).then(|| s.clone());
134 (self.kind == AWS_SECRET).then(|| Source { aws_secret_id: self.location.clone(), key: some(&self.key), user_key: None, region: some(&self.region), profile: some(&self.profile) })
135 }
136}
137
138fn one_line(s: &str, max: usize) -> bool {
139 !s.is_empty() && s.chars().count() <= max && !s.chars().any(char::is_control)
140}
141
142fn name_like(s: &str, extra: &str) -> bool {
143 !s.is_empty() && s.len() <= 100 && !s.starts_with('-') && s.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c))
144}
145
146fn is_repository(s: &str) -> bool {
148 let (repo, env) = s.split_once('@').map_or((s, None), |(r, e)| (r, Some(e)));
149 let mut parts = repo.split('/');
150 let named = |p: Option<&str>| p.is_some_and(|p| name_like(p, "-_."));
151 named(parts.next()) && named(parts.next()) && parts.next().is_none() && env.is_none_or(|e| name_like(e, "-_."))
152}
153
154fn aws_ok(link: &Link) -> Result<(), String> {
156 let ok = |s: Source| aws_import::check_source(&s).is_ok();
157 let id = Source { aws_secret_id: link.location.clone(), ..Default::default() };
158 if !ok(id.clone()) {
159 return Err(format!("{LOCATION} is the AWS secret's name or ARN: letters, digits and /_+=.@:- only"));
160 }
161 if !link.key.is_empty() && !ok(Source { key: Some(link.key.clone()), ..id.clone() }) {
162 return Err(format!("{KEY} is a field of a JSON secret, as a dotted path (db.password): letters, digits, _ and - only"));
163 }
164 if !link.region.is_empty() && !ok(Source { region: Some(link.region.clone()), ..id.clone() }) {
165 return Err(format!("{REGION} is an AWS region such as us-east-1"));
166 }
167 if !link.profile.is_empty() && !ok(Source { profile: Some(link.profile.clone()), ..id }) {
168 return Err(format!("{PROFILE} is the name of an AWS profile on this computer, or of a container agent's AWS grant"));
169 }
170 Ok(())
171}
172
173pub fn validate(fields: &BTreeMap<String, String>) -> Result<(), String> {
176 let Some(link) = Link::of(fields) else { return Ok(()) };
177 if link.location.is_empty() {
178 return Err(format!("a machine copy needs {LOCATION}: where it is"));
179 }
180 if link.kind != AWS_SECRET && (!link.region.is_empty() || !link.profile.is_empty()) {
181 return Err(format!("{REGION} and {PROFILE} are for an {AWS_SECRET} only"));
182 }
183 match link.kind.as_str() {
184 AWS_SECRET => aws_ok(&link),
185 GITHUB_SECRET if !is_repository(&link.location) => Err(format!("{LOCATION} is the repository, owner/repo, or owner/repo@environment for an environment's secret")),
186 GITHUB_SECRET if !name_like(&link.key, "_") => Err(format!("{KEY} is the secret's name: letters, digits and _")),
187 GITHUB_SECRET => Ok(()),
188 OTHER if !one_line(&link.location, MAX_OTHER) || (!link.key.is_empty() && !one_line(&link.key, MAX_OTHER)) => {
189 Err(format!("{LOCATION} and {KEY} are one line each, at most {MAX_OTHER} characters"))
190 }
191 OTHER => Ok(()),
192 "" => Err(format!("a machine copy needs {KIND}: {AWS_SECRET}, {GITHUB_SECRET} or {OTHER}")),
193 other => Err(format!("{other:?} isn't a kind of machine copy: {AWS_SECRET}, {GITHUB_SECRET} or {OTHER}")),
194 }
195}
196
197pub fn settle_kind(fields: &mut BTreeMap<String, String>, asked: &BTreeMap<String, String>) {
202 if !asked.contains_key(KIND) {
203 return;
204 }
205 let left_over: &[&str] = match fields.get(KIND).map(String::as_str) {
206 None => &[LOCATION, KEY, REGION, PROFILE],
207 Some(AWS_SECRET) => &[],
208 Some(_) => &[REGION, PROFILE],
209 };
210 for name in left_over {
211 if !asked.contains_key(*name) {
212 fields.remove(*name);
213 }
214 }
215}
216
217pub fn carry_over(fields: &mut BTreeMap<String, String>, current: &VaultRow) {
219 if fields.keys().any(|k| is_field(k)) {
220 return;
221 }
222 let had: BTreeMap<String, String> = serde_json::from_str(¤t.fields).unwrap_or_default();
223 fields.extend(had.into_iter().filter(|(k, _)| is_field(k)));
224}
225
226#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
228#[ts(export, export_to = "../../../frontend/types/rpc/")]
229pub struct VaultSourceCheck {
230 #[ts(type = "number")]
231 pub at: i64,
232 pub outcome: String,
234}
235
236pub fn last_check(store: &Store, row: &VaultRow, link: &Link) -> Option<VaultSourceCheck> {
241 let newest = store.vault_activity_for_entry(&row.id, &[CHECKED], row.created_at, 1).ok()?.into_iter().next()?;
242 (newest.target == link.text() && newest.at >= row.updated_at).then_some(VaultSourceCheck { at: newest.at, outcome: newest.outcome })
243}
244
245#[derive(Debug, Clone, Default, PartialEq, Serialize)]
247pub struct AgentLink {
248 pub kind: String,
249 pub location: String,
250 #[serde(skip_serializing_if = "String::is_empty")]
251 pub key: String,
252 #[serde(skip_serializing_if = "Option::is_none")]
253 pub checked: Option<VaultSourceCheck>,
254 #[serde(skip_serializing_if = "std::ops::Not::not")]
256 pub link_only: bool,
257 #[serde(skip_serializing_if = "std::ops::Not::not")]
259 pub backed: bool,
260 #[serde(skip_serializing_if = "Vec::is_empty")]
262 pub readers: Vec<String>,
263 #[serde(skip_serializing_if = "Option::is_none")]
265 pub rotated: Option<String>,
266 #[serde(skip_serializing_if = "Vec::is_empty")]
268 pub copies: Vec<String>,
269}
270
271pub fn fields_for_agent(mut fields: BTreeMap<String, String>) -> BTreeMap<String, String> {
275 fields.remove(PROFILE);
276 if let Some(user) = fields.get_mut(super::signins::USERNAME) {
277 *user = super::signins::mask(user);
278 }
279 fields.remove(super::shares::SHARED);
281 fields
282}
283
284pub fn for_agent(store: &Store, row: &VaultRow) -> Option<AgentLink> {
285 let link = Link::of_row(row)?;
286 let checked = last_check(store, row, &link);
287 let fields: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
288 let lines = |name: &str| linked::lines(fields.get(name).map_or("", String::as_str)).into_iter().map(str::to_string).collect();
289 Some(AgentLink {
290 kind: link.kind,
291 location: link.location,
292 key: link.key,
293 checked,
294 link_only: linked::is_linked(&fields) && !linked::is_backed(&fields),
295 backed: linked::is_backed(&fields),
296 readers: lines(linked::READERS),
297 rotated: fields.get(linked::ROTATED).cloned(),
298 copies: lines(linked::COPIES),
299 })
300}
301
302static RUNNING: Mutex<BTreeMap<(usize, String), usize>> = Mutex::new(BTreeMap::new());
306
307#[derive(Debug, PartialEq)]
310pub struct Slot {
311 store: usize,
312 entry_id: String,
313}
314
315impl Drop for Slot {
316 fn drop(&mut self) {
317 let mut running = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
318 let key = (self.store, std::mem::take(&mut self.entry_id));
319 match running.get_mut(&key) {
320 Some(n) if *n > 1 => *n -= 1,
321 _ => {
322 running.remove(&key);
323 }
324 }
325 }
326}
327
328#[derive(Debug, Clone, PartialEq)]
330pub struct CheckPlan {
331 pub entry_id: String,
332 pub created_at: i64,
333 pub label: String,
334 pub part: &'static str,
336 pub link: Link,
337 pub only: bool,
339 pub copies: Vec<Link>,
341 pub actor: String,
343 pub reason: String,
344 pub slot: Option<Arc<Slot>>,
346 pub no_github: Option<String>,
349}
350
351impl CheckPlan {
352 pub fn describes(&self) -> bool {
355 self.only || self.link.kind == GITHUB_SECRET
356 }
357
358 pub fn github_places(&self) -> Vec<&Link> {
360 let copies = self.copies.iter().filter(|_| self.describes());
361 std::iter::once(&self.link).chain(copies).filter(|place| place.kind == GITHUB_SECRET).collect()
362 }
363}
364
365fn plan_of(row: VaultRow, actor: &str, reason: String) -> Result<CheckPlan, String> {
366 let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {} has an unknown kind", row.id))?;
367 let Some(link) = Link::of_row(&row) else {
368 return Err(format!("{} has no machine copy recorded: set {KIND}, {LOCATION} and {KEY} on it first", row.label));
369 };
370 let fields: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
371 let (only, copies) = (linked::is_linked(&fields), linked::copies(&fields));
372 Ok(CheckPlan { entry_id: row.id, created_at: row.created_at, label: row.label, part: kind.parts[0], link, only, copies, actor: actor.to_string(), reason, slot: None, no_github: None })
373}
374
375pub fn plan_for_person(store: &Store, id: &str) -> Result<CheckPlan, String> {
377 let row = store.vault_get(id.trim()).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
378 plan_of(row, PERSON, String::new())
379}
380
381pub fn plan_for_agent(store: &Store, id: &str, agent: &str, reason: Option<&str>) -> Result<CheckPlan, String> {
385 let reason = history::require_reason(reason)?;
386 let no_entry = || format!("no entry {id}");
387 let row = store.vault_get(id.trim()).map_err(|e| e.to_string())?.ok_or_else(no_entry)?;
388 if !vaults::entry_row_usable(store, &row.vault_id, Some(agent))? {
389 return Err(no_entry());
390 }
391 let key = (store as *const Store as usize, row.id.clone());
392 let slot = {
393 let mut running = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
394 let recent = store.vault_activity_for_entry(&row.id, &[CHECKED], now_ms() - HOUR_MS, 100).map_err(|e| e.to_string())?;
395 let done = recent.iter().filter(|r| r.actor != PERSON).count();
396 let now = running.get(&key).copied().unwrap_or(0);
397 if done >= AGENT_CHECKS_PER_HOUR {
398 return Err(format!("{} was checked {AGENT_CHECKS_PER_HOUR} times by agents in the last hour, which is the limit: its history has what they found", row.label));
399 }
400 if done + now >= AGENT_CHECKS_PER_HOUR {
401 return Err(format!(
402 "{} has {done} check(s) by agents in the last hour and {now} more running, which is the limit of {AGENT_CHECKS_PER_HOUR}: its history has what they find",
403 row.label
404 ));
405 }
406 *running.entry(key.clone()).or_insert(0) += 1;
407 Arc::new(Slot { store: key.0, entry_id: key.1 })
408 };
409 plan_of(row, agent, reason).map(|plan| CheckPlan { slot: Some(slot), ..plan })
410}
411
412#[derive(Debug, Clone, PartialEq)]
414pub enum Outcome {
415 Same,
416 Different,
417 CouldNotRead(String),
419 Present,
421 Changed(String),
423 Missing(String),
425 NotStarted(String),
427}
428
429impl Outcome {
430 pub fn word(&self) -> &'static str {
431 match self {
432 Outcome::Same => SAME,
433 Outcome::Different => DIFFERENT,
434 Outcome::CouldNotRead(_) => COULD_NOT_READ,
435 Outcome::Present => PRESENT,
436 Outcome::Changed(_) => CHANGED,
437 Outcome::Missing(_) => MISSING,
438 Outcome::NotStarted(_) => NOT_STARTED,
439 }
440 }
441
442 pub fn why(&self) -> &str {
443 match self {
444 Outcome::CouldNotRead(why) | Outcome::Changed(why) | Outcome::Missing(why) | Outcome::NotStarted(why) => why,
445 _ => "",
446 }
447 }
448
449 pub fn line(&self) -> String {
451 match self.why() {
452 "" => self.word().to_string(),
453 why => format!("{}: {why}", self.word()),
454 }
455 }
456}
457
458#[derive(Debug, Clone, PartialEq, Serialize)]
460pub struct Checked {
461 pub id: String,
462 pub label: String,
463 pub outcome: &'static str,
466 #[serde(skip_serializing_if = "String::is_empty")]
467 pub why: String,
468 pub source: String,
470 pub checked_at: i64,
471 #[serde(skip_serializing_if = "Option::is_none")]
473 pub last_changed: Option<String>,
474 #[serde(skip_serializing_if = "Option::is_none")]
476 pub rotation: Option<bool>,
477 #[serde(skip_serializing_if = "Vec::is_empty")]
479 pub copies: Vec<linked::CopyChecked>,
480 #[serde(skip_serializing_if = "Option::is_none")]
482 pub stored: Option<VaultSourceCheck>,
483}
484
485impl Checked {
486 pub fn of(plan: &CheckPlan, outcome: &Outcome) -> Checked {
488 Checked {
489 id: plan.entry_id.clone(),
490 label: plan.label.clone(),
491 outcome: outcome.word(),
492 why: outcome.why().to_string(),
493 source: plan.link.text(),
494 checked_at: now_ms(),
495 last_changed: None,
496 rotation: None,
497 copies: Vec::new(),
498 stored: None,
499 }
500 }
501}
502
503fn same(a: &[u8], b: &[u8]) -> bool {
505 let (a, b) = (Sha256::digest(a), Sha256::digest(b));
506 a.iter().zip(b.iter()).fold(0u8, |diff, (x, y)| diff | (x ^ y)) == 0
507}
508
509async fn read<R: Runner>(runner: &R, link: &Link, via: Via<'_>) -> Result<Zeroizing<String>, String> {
511 let Some(source) = link.aws() else {
512 return Err("this kind of place can't be read back from here".into());
513 };
514 let secret = aws_import::read_secret(runner, &source, via).await?;
515 aws_import::pick(secret, source.key.as_deref())
516}
517
518pub(super) fn as_planned(store: &Store, plan: &CheckPlan) -> Result<VaultRow, String> {
522 let Some(row) = store.vault_get(&plan.entry_id).ok().flatten().filter(|r| r.created_at == plan.created_at) else {
523 return Err("the entry was deleted while its machine copy was read".into());
524 };
525 if Link::of_row(&row).as_ref() != Some(&plan.link) {
526 return Err("where the entry's machine copy is was changed while it was read, so what was read says nothing about it: check again".into());
527 }
528 Ok(row)
529}
530
531fn compare(row: &VaultRow, plan: &CheckPlan, other: &Zeroizing<String>) -> Outcome {
533 let cant = |why: &str| Outcome::CouldNotRead(why.to_string());
534 let Ok(key) = seal::key(false) else { return cant("this computer's Vault key can't be read, so the entry's own value can't be opened") };
535 let Ok(parts) = seal::open(&key, &row.id, &row.sealed) else { return cant("the entry's own value doesn't open with this computer's Vault key") };
536 match parts.get(plan.part).filter(|v| !v.is_empty()) {
537 Some(ours) if same(ours.as_bytes(), other.as_bytes()) => Outcome::Same,
538 Some(_) => Outcome::Different,
539 None => cant("the entry has no value of its own to compare"),
540 }
541}
542
543pub fn conclude(store: &Store, plan: &CheckPlan, outcome: &Outcome) -> Checked {
545 let source = plan.link.text();
546 record_line(store, Line { entry_id: &plan.entry_id, label: &plan.label, actor: &plan.actor, action: CHECKED, target: &source, outcome: &outcome.line(), reason: &plan.reason });
547 Checked::of(plan, outcome)
548}
549
550fn finish(store: &Store, plan: &CheckPlan, other: Result<Zeroizing<String>, String>) -> Checked {
552 let outcome = match (as_planned(store, plan), &other) {
553 (Err(why), _) => Outcome::CouldNotRead(why),
554 (Ok(row), Ok(value)) => compare(&row, plan, value),
555 (Ok(_), Err(why)) => Outcome::CouldNotRead(why.clone()),
556 };
557 conclude(store, plan, &outcome)
558}
559
560pub async fn check<R: Runner>(store: &Arc<Store>, runner: &R, plan: &CheckPlan, via: Via<'_>) -> Checked {
563 let stopped = Checked::of(plan, &Outcome::CouldNotRead("the check stopped before it finished".into()));
564 let (store, plan) = (Arc::clone(store), plan.clone());
565 if plan.describes() {
568 let found = linked::describe(runner, &plan, via).await;
569 return tokio::task::spawn_blocking(move || linked::finish(&store, &plan, found)).await.unwrap_or(stopped);
570 }
571 let other = read(runner, &plan.link, via).await;
572 tokio::task::spawn_blocking(move || finish(&store, &plan, other)).await.unwrap_or(stopped)
573}
574
575pub fn check_blocking<R: Runner>(store: &Store, runner: &R, plan: &CheckPlan, via: Via<'_>) -> Result<Checked, String> {
577 let runtime = tokio::runtime::Handle::try_current().map_err(|_| "the check can't run here".to_string())?;
578 if plan.describes() {
579 return Ok(linked::finish(store, plan, runtime.block_on(linked::describe(runner, plan, via))));
580 }
581 Ok(finish(store, plan, runtime.block_on(read(runner, &plan.link, via))))
582}
583
584#[cfg(test)]
585#[path = "source_link_tests.rs"]
586mod tests;