Skip to main content

agentmux_srv/server/
vault_source.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/vault/check`: an agent asks whether an entry's machine copy still holds the entry's value
5//! (`backend::vault::source_link`). srv reads the other place with the agent's own access (the host's AWS setup for
6//! a native agent, a broker session for a container agent's grant), compares inside srv and answers `same`,
7//! `different` or `could not read` with why. No value comes back, and a place that refuses the read is the answer.
8//!
9//! A CI secret is read with the GitHub CLI signed in on this computer, which is the person's login
10//! (`backend::vault::github_secret`). A native agent already runs as the person. A container agent does not, so its
11//! check starts that read only for an entry it holds the person's standing approval to use; without it the answer is
12//! the newest stored result, the reason and what to do. Every read that is started is one line in Audit.
13
14use axum::extract::State;
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Response};
17use axum::Json;
18use serde::Deserialize;
19use serde_json::json;
20
21use super::vault_import::{asker, credentials, Who};
22use super::AppState;
23use crate::backend::rpc::action_record::{ActionRecord, Target};
24use crate::backend::rpc::actor::Actor;
25use crate::backend::vault::aws_import::Via;
26use crate::backend::vault::github_secret::Place;
27use crate::backend::vault::linked::place_text;
28use crate::backend::vault::source_link::{self, CheckPlan, Checked, Outcome, AWS_SECRET, COULD_NOT_READ, NOT_STARTED};
29use crate::backend::vault::vaults;
30use crate::identity::aws_broker::mint::{HostRunner, Runner};
31
32/// The Audit action of a read of a CI secret's listing entry.
33pub(crate) const AUDIT_ACTION: &str = "vault.check.ci-secret";
34
35#[derive(Debug, Deserialize)]
36pub(crate) struct CheckBody {
37    #[serde(default)]
38    id: String,
39    #[serde(default)]
40    reason: Option<String>,
41    #[serde(default)]
42    auth: Option<agentmux_common::api_types::UiAutomationAuth>,
43}
44
45fn error(status: StatusCode, message: impl Into<String>) -> Response {
46    (status, Json(json!({ "error": message.into() }))).into_response()
47}
48
49/// Why a check was not started, as a status: an entry the agent can't use is not there, and the hourly limit is a
50/// "try later".
51fn refusal(why: String) -> Response {
52    let status = if why.starts_with("no entry") {
53        StatusCode::NOT_FOUND
54    } else if why.contains("is the limit") {
55        StatusCode::TOO_MANY_REQUESTS
56    } else {
57        StatusCode::BAD_REQUEST
58    };
59    error(status, why)
60}
61
62/// A check that ended before the place was read, recorded like any other.
63async fn could_not_read(state: &AppState, plan: CheckPlan, why: String) -> Checked {
64    let store = state.identity_store.clone();
65    let stopped = Checked::of(&plan, &Outcome::CouldNotRead(why.clone()));
66    tokio::task::spawn_blocking(move || source_link::conclude(&store, &plan, &Outcome::CouldNotRead(why))).await.unwrap_or(stopped)
67}
68
69/// Whether the person answered Always to this agent's use of the entry's value, in a Vault the agent may use: the
70/// standing approval a container agent's read of a CI secret needs.
71async fn approved(state: &AppState, plan: &CheckPlan, who: &Who) -> bool {
72    let (store, id, agent) = (state.identity_store.clone(), plan.entry_id.clone(), who.agent.clone());
73    let key = super::shell_secrets::grant_key(&who.agent, plan.part);
74    let asked = move || store.vault_grant_check(&id, &key).unwrap_or(false) && vaults::entry_usable(&store, &id, Some(&agent)).unwrap_or(false);
75    tokio::task::spawn_blocking(asked).await.unwrap_or(false)
76}
77
78/// Why a container agent's check starts no read of a CI secret, and what to do. A link holds no value, so nobody
79/// can have answered Always for it.
80fn held(plan: &CheckPlan) -> String {
81    let instead = if plan.only {
82        "This entry holds no value, so it has no such answer: ask the person to check it, with the button on the entry in the Vault pane."
83    } else {
84        "Ask for the entry through the Vault, and check again once the person has answered Always."
85    };
86    format!("A container agent's check of a CI secret is read with the person's GitHub login on this computer, so it starts only for an entry the person answered Always for to this agent. {instead}")
87}
88
89/// What the check found at `place`, one of the plan's CI secrets; `None` when no read of it was started.
90fn read_of<'a>(plan: &CheckPlan, checked: &'a Checked, place: &source_link::Link) -> Option<(&'a str, &'a str)> {
91    let found = if *place == plan.link {
92        Some((checked.outcome, checked.why.as_str()))
93    } else {
94        checked.copies.iter().find(|copy| copy.place == place_text(place)).map(|copy| (copy.outcome, copy.why.as_str()))
95    };
96    found.filter(|(outcome, _)| *outcome != NOT_STARTED)
97}
98
99/// One Audit line for every CI secret the check read, an action of the agent's or of the person's: who, which
100/// entry, which repository and the outcome. A place no read was started for has none.
101fn audit_reads(state: &AppState, who: Option<&Who>, plan: &CheckPlan, checked: &Checked) {
102    let actor = who.map_or(Actor::Operator, |who| Actor::Agent(who.slug.clone()));
103    for place in plan.github_places() {
104        let Some((outcome, why)) = read_of(plan, checked, place) else { continue };
105        let repository = Place::of(place).map(|p| p.repository()).unwrap_or_else(|_| place.location.clone());
106        let note = format!("checked the CI secret {} of {repository} for {} ({}): {outcome}", place.key, plan.label, plan.entry_id);
107        state.reactive_handler.audit_action(&ActionRecord {
108            actor: actor.clone(),
109            command: AUDIT_ACTION.to_string(),
110            // The read acts on no agent and no pane: the line names the secret, its repository and the entry.
111            target: Target { agent: None, block_id: None, subject: Some(note) },
112            request_id: uuid::Uuid::new_v4().to_string(),
113            error: (outcome == COULD_NOT_READ).then(|| why.to_string()),
114        });
115    }
116}
117
118/// The person's check, from the Vault pane: read with this computer's own logins, and recorded.
119pub(crate) fn person_check(state: &AppState, id: &str) -> Result<Checked, String> {
120    person_check_with(state, &HostRunner, id)
121}
122
123fn person_check_with<R: Runner>(state: &AppState, runner: &R, id: &str) -> Result<Checked, String> {
124    let store = &state.identity_store;
125    let plan = source_link::plan_for_person(store, id)?;
126    let checked = source_link::check_blocking(store, runner, &plan, Via::Host)?;
127    audit_reads(state, None, &plan, &checked);
128    Ok(checked)
129}
130
131/// Reads the place as `who` and compares. A container agent reads an AWS secret under the grant the link names; when
132/// it has none, or the broker refuses, that is what the check found. Its read of a CI secret needs the person's
133/// standing approval of the entry ([`approved`]).
134async fn run<R: Runner>(state: &AppState, runner: &R, mut plan: CheckPlan, who: &Who) -> Checked {
135    if who.container && !plan.github_places().is_empty() && !approved(state, &plan, who).await {
136        plan.no_github = Some(held(&plan));
137    }
138    let minted = if who.container && plan.link.kind == AWS_SECRET {
139        if plan.link.profile.is_empty() {
140            let why = format!("a container agent reads AWS under a grant, and this entry's {} names none", source_link::PROFILE);
141            return could_not_read(state, plan, why).await;
142        }
143        match credentials(state, who, &plan.link.profile, &plan.reason).await {
144            Ok(minted) => minted,
145            Err(why) => return could_not_read(state, plan, why).await,
146        }
147    } else {
148        None
149    };
150    let via = minted.as_ref().map_or(Via::Host, Via::Session);
151    let checked = source_link::check(&state.identity_store, runner, &plan, via).await;
152    audit_reads(state, Some(who), &plan, &checked);
153    checked
154}
155
156/// `POST /api/v1/vault/check`
157pub(crate) async fn handle_vault_check(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<CheckBody>) -> Response {
158    let who = match asker(&state, caller.as_deref(), body.auth.as_ref(), "check", "who checked each entry") {
159        Ok(who) => who,
160        Err(refusal) => return refusal,
161    };
162    if body.id.trim().is_empty() {
163        return error(StatusCode::BAD_REQUEST, "check needs an id: the entry whose machine copy to check (list shows which have one)");
164    }
165    let (store, agent) = (state.identity_store.clone(), who.agent.clone());
166    let planned = tokio::task::spawn_blocking(move || source_link::plan_for_agent(&store, &body.id, &agent, body.reason.as_deref())).await;
167    let plan = match planned {
168        Ok(Ok(plan)) => plan,
169        Ok(Err(why)) => return refusal(why),
170        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
171    };
172    let checked = run(&state, &HostRunner, plan, &who).await;
173    super::vault_handlers::publish(&state);
174    Json(checked).into_response()
175}
176
177#[cfg(test)]
178#[path = "vault_source_ci_tests.rs"]
179mod ci_tests;
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn a_refusal_says_not_found_for_an_entry_out_of_reach_and_try_later_at_the_limit() {
187        assert_eq!(refusal("no entry api-key-example".into()).status(), StatusCode::NOT_FOUND);
188        assert_eq!(refusal("Example was checked 6 times by agents in the last hour, which is the limit: its history has what they found".into()).status(), StatusCode::TOO_MANY_REQUESTS);
189        assert_eq!(refusal("Example has no machine copy recorded".into()).status(), StatusCode::BAD_REQUEST);
190    }
191}