fix(webhooks): the managed Gitea webhook answers 202 and works in the background #538

Merged
sharang merged 1 commits from fix/webhook-async-202 into main 2026-10-09 11:22:01 +00:00
3 changed files with 179 additions and 49 deletions

No files matched your search

+45 -1
View File
@@ -26,6 +26,10 @@ use compliance_core::AgentConfig;
pub const ENTITLEMENT_TTL: Duration = Duration::from_secs(60);
/// Refresh the service token this long before it expires.
const TOKEN_MARGIN: Duration = Duration::from_secs(30);
/// Upper bound for one registry or Keycloak token request. Without it a hung
/// Keycloak holds the token lock, and every caller behind it, for the shared
/// client's 30 s.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
/// The registry's `reason` for a member blocked in the tenant.
pub const MEMBER_BLOCKED: &str = "member_blocked";
@@ -230,6 +234,7 @@ impl RegistryClient {
let resp = self
.http
.post(url)
.timeout(REQUEST_TIMEOUT)
.form(&[
("grant_type", "client_credentials"),
("client_id", id.as_str()),
@@ -261,7 +266,7 @@ impl RegistryClient {
let mut rb = self
.http
.request(method, format!("{}{path}", self.base_url))
.timeout(Duration::from_secs(5));
.timeout(REQUEST_TIMEOUT);
if let Some(tok) = self.bearer().await? {
rb = rb.bearer_auth(tok);
}
@@ -542,4 +547,43 @@ mod tests {
assert!(!scheduler_runs_for(s), "{s} should be skipped");
}
}
/// A Keycloak that accepts the connection and never answers costs one
/// [`REQUEST_TIMEOUT`], not the shared client's 30 s.
#[tokio::test]
async fn a_hung_token_endpoint_gives_up_after_the_request_timeout() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let mut held = Vec::new();
while let Ok((socket, _)) = listener.accept().await {
held.push(socket);
}
});
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.build()
.unwrap();
let client = RegistryClient {
base_url: format!("http://{addr}"),
product: "pruefwerk".into(),
http,
token_url: Some(format!("http://{addr}/token")),
client_id: Some("svc".into()),
client_secret: Some("secret".into()),
token: Mutex::new(None),
cache: DashMap::new(),
projects: DashMap::new(),
};
let started = Instant::now();
let result = client.bearer().await;
assert!(result.is_err(), "{result:?}");
assert!(
started.elapsed() < REQUEST_TIMEOUT * 2,
"{:?}",
started.elapsed()
);
}
}
+88 -27
View File
@@ -4,23 +4,53 @@
//! Authenticated by `X-Gitea-Signature`: HMAC-SHA256 of the body under the
//! source's webhook secret. Until that is verified nothing is created: the
//! source is read through a handle that cannot conjure a tenant database.
//!
//! A verified delivery that asks for work is answered `202 Accepted` at once;
//! the entitlement check, the target and the scan follow in the background,
//! so a slow registry or Keycloak never runs into Gitea's delivery timeout.
use std::sync::Arc;
use std::time::Instant;
use axum::body::Bytes;
use axum::extract::{Extension, Path};
use axum::http::{HeaderMap, StatusCode};
use compliance_core::models::GitSource;
use crate::agent::ComplianceAgent;
use crate::git_source::{self, events};
/// Answer one delivery and log how long the answer took.
///
/// # Returns
///
/// `202` when work was handed to the background, `200` when the event needs
/// none, `401`/`404`/`400`/`500` when the delivery is refused or unreadable.
pub async fn handle_gitea_source_webhook(
Extension(agent): Extension<Arc<ComplianceAgent>>,
Path(tenant_id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> StatusCode {
let probe = agent.db_pool.for_existing_tenant_id(&tenant_id);
let started = Instant::now();
let status = answer(agent, &tenant_id, &headers, &body).await;
tracing::info!(
tenant_id,
status = status.as_u16(),
elapsed_ms = started.elapsed().as_millis() as u64,
"Gitea source webhook answered"
);
status
}
/// Verify and route a delivery; hand any work to [`process`] in the background.
async fn answer(
agent: Arc<ComplianceAgent>,
tenant_id: &str,
headers: &HeaderMap,
body: &[u8],
) -> StatusCode {
let probe = agent.db_pool.for_existing_tenant_id(tenant_id);
let source = match git_source::load_source(&probe).await {
Ok(Some(source)) if source.enabled => source,
Ok(_) => {
@@ -43,14 +73,14 @@ pub async fn handle_gitea_source_webhook(
);
return StatusCode::UNAUTHORIZED;
};
let signature = header(&headers, "x-gitea-signature");
if !super::gitea::verify_signature(&secret, &body, signature) {
let signature = header(headers, "x-gitea-signature");
if !super::gitea::verify_signature(&secret, body, signature) {
tracing::warn!("Gitea source webhook: invalid signature for tenant '{tenant_id}'");
return StatusCode::UNAUTHORIZED;
}
let event = header(&headers, "x-gitea-event");
let payload: serde_json::Value = match serde_json::from_slice(&body) {
let event = header(headers, "x-gitea-event");
let payload: serde_json::Value = match serde_json::from_slice(body) {
Ok(v) => v,
Err(e) => {
tracing::warn!("Gitea source webhook: invalid JSON: {e}");
@@ -63,29 +93,60 @@ pub async fn handle_gitea_source_webhook(
return StatusCode::OK;
}
// Automated work follows the same entitlement and ladder rules as the
// scheduler. Refused visibly, so the delivery log in Gitea shows it.
if let Err(why) = git_source::automation_allowed(&agent, &tenant_id).await {
tracing::info!(tenant_id, "Gitea source webhook refused: {why}");
return StatusCode::FORBIDDEN;
}
let db = match agent.db_pool.for_tenant_id(&tenant_id).await {
Ok(db) => db,
Err(e) => {
tracing::error!("Gitea source webhook: tenant database: {e}");
return StatusCode::INTERNAL_SERVER_ERROR;
let tenant_id = tenant_id.to_string();
let event = event.to_string();
tokio::spawn(async move {
let started = Instant::now();
let result = process(&agent, &tenant_id, &source, action).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
match result {
Ok(outcome) => tracing::info!(
tenant_id,
event,
elapsed_ms,
%outcome,
"Gitea source webhook handled"
),
Err(why) => tracing::warn!(
tenant_id,
event,
elapsed_ms,
"Gitea source webhook not handled: {why}"
),
}
};
match git_source::apply_action(&agent, &db, &tenant_id, &source, action).await {
Ok(outcome) => {
tracing::info!(tenant_id, event, ?outcome, "Gitea source webhook handled");
StatusCode::OK
}
Err(e) => {
tracing::error!(tenant_id, event, "Gitea source webhook failed: {e}");
StatusCode::INTERNAL_SERVER_ERROR
}
}
});
StatusCode::ACCEPTED
}
/// The work a verified delivery asks for: entitlement, target, scan.
///
/// # Returns
///
/// The outcome for the log.
///
/// # Errors
///
/// Why nothing was done: automation refused for the tenant (same entitlement
/// and ladder rules as the scheduler), or the tenant database or the action
/// failed.
async fn process(
agent: &ComplianceAgent,
tenant_id: &str,
source: &GitSource,
action: events::SourceAction,
) -> Result<String, String> {
git_source::automation_allowed(agent, tenant_id)
.await
.map_err(|why| format!("refused: {why}"))?;
let db = agent
.db_pool
.for_tenant_id(tenant_id)
.await
.map_err(|e| format!("tenant database: {e}"))?;
let outcome = git_source::apply_action(agent, &db, tenant_id, source, action)
.await
.map_err(|e| e.to_string())?;
Ok(format!("{outcome:?}"))
}
fn header<'a>(headers: &'a HeaderMap, name: &str) -> &'a str {
+46 -21
View File
@@ -1,8 +1,9 @@
//! Managed git source (#439) against a live Mongo: the platform API stores the
//! source sealed and hands out the webhook secret once, the org webhook is
//! HMAC-checked and creates exactly one target per repository however often
//! (or concurrently) it is delivered, deletion archives, and the sync diffs a
//! mocked Gitea listing. Skips cleanly when no Mongo is reachable.
//! HMAC-checked, answers 202 and creates exactly one target per repository in
//! the background however often (or concurrently) it is delivered, deletion
//! archives, and the sync diffs a mocked Gitea listing. Skips cleanly when no
//! Mongo is reachable.
//!
//! Every repository here is empty, so no scan (and no clone) is started.
@@ -24,6 +25,7 @@ use compliance_agent::database::{Database, DatabasePool};
use compliance_agent::error::AgentError;
use compliance_agent::git_source::gitea::{GiteaRepo, RepoLister};
use compliance_agent::webhooks::gitea_source::handle_gitea_source_webhook;
use compliance_core::models::OnboardedTarget;
use common::dev_config;
@@ -126,6 +128,29 @@ impl Harness {
req.body(bytes).send().await.unwrap().status().as_u16()
}
/// Poll `check` until it holds: the webhook's work runs after its answer.
async fn eventually<F, Fut>(what: &str, mut check: F)
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = bool>,
{
for _ in 0..100 {
if check().await {
return;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
panic!("{what} did not happen within 5 s");
}
async fn target(&self, repo_id: i64) -> Option<OnboardedTarget> {
self.db
.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": repo_id })
.await
.unwrap()
}
async fn managed_count(&self, repo_id: i64) -> u64 {
self.db
.onboarded_targets()
@@ -255,25 +280,28 @@ async fn platform_api_webhook_and_sync() {
);
assert_eq!(h.managed_count(11).await, 0);
// Twice at once and once more: one target.
// Twice at once and once more: accepted at once, one target.
let sig = sign(&secret, &body);
let (a, b) = tokio::join!(
h.deliver(TENANT, "repository", &created_evt, Some(sig.clone())),
h.deliver(TENANT, "repository", &created_evt, Some(sig.clone())),
);
assert_eq!((a, b), (200, 200));
assert_eq!((a, b), (202, 202));
Harness::eventually("the first target", || async {
h.target(11)
.await
.is_some_and(|t| t.classification.is_some())
})
.await;
assert_eq!(
h.deliver(TENANT, "repository", &created_evt, Some(sig))
.await,
200
202
);
// Let the third delivery's refresh finish before the deletion below.
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
assert_eq!(h.managed_count(11).await, 1);
let target =
h.db.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": 11_i64 })
.await
.unwrap()
.unwrap();
let target = h.target(11).await.unwrap();
assert_eq!(target.name, "kunde/fw");
assert_eq!(
target.code_artifact().unwrap().source_ref,
@@ -281,7 +309,7 @@ async fn platform_api_webhook_and_sync() {
);
assert!(target.classification.is_some(), "detection ran");
// Another organisation's repository is ignored.
// Another organisation's repository is ignored, and said so at once.
let other =
serde_json::json!({ "action": "created", "repository": repo_json(12, "andere", "x") });
let ob = serde_json::to_vec(&other).unwrap();
@@ -299,15 +327,12 @@ async fn platform_api_webhook_and_sync() {
assert_eq!(
h.deliver(TENANT, "repository", &deleted, Some(sign(&secret, &db_)))
.await,
200
202
);
let target =
h.db.onboarded_targets()
.find_one(doc! { "source_repo.repo_id": 11_i64 })
.await
.unwrap()
.unwrap();
assert!(target.archived_at.is_some());
Harness::eventually("the archive", || async {
h.target(11).await.is_some_and(|t| t.archived_at.is_some())
})
.await;
// ── sync against a mocked listing ───────────────────────────────────
struct Listing(Vec<GiteaRepo>);