hyperhive/hive-c0re/src/dashboard/webhook.rs
atlas 18e7c406b0 fix(#2377): doc_markdown + too_many_lines clippy lints
- Backtick-quote `pull_request` in doc comments (4x doc_markdown)
- Add #[allow(clippy::too_many_lines)] to server::dispatch (101/100;
  +1 line from submit_kind fetched_sha param in 5dd0a36f)
2026-07-11 12:19:52 +02:00

206 lines
7.5 KiB
Rust

//! Forgejo webhook endpoints.
//!
//! - **`/webhook/knowledge`** — push events on `internal/knowledge` trigger a
//! `git pull` on the local clone so agents see up-to-date docs.
//! - **`/webhook/config-pr`** — `pull_request` events on any `agent-configs/*`
//! repo queue a [`hive_sh4re::ApprovalKind::MergeConfigPr`] approval row
//! so the operator can review + approve the merge from the dashboard.
//!
//! Both endpoints are loopback-only (the axum listener binds
//! `127.0.0.1:<port>`) and have no signature verification (the risk is low:
//! loopback access implies host compromise already, and the config-PR path
//! still requires the operator to approve on the dashboard).
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use super::AppState;
// ── knowledge webhook ──────────────────────────────────────────────────────────
/// Minimal Forgejo push-webhook payload — only the fields we care about.
#[derive(Deserialize)]
pub(super) struct PushWebhookPayload {
#[serde(rename = "ref")]
git_ref: Option<String>,
repository: Option<PushWebhookRepo>,
}
#[derive(Deserialize)]
pub(super) struct PushWebhookRepo {
full_name: Option<String>,
}
/// POST `/webhook/knowledge` — Forgejo push webhook for
/// `internal/knowledge`. Runs `git pull` on the local clone so
/// agents see up-to-date documents on their next turn.
///
/// Expected Forgejo webhook configuration:
/// - URL: `http://127.0.0.1:<dashboard_port>/webhook/knowledge`
/// - Event: "Push" (fires on merge commits to main as well)
///
/// No signature verification for now; the endpoint is loopback-only
/// and only triggers a read-only `git pull` on an operator-curated repo.
pub(super) async fn post_webhook_knowledge(
axum::extract::Json(payload): axum::extract::Json<PushWebhookPayload>,
) -> Response {
let expected_repo = format!("{}/{}", crate::knowledge::ORG, crate::knowledge::REPO);
let full_name = payload
.repository
.as_ref()
.and_then(|r| r.full_name.as_deref())
.unwrap_or("");
if full_name != expected_repo {
tracing::debug!(
full_name,
"webhook/knowledge: ignoring push from unexpected repo"
);
return (StatusCode::OK, "ignored").into_response();
}
let git_ref = payload.git_ref.as_deref().unwrap_or("");
if git_ref != "refs/heads/main" {
tracing::debug!(git_ref, "webhook/knowledge: ignoring non-main push");
return (StatusCode::OK, "ignored").into_response();
}
tracing::info!("webhook/knowledge: pull triggered by push to {expected_repo}");
tokio::spawn(async {
if let Err(e) = crate::knowledge::pull().await {
tracing::warn!(error = ?e, "webhook/knowledge: pull failed");
}
});
(StatusCode::OK, "ok").into_response()
}
// ── config-PR webhook ──────────────────────────────────────────────────────────
/// Minimal Forgejo `pull_request`-webhook payload.
///
/// Forgejo fires this for actions: `opened`, `closed`, `reopened`,
/// `synchronize`, `assigned`, `unassigned`, `label_updated`,
/// `label_cleared`, `milestoned`, `demilestoned`, `review_requested`,
/// `review_request_removed`, `auto_merge_enabled`, `auto_merge_disabled`.
/// We only act on `opened` and `synchronize`.
#[derive(Deserialize)]
pub(super) struct PrWebhookPayload {
/// What triggered this event (`opened`, `closed`, `synchronize`, …).
action: Option<String>,
/// PR index on the repo.
number: Option<u64>,
pull_request: Option<PrWebhookPr>,
repository: Option<PrWebhookRepo>,
}
#[derive(Deserialize)]
struct PrWebhookPr {
head: Option<PrWebhookHead>,
}
#[derive(Deserialize)]
struct PrWebhookHead {
sha: Option<String>,
}
#[derive(Deserialize)]
struct PrWebhookRepo {
full_name: Option<String>,
}
/// POST `/webhook/config-pr` — Forgejo `pull_request` webhook for
/// `agent-configs/*` repos.
///
/// On `opened` or `synchronize` for an `agent-configs/<agent>` PR:
/// fetches the current PR head sha, queues a `MergeConfigPr` approval row,
/// and emits the `ApprovalAdded` event so the dashboard card appears
/// immediately.
///
/// All other actions (closed, label changes, etc.) are silently ignored —
/// the operator can deny a pending approval if the PR is later closed.
///
/// Always returns HTTP 200 (even on queue failure) so Forgejo does not
/// retry the delivery. Failures are logged at `warn` level.
///
/// Expected Forgejo webhook configuration:
/// - URL: `http://127.0.0.1:<dashboard_port>/webhook/config-pr`
/// - Content type: `application/json`
/// - Events: "Pull Request" only
/// - Organisation: `agent-configs` (org-level hook covers all config repos)
///
/// hive-c0re registers this hook automatically at startup via
/// [`crate::forge::ensure_config_pr_webhook`].
pub(super) async fn post_webhook_config_pr(
State(state): State<AppState>,
axum::extract::Json(payload): axum::extract::Json<PrWebhookPayload>,
) -> Response {
let action = payload.action.as_deref().unwrap_or("");
// Only act on newly-opened or force-updated PRs.
if action != "opened" && action != "synchronize" {
tracing::debug!(action, "webhook/config-pr: ignoring action");
return (StatusCode::OK, "ignored").into_response();
}
let full_name = payload
.repository
.as_ref()
.and_then(|r| r.full_name.as_deref())
.unwrap_or("");
// Expect `agent-configs/<agent>`.
let agent = match full_name.strip_prefix(&format!("{}/", crate::forge::CONFIG_ORG)) {
Some(name) if !name.is_empty() && !name.contains('/') => name,
_ => {
tracing::debug!(
full_name,
"webhook/config-pr: ignoring non-config-repo event"
);
return (StatusCode::OK, "ignored").into_response();
}
};
let pr_number = match payload.number {
Some(n) if n > 0 => n,
_ => {
tracing::warn!(full_name, "webhook/config-pr: missing or zero PR number");
return (StatusCode::OK, "ignored").into_response();
}
};
// The payload already carries the head sha — use it as an early hint for
// logging, but the canonical sha comes from `submit_merge_config_pr`'s
// fresh forge API call so we don't trust a potentially-stale payload sha.
let payload_sha = payload
.pull_request
.as_ref()
.and_then(|pr| pr.head.as_ref())
.and_then(|h| h.sha.as_deref())
.unwrap_or("<unknown>");
tracing::info!(
%full_name, %agent, %pr_number, %payload_sha, %action,
"webhook/config-pr: queuing MergeConfigPr approval"
);
// Queue the approval. The description surfaces the action and PR number
// on the dashboard card so the operator has context without opening the
// forge PR.
let description = format!("PR #{pr_number} on {full_name} ({action})");
if let Err(e) = crate::socket_server::submit_merge_config_pr(
&state.coord,
agent,
pr_number,
Some(&description),
"forge", // submitter — identifies the webhook path in the audit trail
)
.await
{
tracing::warn!(
%agent, %pr_number, error = ?e,
"webhook/config-pr: failed to queue MergeConfigPr approval"
);
}
(StatusCode::OK, "ok").into_response()
}