1use axum::extract::State;
19use axum::http::StatusCode;
20use axum::response::{IntoResponse, Response};
21use axum::{Extension, Json};
22use serde::Deserialize;
23use serde_json::{json, Value};
24
25use super::folder_overlap_ask::{asker_named, refuse, Asker, Refusal};
26use super::pins::{change, confirm_shown, label, Change};
27use super::*;
28use crate::backend::pin_asks::{asks, Asked, Outcome, PinAsk, OPEN_MS};
29use crate::backend::rpc_types::{CommandPinsAskAnswerData, CommandPinsChangeData, PinsAskAnswerResult, PinsAsksResult, COMMAND_PINS_ASKS, COMMAND_PINS_ASK_ANSWER};
30use crate::server::caller::Caller;
31use crate::server::reactive::lan_continuity::fingerprint;
32use crate::server::reactive::lan_refusals;
33
34pub(crate) const AUDIT_ASK: &str = "pins.ask";
36const AUDIT_ALLOW: &str = "pins.ask.allow";
37const AUDIT_DECLINE: &str = "pins.ask.decline";
38
39const MAX_REASON: usize = 300;
41
42const ONLY_THE_PERSON_ANSWERS: &str = "only the person answers an agent's ask to change a pin, from the AgentMux window";
44
45#[derive(Debug, Deserialize)]
46pub(crate) struct AskRequest {
47 pub change: String,
49 pub kind: String,
51 pub agent_id: String,
53 #[serde(default)]
55 pub channel: Option<String>,
56 #[serde(default)]
59 pub expect: Option<String>,
60 #[serde(default)]
62 pub reason: String,
63}
64
65struct Shown {
67 from: String,
68 from_install: String,
69 to: String,
70 to_install: String,
71}
72
73fn internal(e: impl std::fmt::Display) -> Refusal {
74 refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("pins: {e}"))
75}
76
77fn clean_reason(reason: &str) -> Result<String, Refusal> {
79 let one_line = reason.split_whitespace().collect::<Vec<_>>().join(" ");
80 let one_line: String = one_line.chars().filter(|c| !c.is_control()).collect();
81 if one_line.is_empty() {
82 return Err(refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change needs a reason: say in a sentence why the pin should change; the person reads it"));
83 }
84 if one_line.chars().count() > MAX_REASON {
85 return Err(refuse(StatusCode::BAD_REQUEST, format!("Agents ask_pin_change: the reason is at most {MAX_REASON} characters")));
86 }
87 Ok(one_line)
88}
89
90fn stale(what: String) -> Refusal {
91 refuse(StatusCode::CONFLICT, what)
92}
93
94fn pin_now(state: &AppState, kind: &str, agent: &str, channel: &str) -> Result<Option<(String, String)>, Refusal> {
96 match kind {
97 "lan" => {
98 let Some((key, _since)) = state.mstore.lan_peer_pubkey_pin_since(agent).map_err(internal)? else { return Ok(None) };
99 let bound = state.mstore.lan_pin_installed(agent).ok().flatten().map(|i| label(&i.host_hint, &i.instance_id)).unwrap_or_default();
100 Ok(Some((fingerprint(&key), bound)))
101 }
102 _ => {
103 let Some(wan) = crate::backend::storage::wan_identity::global() else { return Ok(None) };
104 let pin = wan.agent_instance_pin_get(agent, channel).map_err(internal)?;
105 Ok(pin.map(|p| (label(&p.host_hint, &p.instance_id), String::new())))
106 }
107 }
108}
109
110fn describe(state: &AppState, req: &AskRequest, how: Change, agent: &str, channel: &str) -> Result<Shown, Refusal> {
113 let (from, from_install) = pin_now(state, &req.kind, agent, channel)?.ok_or_else(|| {
114 stale(format!("no {} pin for {agent}: there is nothing to move or forget (a name with no pin takes its first key with pins adopt)", req.kind))
115 })?;
116 let expect = req.expect.as_deref();
117 if how == Change::Forget {
118 if expect != Some(from.as_str()) {
119 return Err(stale(format!("the pin for {agent} is not the one named: expect the fingerprint or install now pinned, {from}")));
120 }
121 return Ok(Shown { from, from_install, to: String::new(), to_install: String::new() });
122 }
123 let (to, to_install) = if req.kind == "lan" {
124 let refused = lan_refusals::get(agent)
125 .filter(|r| fingerprint(&r.key_b64) != from)
126 .ok_or_else(|| stale(format!("no other key has been shown for {agent} since AgentMux started")))?;
127 let install = refused.cert.as_ref().map(|c| label(&c.host_hint, &c.instance_id)).unwrap_or_default();
128 (fingerprint(&refused.key_b64), install)
129 } else {
130 let wan = crate::backend::storage::wan_identity::global().ok_or_else(|| stale("this install has no WAN identity".to_string()))?;
131 let pin = wan.agent_instance_pin_get(agent, channel).map_err(internal)?.ok_or_else(|| stale(format!("no WAN pin for {agent} on {channel}")))?;
132 let conflict = pin.conflict.ok_or_else(|| stale(format!("no other install has spoken for {agent} on {channel}")))?;
133 (label(&conflict.host_hint, &conflict.instance_id), String::new())
134 };
135 confirm_shown(expect, &to, agent).map_err(stale)?;
136 Ok(Shown { from, from_install, to, to_install })
137}
138
139fn how_of(change: &str) -> Option<Change> {
140 match change {
141 "move" => Some(Change::Adopt),
142 "forget" => Some(Change::Forget),
143 _ => None,
144 }
145}
146
147pub(crate) fn ask(state: &AppState, asker: &Asker, req: &AskRequest, now_ms: u64) -> Result<Value, Refusal> {
149 let change = req.change.trim();
150 let how = how_of(change).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change: change is move or forget"))?;
151 let agent = req.agent_id.trim().to_lowercase();
152 if agent.is_empty() {
153 return Err(refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change: no agent named"));
154 }
155 let channel = req.channel.as_deref().map(str::trim).unwrap_or_default();
156 match (req.kind.as_str(), channel.is_empty()) {
157 ("lan", true) | ("wan", false) => {}
158 ("lan", false) => return Err(refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change: a LAN pin has no channel")),
159 ("wan", true) => return Err(refuse(StatusCode::BAD_REQUEST, "Agents ask_pin_change: a WAN pin needs its channel")),
160 (other, _) => return Err(refuse(StatusCode::BAD_REQUEST, format!("Agents ask_pin_change: unknown kind {other:?} (lan or wan)"))),
161 }
162 let reason = clean_reason(&req.reason)?;
163 let shown = match describe(state, req, how, &agent, channel) {
164 Ok(shown) => shown,
165 Err(why) => {
167 return match asks().allowed_ago_ms(change, &req.kind, &agent, channel, &asker.slug, req.expect.as_deref().unwrap_or_default(), now_ms) {
168 Some(ago) => Ok(json!({ "status": "allowed", "seconds_ago": ago / 1000, "note": "the person allowed this change; it is done" })),
169 None => Err(why),
170 }
171 }
172 };
173 if asker.block_id.is_empty() {
174 return Err(refuse(StatusCode::CONFLICT, "Agents ask_pin_change shows its card in the asking agent's pane, and this agent has no open pane to show it in"));
175 }
176 let card = PinAsk {
177 id: uuid::Uuid::new_v4().to_string(),
178 change: change.to_string(),
179 kind: req.kind.clone(),
180 agent_id: agent.clone(),
181 channel: channel.to_string(),
182 from: shown.from,
183 from_install: shown.from_install,
184 to: shown.to,
185 to_install: shown.to_install,
186 reason,
187 agent: asker.name.clone(),
188 asker_id: asker.slug.clone(),
189 block_id: asker.block_id.clone(),
190 requested_ms: now_ms,
191 };
192 match asks().ask(card, now_ms) {
193 Asked::Waiting { ask: kept, new } => {
194 publish_asks(state);
195 if new {
196 audit(state, Some(&asker.slug), AUDIT_ASK, &kept);
197 }
198 Ok(json!({
199 "status": "asked",
200 "expires_in_seconds": (OPEN_MS.saturating_sub(now_ms.saturating_sub(kept.requested_ms))).div_ceil(1000),
201 "note": "the person is asked in your pane; ask_pin_change again with the same arguments for their answer. No answer in time counts as a no",
202 }))
203 }
204 Asked::Settled { outcome: Outcome::Allowed, .. } => Ok(json!({ "status": "allowed", "note": "the person allowed this change; it is done" })),
205 Asked::Settled { outcome: Outcome::Declined, retry_after_ms } => Ok(json!({
206 "status": "declined",
207 "retry_after_seconds": retry_after_ms.div_ceil(1000),
208 "note": "the person said no to this change; it is not asked again for a while",
209 })),
210 Asked::Settled { outcome: Outcome::Expired, .. } => Ok(json!({
211 "status": "expired",
212 "note": "nobody answered in time, which is a no; ask again if the change is still needed",
213 })),
214 }
215}
216
217pub(crate) fn publish_asks(state: &AppState) {
219 let event = crate::backend::mps_events::PinAsksEvent { asks: asks().list(agentmux_common::time::now_ms_u64()) };
220 state.broker.publish_event::<crate::backend::mps_events::PinAsks>(&event, vec![], 0);
221}
222
223pub(crate) fn pin_changed(state: &AppState, kind: &str, agent: &str, channel: &str) {
225 asks().forget_pin(kind, agent, channel, agentmux_common::time::now_ms_u64());
226 publish_asks(state);
227}
228
229fn audit(state: &AppState, by: Option<&str>, action: &str, ask: &PinAsk) {
231 let note = match ask.change.as_str() {
232 "forget" => format!("{} asked to forget the {} pin for {} ({}): {}", ask.agent, ask.kind, ask.agent_id, ask.from, ask.reason),
233 _ => format!("{} asked to move the {} pin for {} from {} to {}: {}", ask.agent, ask.kind, ask.agent_id, ask.from, ask.to, ask.reason),
234 };
235 tracing::info!(action, "{note}");
236 let request_id = uuid::Uuid::new_v4().to_string();
237 state.reactive_handler.log_fleet_action_audit(by, &ask.agent_id, &ask.block_id, action, true, None, &request_id, Some(¬e));
238}
239
240fn apply(state: &AppState, ask: &PinAsk) -> Result<(), String> {
242 let how = how_of(&ask.change).ok_or_else(|| "pins: unknown change".to_string())?;
243 let now = pin_now(state, &ask.kind, &ask.agent_id, &ask.channel).map_err(|r| r.message)?;
244 if now.map(|(from, _)| from).as_deref() != Some(ask.from.as_str()) {
245 return Err(format!("pins: the pin for {} is not the one the card showed, so nothing was changed; ask again", ask.agent_id));
246 }
247 let req = CommandPinsChangeData {
248 kind: ask.kind.clone(),
249 agent_id: ask.agent_id.clone(),
250 channel: (!ask.channel.is_empty()).then(|| ask.channel.clone()),
251 expect: (how == Change::Adopt).then(|| ask.to.clone()),
253 };
254 change(state, &req, how, Some(&ask.asker_id))
255}
256
257fn answer(state: &AppState, cmd: CommandPinsAskAnswerData) -> Result<PinsAskAnswerResult, String> {
259 let now = agentmux_common::time::now_ms_u64();
260 let Some(ask) = asks().take(&cmd.id, now) else {
261 publish_asks(state);
262 return Ok(PinsAskAnswerResult { outcome: "gone".to_string() });
263 };
264 if !cmd.allow {
265 asks().settle(&ask, Outcome::Declined, now);
266 publish_asks(state);
267 audit(state, None, AUDIT_DECLINE, &ask);
268 return Ok(PinsAskAnswerResult { outcome: "declined".to_string() });
269 }
270 let applied = apply(state, &ask);
272 if applied.is_ok() {
273 asks().settle(&ask, Outcome::Allowed, now);
274 audit(state, None, AUDIT_ALLOW, &ask);
275 }
276 publish_asks(state);
277 applied.map(|()| PinsAskAnswerResult { outcome: "changed".to_string() })
278}
279
280pub(crate) async fn handle_pin_ask(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<AskRequest>) -> Response {
281 let caller = caller.map(|Extension(c)| c);
282 let run = || -> Result<Value, Refusal> {
283 let asker = asker_named(&state, caller.as_ref(), "no agent token: Agents ask_pin_change is an agent's ask; the person changes a pin from the AgentMux window")?;
284 ask(&state, &asker, &req, agentmux_common::time::now_ms_u64())
285 };
286 match run() {
287 Ok(body) => Json(body).into_response(),
288 Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
289 }
290}
291
292pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
293 let st = state.clone();
294 engine.register_typed(COMMAND_PINS_ASK_ANSWER, move |cmd: CommandPinsAskAnswerData, ctx| {
295 let state = st.clone();
296 async move {
297 ctx.operator_only(ONLY_THE_PERSON_ANSWERS)?;
298 answer(&state, cmd)
299 }
300 });
301 engine.register_typed(COMMAND_PINS_ASKS, |_req: Value, ctx| async move {
302 ctx.operator_only(ONLY_THE_PERSON_ANSWERS)?;
303 Ok(PinsAsksResult { asks: asks().list(agentmux_common::time::now_ms_u64()) })
304 });
305}
306
307#[cfg(test)]
308#[path = "pin_ask_tests.rs"]
309mod tests;