Skip to main content

agentmux_srv/server/
hook_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! `POST /agentmux/hook/:job`: a script on this computer starts an event job's run
5//! (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md ยง3.2, `webhook_local`; the job side is `backend::jobs::webhook_local`).
6//!
7//! Any page open in a browser pane can POST to loopback, so the request has to look like a script's and not a page's.
8//! The route is on the full router only, which listens on loopback; it is not behind the AuthKey (a script has none),
9//! and the job's own secret is its key. In this order, a request is refused when:
10//! - its peer is not a loopback address, or its `Host` is not a loopback name (a DNS rebinding page arrives under its own);
11//! - it carries an `Origin` or any `Sec-Fetch-*` header (a browser sends them, `curl` and scripts do not);
12//! - its content type is not `application/json` (a cross-site form cannot send that without a preflight, which is not answered);
13//! - it has no secret header, or the secret is not the job's (the same answer for a job that does not exist or is off);
14//! - its body is over 64 KiB, or is not a JSON object.
15
16use std::net::{IpAddr, SocketAddr};
17
18use axum::body::Bytes;
19use axum::extract::{ConnectInfo, Extension, Path, State};
20use axum::http::{header, HeaderMap, StatusCode};
21use axum::response::{IntoResponse, Response};
22use axum::Json;
23use serde_json::{json, Value};
24
25use super::AppState;
26use crate::backend::cron::{FireOutcome, JobEvent};
27use crate::backend::jobs::definition::event_source;
28use crate::backend::jobs::webhook_local::{accepts, ID_HEADER, MAX_ID_CHARS, SECRET_HEADER};
29
30fn refuse(status: StatusCode, why: &str) -> Response {
31    (status, Json(json!({ "ok": false, "error": why }))).into_response()
32}
33
34/// Whether the `Host` header names this computer's loopback: `127.0.0.1`, `localhost` or `[::1]`, with or without a port.
35fn loopback_host(host: &str) -> bool {
36    let name = if let Some(rest) = host.strip_prefix('[') { rest.split(']').next().unwrap_or("") } else { host.rsplit_once(':').map_or(host, |(n, _)| n) };
37    matches!(name, "127.0.0.1" | "localhost" | "::1")
38}
39
40/// What is wrong with a request before the secret is looked at, or nothing. Pure: the handler's first four rules.
41pub(crate) fn precheck(peer: Option<IpAddr>, headers: &HeaderMap) -> Result<String, Response> {
42    if peer.is_some_and(|ip| !ip.is_loopback()) {
43        return Err(refuse(StatusCode::FORBIDDEN, "this address answers only on this computer"));
44    }
45    let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("");
46    if !loopback_host(host) {
47        return Err(refuse(StatusCode::FORBIDDEN, "this address answers only on this computer"));
48    }
49    if headers.contains_key(header::ORIGIN) || headers.keys().any(|k| k.as_str().starts_with("sec-fetch-")) {
50        return Err(refuse(StatusCode::FORBIDDEN, "a web page may not call this; send it from a script"));
51    }
52    let json_type = headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|v| {
53        let essence = v.split(';').next().unwrap_or("").trim();
54        essence.eq_ignore_ascii_case("application/json")
55    });
56    if !json_type {
57        return Err(refuse(StatusCode::UNSUPPORTED_MEDIA_TYPE, "send Content-Type: application/json"));
58    }
59    match headers.get(SECRET_HEADER).and_then(|v| v.to_str().ok()).filter(|s| !s.is_empty()) {
60        Some(secret) => Ok(secret.to_string()),
61        None => Err(refuse(StatusCode::UNAUTHORIZED, "the secret is not right")),
62    }
63}
64
65pub(crate) async fn handle_hook(
66    State(state): State<AppState>,
67    Path(job_id): Path<String>,
68    peer: Option<Extension<ConnectInfo<SocketAddr>>>,
69    headers: HeaderMap,
70    body: Bytes,
71) -> Response {
72    let secret = match precheck(peer.map(|Extension(ConnectInfo(a))| a.ip()), &headers) {
73        Ok(s) => s,
74        Err(refused) => return refused,
75    };
76    let Some(jobs) = super::cron::jobs_store(&state) else { return refuse(StatusCode::UNAUTHORIZED, "the secret is not right") };
77    let id = job_id.clone();
78    let job = tokio::task::spawn_blocking(move || jobs.cron_get(&id)).await.ok().and_then(Result::ok).flatten();
79    let Some(job) = job.filter(|j| accepts(j, &secret)) else { return refuse(StatusCode::UNAUTHORIZED, "the secret is not right") };
80    let Ok(Value::Object(object)) = serde_json::from_slice::<Value>(&body) else {
81        return refuse(StatusCode::BAD_REQUEST, "send a JSON object");
82    };
83    let call = headers.get(ID_HEADER).and_then(|v| v.to_str().ok()).map(str::trim).filter(|s| !s.is_empty() && s.chars().count() <= MAX_ID_CHARS && !s.chars().any(char::is_control));
84    let event = JobEvent {
85        id: format!("wh:{}:{}", job.id, call.map_or_else(|| uuid::Uuid::new_v4().to_string(), str::to_string)),
86        source: event_source::WEBHOOK_LOCAL.to_string(),
87        input: json!({ "body": object, "received_ms": agentmux_common::time::now_ms() }),
88    };
89    let fired = state.cron_scheduler.fire_event(&job, event).await;
90    let status = match (&fired.outcome, &fired.waiting, &fired.run_id) {
91        (Some(FireOutcome::Delivered { .. }), _, _) => "started",
92        (_, Some(_), Some(_)) => "waiting",
93        _ => "not_started",
94    };
95    (StatusCode::ACCEPTED, Json(json!({ "ok": true, "status": status, "run_id": fired.run_id }))).into_response()
96}
97
98#[cfg(test)]
99#[path = "hook_tests.rs"]
100mod tests;