1use 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
32pub(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
49fn 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
62async 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
69async 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
78fn 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
89fn 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
99fn 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 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
118pub(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
131async 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
156pub(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}