Skip to main content

agentmux_srv_core/backend/vault/
source_link.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An entry's machine copy: where a copy of its value lives outside the Vault (a secret store a service reads, a CI
5//! secret), and a check that says whether that copy still equals the entry's value. A first step toward an entry's
6//! "backing" (docs/specs/SPEC_VAULT_SHARED_ACROSS_MACHINES_LAN_AND_CLOUD_2026_11_01.md ยง11.1).
7//!
8//! The link is plain fields (`source_*`), allowed on every kind and never a value. The check reads the other place
9//! with the access the asker already has, compares inside srv, and answers `same`, `different` or `could not read`
10//! with why: neither value, nor a length or a hash of one, is in an answer, an error or a history line. A refusal to
11//! read is the answer, not something to get around. A CI secret's value can't be read back by anyone, so its check
12//! reads the secret's listing entry and says whether it is there and when it last changed (`github_secret`).
13
14use 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
28/// The kind of place the copy is in.
29pub const KIND: &str = "source_kind";
30/// Where in it: an AWS secret's name or ARN, a repository (`owner/repo`, or `owner/repo@environment`), or free text.
31pub const LOCATION: &str = "source_location";
32/// The key there: a JSON secret's dotted key, a CI secret's name.
33pub const KEY: &str = "source_key";
34/// An AWS secret's region and the profile (or a container agent's grant) it is read under.
35pub const REGION: &str = "source_region";
36pub const PROFILE: &str = "source_profile";
37pub const FIELDS: [&str; 5] = [KIND, LOCATION, KEY, REGION, PROFILE];
38
39/// A secret in AWS Secrets Manager: the one kind whose value a check can read.
40pub const AWS_SECRET: &str = "aws-secret";
41/// A repository's or an environment's Actions secret. Nothing can read its value back; a check reads its listing
42/// entry (`github_secret`).
43pub const GITHUB_SECRET: &str = "github-secret";
44/// Anywhere else, as the person describes it.
45pub const OTHER: &str = "other";
46
47/// The fields as a KeePass export names them, so a database written from the Vault brings the link back.
48pub 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
56/// The Activity action of a check.
57pub const CHECKED: &str = "checked";
58pub const SAME: &str = "same";
59pub const DIFFERENT: &str = "different";
60pub const COULD_NOT_READ: &str = "could not read";
61/// What a check of a linked entry's place finds, from the place's description alone (`linked`).
62pub const PRESENT: &str = "present";
63pub const CHANGED: &str = "changed since recorded";
64pub const MISSING: &str = "missing";
65/// No read was started for this asker: the answer carries the newest stored result instead.
66pub const NOT_STARTED: &str = "not started";
67
68/// How many checks agents get of one entry in an hour, all agents together: a check answers one bit about the sealed
69/// value, so it is not something to ask in a loop.
70pub const AGENT_CHECKS_PER_HOUR: usize = 6;
71const HOUR_MS: i64 = 60 * 60 * 1000;
72const MAX_OTHER: usize = 300;
73
74/// Whether `name` is one of the link's fields, which every kind of entry may have.
75pub fn is_field(name: &str) -> bool {
76    FIELDS.contains(&name)
77}
78
79/// Where an entry's machine copy is. Empty parts are not set.
80#[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    /// The link in `fields`, if any of its fields is set.
94    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    /// The link of an entry's row.
103    pub fn of_row(row: &VaultRow) -> Option<Link> {
104        Link::of(&serde_json::from_str(&row.fields).unwrap_or_default())
105    }
106
107    /// One line for a history row: `aws-secret:staging/app#db.password`.
108    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    /// The place as a person reads it, for the question asked before an agent changes it.
117    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    /// What an import-style read of it takes, for an AWS secret.
132    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
146/// `owner/repo`, or `owner/repo@environment`.
147fn 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
154/// An AWS secret's parts, each held to what the import takes (they go to the AWS CLI as arguments).
155fn 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
173/// Whether the link in `fields` is one the Vault keeps: a known kind, a place written the way that kind is, and no
174/// part the kind has no use for. No link at all is fine.
175pub 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
197/// An update that names a new kind of place takes the parts the new kind has no use for with it, unless the update
198/// names them itself: an AWS secret's region and profile when the place becomes any other kind, and every part when
199/// the kind is emptied, which takes the link off. Without it an agent that moved a link off AWS was refused over a
200/// region the old place had left behind, and had to know to clear it (found in the Linux look check, 2026-11-14).
201pub 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
217/// An import that replaces an entry and names no machine copy leaves the entry's own link as it is.
218pub 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(&current.fields).unwrap_or_default();
223    fields.extend(had.into_iter().filter(|(k, _)| is_field(k)));
224}
225
226/// The newest check of the entry's link as it is now: when, and what it found.
227#[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    /// `same`, `different`, or `could not read: <why>`.
233    pub outcome: String,
234}
235
236/// The newest check of `row`'s link, when it is of the entry as it is now. A check of a place the link no longer
237/// names says nothing about this one, and neither does a check made before the entry last changed: the change may
238/// be the link's region or profile, which the history line does not name (an agent reads the history, and is never
239/// told the profile), or the entry's own value, which an older "same" was not compared with.
240pub 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/// The link as `list` gives it to an agent: the place, and the newest check. Which login reads it is left out.
246#[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    /// The entry is a link (`linked`): it holds no value, and the key is only at the place. A use of it is refused.
255    #[serde(skip_serializing_if = "std::ops::Not::not")]
256    pub link_only: bool,
257    /// The entry is backed by AWS Secrets Manager: the Vault keeps no value, and each use reads the key at the place.
258    #[serde(skip_serializing_if = "std::ops::Not::not")]
259    pub backed: bool,
260    /// Who or what reads the key, as recorded.
261    #[serde(skip_serializing_if = "Vec::is_empty")]
262    pub readers: Vec<String>,
263    /// When the key was last changed, as recorded.
264    #[serde(skip_serializing_if = "Option::is_none")]
265    pub rotated: Option<String>,
266    /// Other places the same key is kept.
267    #[serde(skip_serializing_if = "Vec::is_empty")]
268    pub copies: Vec<String>,
269}
270
271/// An entry's plain fields as an agent is given them: all of them but the login its machine copy is read under, and a
272/// login's user name only masked (its first two characters and `***`, as `Browser` `signin` names it): an agent can set
273/// a user name, and sign in with it, and can't read one back.
274pub 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    // Who else a login is shared with is the person's business; the agent is told only whether it is (`shared_with_you`).
280    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
302/// Agents' checks that are planned and have not written their history line yet, by store and entry. They count
303/// toward the hour's limit with the lines already written: counted by the lines alone, checks started together each
304/// saw fewer than the limit, and all of them ran.
305static RUNNING: Mutex<BTreeMap<(usize, String), usize>> = Mutex::new(BTreeMap::new());
306
307/// An agent's place among an entry's checks of the hour: held by the plan (and its clones) from the moment the check
308/// is allowed until the plan is dropped, which is after the check's line is written.
309#[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/// A check that has been allowed to run: which entry, which place, for whom.
329#[derive(Debug, Clone, PartialEq)]
330pub struct CheckPlan {
331    pub entry_id: String,
332    pub created_at: i64,
333    pub label: String,
334    /// The entry's main part, which the copy is compared with.
335    pub part: &'static str,
336    pub link: Link,
337    /// The entry is a link: it holds no value, so the check reads the place's description and compares nothing.
338    pub only: bool,
339    /// The other places the key is kept, which a linked entry's check describes too.
340    pub copies: Vec<Link>,
341    /// The agent's id, or the person.
342    pub actor: String,
343    pub reason: String,
344    /// An agent's check holds its place in the hour's limit; the person's has none.
345    pub slot: Option<Arc<Slot>>,
346    /// Why this asker's check may not start a read of a CI secret, and what to do instead; `None` when it may. The
347    /// read uses the GitHub login of the person on this computer, so who may start one is decided by the caller.
348    pub no_github: Option<String>,
349}
350
351impl CheckPlan {
352    /// The check reads descriptions and compares no value: the entry is a link, or its place is a CI secret, whose
353    /// value nothing can read back.
354    pub fn describes(&self) -> bool {
355        self.only || self.link.kind == GITHUB_SECRET
356    }
357
358    /// The CI secrets this check would read: the entry's own place and its other places, when it describes them.
359    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
375/// The person's check, from the Vault pane.
376pub 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
381/// An agent's check of an entry in a Vault it may use: its reason is required, and agents together get
382/// [`AGENT_CHECKS_PER_HOUR`] checks of one entry in an hour, counting the ones still running. The count and the new
383/// check's place are taken under one lock, so checks asked for at the same moment are counted one after the other.
384pub 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/// What a check found.
413#[derive(Debug, Clone, PartialEq)]
414pub enum Outcome {
415    Same,
416    Different,
417    /// Why neither could be said: the other place refused, has no such key, or is a kind nothing reads back.
418    CouldNotRead(String),
419    /// A linked entry's place is there, and did not change after the date the entry records.
420    Present,
421    /// The place changed after the date the entry records: what it says about that.
422    Changed(String),
423    /// The place is not there, or is being deleted: which.
424    Missing(String),
425    /// No read was started for this asker: why, and what to do. Never a history line.
426    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    /// The history line's outcome: the word, and why when there is one to give.
450    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/// A check's answer: ids, names, the outcome and when. No value.
459#[derive(Debug, Clone, PartialEq, Serialize)]
460pub struct Checked {
461    pub id: String,
462    pub label: String,
463    /// `same`, `different` or `could not read`; for a linked entry or a CI secret `present`, `changed since
464    /// recorded`, `missing` or `could not read`; `not started` when no read was started for this asker.
465    pub outcome: &'static str,
466    #[serde(skip_serializing_if = "String::is_empty")]
467    pub why: String,
468    /// The place that was read, as the history names it.
469    pub source: String,
470    pub checked_at: i64,
471    /// A linked entry: the day the place last changed, as the place says.
472    #[serde(skip_serializing_if = "Option::is_none")]
473    pub last_changed: Option<String>,
474    /// A linked entry: whether the place rotates the key itself, when the place says.
475    #[serde(skip_serializing_if = "Option::is_none")]
476    pub rotation: Option<bool>,
477    /// A linked entry: what was found at each other place the key is kept.
478    #[serde(skip_serializing_if = "Vec::is_empty")]
479    pub copies: Vec<linked::CopyChecked>,
480    /// `not started`: the newest check of the place as the entry is now, when there is one.
481    #[serde(skip_serializing_if = "Option::is_none")]
482    pub stored: Option<VaultSourceCheck>,
483}
484
485impl Checked {
486    /// The answer for `plan`'s entry and place, as of now.
487    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
503/// Whether two values are equal, in time that does not depend on where they differ: their digests are compared, whole.
504fn 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
509/// The copy at `link`, read with the asker's access. An AWS secret is the one place read today.
510async 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
518/// The entry as it is once the read has come back, when it is still the entry the check was planned for and its
519/// link is still the one that was read. A read takes seconds, and the link may change under it: a line written for
520/// the old region or profile would count as the newest check of the new one, which the history names the same way.
521pub(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
531/// The entry's own value against `other`. The entry is opened here and wiped when this returns.
532fn 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
543/// Records what a check found (or why it did not run) in the entry's history, naming the place, and answers it.
544pub 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
550/// What a read of the copy came to, compared with the entry's value and recorded.
551fn 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
560/// Reads the machine copy, compares it with the entry's value and records the outcome. Never fails: a place that
561/// can't be read is an outcome. The store is read and written on the blocking pool.
562pub 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    // A linked entry holds no value to compare, and a CI secret gives none back: the place is described, and nothing
566    // of the key is read.
567    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
575/// [`check`] from a thread of the blocking pool, where the pane's operations run: the read is waited for here.
576pub 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;