1use std::time::Duration;
20
21use crate::backend::vault::scrub::{self, Scrubber};
22use crate::backend::vault::uses::{self, Ended, UseRequest};
23use crate::backend::vault::{self, FillTarget};
24
25use super::AppState;
26
27const ANSWER_WAIT: Duration = Duration::from_secs(120);
29const CALLED: &str = "called an API";
31const NOT_SENT: &str = "the request was not sent";
32const NOT_ANSWERED: &str = "not answered";
34
35pub(crate) struct Resolved {
37 pub value: zeroize::Zeroizing<String>,
38 pub scrubber: Scrubber,
39}
40
41pub(crate) fn actor(drone_id: &str) -> String {
43 format!("{}{drone_id}", uses::DRONE_ACTOR)
45}
46
47pub(crate) fn grant_key(drone_id: &str, origin: &str, part: &str) -> String {
51 format!("{}:{origin}:{part}", actor(drone_id))
52}
53
54pub(crate) fn part_allowed(kind: &str, part: &str) -> Result<(), String> {
58 match (kind, part) {
59 ("api-key", "value") | ("login", "password") => Ok(()),
60 _ => Err(format!("a drone's API call can use an api-key entry's value or a login's password, not the {part} of a {kind} entry")),
61 }
62}
63
64pub(crate) fn entry_text_ok(entry: &str) -> Result<&str, String> {
67 let entry = entry.trim();
68 if entry.is_empty() {
69 return Err("the API block's auth names no Vault entry".into());
70 }
71 if entry.contains("{{") || entry.contains("}}") {
72 return Err("the API block's Vault entry is written in the drone, not taken from a {{...}} value".into());
73 }
74 if entry.contains('@') {
75 return Err("the API block takes the entry's current value: no @version".into());
76 }
77 Ok(entry)
78}
79
80#[derive(Debug, Clone, PartialEq)]
82pub(crate) enum Binding {
83 Unrecorded,
85 Matches,
86 Differs { recorded: String },
88}
89
90fn recorded_of(kind: &str, fields: &str) -> String {
92 let key = if kind == "login" { "site" } else { "service" };
93 serde_json::from_str::<serde_json::Value>(fields).ok().and_then(|v| v.get(key).and_then(|x| x.as_str()).map(|x| x.trim().to_string())).unwrap_or_default()
94}
95
96fn host_in(recorded: &str) -> Option<String> {
99 let text = recorded.trim().trim_end_matches('/');
100 let candidate = text.split("://").nth(1).unwrap_or(text);
101 let host = candidate.split(['/', '?', '#']).next().unwrap_or("").split(':').next().unwrap_or("").trim().trim_start_matches("www.").to_ascii_lowercase();
102 let host_like = !host.is_empty() && host.contains('.') && host.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.');
103 host_like.then_some(host)
104}
105
106pub(crate) fn binding(recorded: &str, origin: &str) -> Binding {
111 let recorded = recorded.trim();
112 if recorded.is_empty() {
113 return Binding::Unrecorded;
114 }
115 let host = reqwest::Url::parse(origin).ok().and_then(|u| u.host_str().map(str::to_ascii_lowercase)).unwrap_or_default();
116 let fits = match host_in(recorded) {
117 Some(want) => host == want || host.ends_with(&format!(".{want}")),
118 None => {
119 let name: String = recorded.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
120 let labels: Vec<&str> = host.split('.').collect();
121 !name.is_empty() && labels.len() >= 2 && labels[labels.len() - 2] == name
122 }
123 };
124 if fits {
125 Binding::Matches
126 } else {
127 Binding::Differs { recorded: recorded.to_string() }
128 }
129}
130
131fn host_of(origin: &str) -> String {
133 reqwest::Url::parse(origin).ok().and_then(|u| u.host_str().map(str::to_string)).unwrap_or_else(|| origin.to_string())
134}
135
136#[derive(Clone, Copy, PartialEq, Eq, Debug)]
138pub(crate) enum Asking {
139 Person,
141 Never,
145}
146
147const POLL_LINE_EVERY_MS: i64 = 3_600_000;
149
150fn poll_lines() -> &'static std::sync::Mutex<std::collections::HashMap<(String, String), (i64, u32)>> {
152 static LINES: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<(String, String), (i64, u32)>>> = std::sync::OnceLock::new();
153 LINES.get_or_init(Default::default)
154}
155
156fn poll_line_due(drone_id: &str, entry_id: &str, now_ms: i64) -> Option<u32> {
158 let mut map = poll_lines().lock().unwrap_or_else(|p| p.into_inner());
159 let slot = map.entry((drone_id.to_string(), entry_id.to_string())).or_insert((i64::MIN, 0));
160 slot.1 += 1;
161 if now_ms.saturating_sub(slot.0) < POLL_LINE_EVERY_MS {
162 return None;
163 }
164 let polls = slot.1;
165 *slot = (now_ms, 0);
166 Some(polls)
167}
168
169async fn site_mismatch(state: &AppState, target: &FillTarget, drone_id: &str, origin: &str) -> Option<String> {
171 let (store, id) = (state.identity_store.clone(), target.id.clone());
172 let fields = tokio::task::spawn_blocking(move || store.vault_get(&id).ok().flatten().map(|r| r.fields).unwrap_or_default()).await.unwrap_or_default();
173 match binding(&recorded_of(target.kind, &fields), origin) {
174 Binding::Differs { recorded } => Some(format!("This key was saved for {recorded}; the drone {drone_id} sends it to {}", host_of(origin))),
175 _ => None,
176 }
177}
178
179fn poll_cannot_ask(mismatch: Option<&str>, drone_id: &str, label: &str, origin: &str) -> String {
181 match mismatch {
182 Some(why) => format!("{why}: a poll can't ask, so it doesn't send it; run the drone by hand and choose Allow once"),
183 None => format!("the drone {drone_id} has no \"Always\" for {label} at {origin}, and a poll can't ask: run the drone by hand once, answer \"Always\", then the poll goes ahead"),
184 }
185}
186
187pub(crate) async fn resolve(state: &AppState, drone_id: &str, entry: &str, origin: &str) -> Result<Resolved, String> {
190 resolve_with(state, drone_id, entry, origin, Asking::Person).await
191}
192
193pub(crate) async fn resolve_with(state: &AppState, drone_id: &str, entry: &str, origin: &str, asking: Asking) -> Result<Resolved, String> {
195 let entry = entry_text_ok(entry)?.to_string();
196 let who = actor(drone_id);
197 let (store, e, a) = (state.identity_store.clone(), entry, who.clone());
198 let target: FillTarget = tokio::task::spawn_blocking(move || vault::command_target(&store, &e, Some(&a)))
199 .await
200 .map_err(|e| e.to_string())??;
201 part_allowed(target.kind, target.part)?;
202
203 let mismatch = site_mismatch(state, &target, drone_id, origin).await;
205
206 let note = mismatch.clone().unwrap_or_default();
207 let record = |outcome: &str| {
208 vault::record_line(
209 &state.identity_store,
210 vault::Line { entry_id: &target.id, label: &target.label, actor: &who, action: CALLED, target: origin, outcome, reason: ¬e },
211 );
212 super::vault_handlers::publish(state);
214 };
215
216 let key = grant_key(drone_id, origin, target.part);
218 let granted = if mismatch.is_some() {
219 false
220 } else {
221 let (store, id, k) = (state.identity_store.clone(), target.id.clone(), key.clone());
222 tokio::task::spawn_blocking(move || store.vault_grant_check(&id, &k).unwrap_or(false)).await.unwrap_or(false)
223 };
224 if !granted && asking == Asking::Never {
225 return Err(poll_cannot_ask(mismatch.as_deref(), drone_id, &target.label, origin));
227 }
228 if !granted {
229 let request = UseRequest {
230 id: uuid::Uuid::new_v4().to_string(),
231 agent: who.clone(),
232 entry_id: target.id.clone(),
233 entry_label: target.label.clone(),
234 what: target.what.clone(),
235 origin: origin.to_string(),
236 field: "an authorization header".into(),
237 offer_always: mismatch.is_none(),
239 reason: mismatch.clone().unwrap_or_else(|| format!("it is the first time the drone {drone_id} calls {origin} with this entry")),
240 kind: target.kind.to_string(),
241 requested_ms: agentmux_common::time::now_ms_u64(),
242 ..Default::default()
243 };
244 let headline = format!("The drone {drone_id} wants to call {origin} with your {}", target.what);
245 let (ended, _) = super::vault_ask::ask(state, "", request, ANSWER_WAIT, &headline).await;
247 if !ended.allowed() {
248 if matches!(ended, Ended::Expired | Ended::NoAnswer) {
250 record(NOT_ANSWERED);
251 return Err(format!("nobody answered the Vault request to send {} to {origin}, and a drone's first use of a site needs a yes: {NOT_SENT}; the next run asks again", target.label));
252 }
253 record(ended.outcome());
254 return Err(ended.refusal(NOT_SENT));
255 }
256 if ended == Ended::Always && mismatch.is_none() {
257 let (store, id, k, created) = (state.identity_store.clone(), target.id.clone(), key, target.created_at);
258 let _ = tokio::task::spawn_blocking(move || store.vault_grant_add(&id, &k, agentmux_common::time::now_ms(), created)).await;
259 }
260 }
261
262 let (store, t) = (state.identity_store.clone(), target.clone());
264 let value = match tokio::task::spawn_blocking(move || vault::value_for_command(&store, &t)).await {
265 Ok(Ok(v)) => v,
266 Ok(Err(e)) => {
267 record("failed");
268 return Err(e);
269 }
270 Err(e) => return Err(e.to_string()),
271 };
272 if value.chars().count() < scrub::MIN_LEN {
273 record("failed");
274 return Err(format!("{} is too short to send: the response couldn't be cleaned of it", target.label));
275 }
276 if asking == Asking::Never {
277 if let Some(polls) = poll_line_due(drone_id, &target.id, agentmux_common::time::now_ms()) {
279 let reason = format!("a poll, {polls} time(s) since the last line");
280 vault::record_line(
281 &state.identity_store,
282 vault::Line { entry_id: &target.id, label: &target.label, actor: &who, action: CALLED, target: origin, outcome: "done", reason: &reason },
283 );
284 super::vault_handlers::publish(state);
285 }
286 } else {
287 record("done");
288 }
289 let (store, id) = (state.identity_store.clone(), target.id.clone());
290 let _ = tokio::task::spawn_blocking(move || store.vault_touch(&id, agentmux_common::time::now_ms())).await;
291 let scrubber = Scrubber::new(&[(target.id.clone(), value.to_string())]);
292 Ok(Resolved { value, scrubber })
293}
294
295#[cfg(test)]
296mod unit_tests {
297 use super::*;
298
299 #[test]
300 fn a_drone_is_its_own_actor_and_never_a_named_agent() {
301 assert_eq!(actor("nightly"), "drone:nightly");
302 let (a, b) = (format!("{}a", "x".repeat(80)), format!("{}b", "x".repeat(80)));
304 assert_ne!(actor(&a), actor(&b));
305 assert_ne!(grant_key(&a, "https://api.example.com", "value"), grant_key(&b, "https://api.example.com", "value"));
306 }
307
308 #[test]
309 fn a_grant_is_for_one_drone_one_site_and_one_part() {
310 let k = grant_key("nightly", "https://api.example.com", "value");
311 assert_eq!(k, "drone:nightly:https://api.example.com:value");
312 assert_ne!(k, grant_key("nightly", "https://api.example.org", "value"));
313 assert_ne!(k, grant_key("other", "https://api.example.com", "value"));
314 assert_ne!(k, grant_key("nightly", "https://api.example.com", "password"));
315 assert!(!k.starts_with("command:") && !k.starts_with("http"));
317 }
318
319 #[test]
320 fn only_an_api_keys_value_or_a_logins_password_may_go_in_a_header() {
321 assert!(part_allowed("api-key", "value").is_ok());
322 assert!(part_allowed("login", "password").is_ok());
323 assert!(part_allowed("login", "totp").is_err());
324 assert!(part_allowed("login", "username").is_err());
325 assert!(part_allowed("card", "number").is_err());
326 assert!(part_allowed("note", "value").is_err());
327 assert!(part_allowed("api-key", "other").is_err());
328 }
329
330 #[test]
331 fn the_entry_is_written_in_the_drone() {
332 assert_eq!(entry_text_ok(" api-key-stripe ").unwrap(), "api-key-stripe");
333 assert_eq!(entry_text_ok("login-bank.password").unwrap(), "login-bank.password");
334 assert!(entry_text_ok("").is_err());
335 assert!(entry_text_ok(" ").is_err());
336 assert!(entry_text_ok("{{trigger.entry}}").is_err());
337 assert!(entry_text_ok("api-key-stripe@previous").is_err());
338 assert!(entry_text_ok("api-key-stripe@pending").is_err());
339 }
340}
341
342#[cfg(test)]
343#[path = "drone_vault/tests.rs"]
344mod tests;