305 lines
11 KiB
Rust
305 lines
11 KiB
Rust
//! `POST /webhook/{tenant_id}/gitea-source` — the system/org webhook of a
|
|
//! tenant's managed Gitea (#439).
|
|
//!
|
|
//! 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.
|
|
//! What became of it (handled, refused, failed) is recorded for the target
|
|
//! page, since Gitea's delivery log only ever sees the `202`.
|
|
|
|
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::{DeliveryResult, GitSource, SourceRepo, WebhookDelivery};
|
|
|
|
use super::deliveries;
|
|
use crate::agent::ComplianceAgent;
|
|
use crate::git_source::{self, events, Outcome};
|
|
|
|
/// This receiver's name in the delivery records.
|
|
const SOURCE: &str = "gitea-source";
|
|
|
|
/// 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 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(_) => {
|
|
tracing::warn!("Gitea source webhook: no enabled git source in tenant '{tenant_id}'");
|
|
return StatusCode::NOT_FOUND;
|
|
}
|
|
Err(e) => {
|
|
tracing::error!("Gitea source webhook: reading the git source failed: {e}");
|
|
return StatusCode::INTERNAL_SERVER_ERROR;
|
|
}
|
|
};
|
|
|
|
// Fail closed: a source whose secret cannot be opened accepts nothing.
|
|
let Some(secret) = agent
|
|
.secrets
|
|
.open_opt(source.webhook_secret.as_ref(), "git source webhook secret")
|
|
else {
|
|
tracing::warn!(
|
|
"Gitea source webhook: tenant '{tenant_id}' has no webhook secret; rejected"
|
|
);
|
|
return StatusCode::UNAUTHORIZED;
|
|
};
|
|
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) {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
tracing::warn!("Gitea source webhook: invalid JSON: {e}");
|
|
return StatusCode::BAD_REQUEST;
|
|
}
|
|
};
|
|
let action = events::route_event(event, &payload, &source.org);
|
|
if let events::SourceAction::Ignore(why) = action {
|
|
tracing::debug!(tenant_id, event, "Gitea source webhook ignored: {why}");
|
|
return StatusCode::OK;
|
|
}
|
|
|
|
let tenant_id = tenant_id.to_string();
|
|
let event = event.to_string();
|
|
tokio::spawn(async move {
|
|
let (received_at, started) = (chrono::Utc::now(), Instant::now());
|
|
let repo = action.repo().map(|repo| SourceRepo {
|
|
base_url: source.base_url.clone(),
|
|
repo_id: repo.id,
|
|
full_name: repo.full_name.clone(),
|
|
});
|
|
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}"
|
|
),
|
|
}
|
|
let mut delivery = delivery_of(&event, &result);
|
|
delivery.received_at = received_at;
|
|
delivery.elapsed_ms = elapsed_ms;
|
|
delivery.source_repo = repo;
|
|
deliveries::record(&agent, &tenant_id, &delivery).await;
|
|
});
|
|
StatusCode::ACCEPTED
|
|
}
|
|
|
|
/// Why a verified delivery did no work.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
enum NotHandled {
|
|
/// Automation refused for the tenant: entitlement, read-only.
|
|
Refused(String),
|
|
/// The tenant database or the action failed.
|
|
Failed(String),
|
|
}
|
|
|
|
impl std::fmt::Display for NotHandled {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
Self::Refused(why) => write!(f, "refused: {why}"),
|
|
Self::Failed(why) => write!(f, "{why}"),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The work a verified delivery asks for: entitlement, target, scan.
|
|
///
|
|
/// # Returns
|
|
///
|
|
/// What was done.
|
|
///
|
|
/// # 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<Outcome, NotHandled> {
|
|
git_source::automation_allowed(agent, tenant_id)
|
|
.await
|
|
.map_err(NotHandled::Refused)?;
|
|
let db = agent
|
|
.db_pool
|
|
.for_tenant_id(tenant_id)
|
|
.await
|
|
.map_err(|e| NotHandled::Failed(format!("tenant database: {e}")))?;
|
|
git_source::apply_action(agent, &db, tenant_id, source, action)
|
|
.await
|
|
.map_err(|e| NotHandled::Failed(e.to_string()))
|
|
}
|
|
|
|
/// The record of a delivery of `event` that came to `result`; the target is
|
|
/// set when the delivery created or found one.
|
|
fn delivery_of(event: &str, result: &Result<Outcome, NotHandled>) -> WebhookDelivery {
|
|
let (outcome, detail, target_id) = match result {
|
|
Ok(Outcome::Ensured { target_id, scan }) => (
|
|
DeliveryResult::Handled,
|
|
if *scan {
|
|
"scan queued"
|
|
} else {
|
|
"target ready, nothing to scan yet"
|
|
},
|
|
Some(target_id.clone()),
|
|
),
|
|
Ok(Outcome::Archived(true)) => (DeliveryResult::Handled, "target archived", None),
|
|
Ok(Outcome::Archived(false)) => {
|
|
(DeliveryResult::Handled, "no active target to archive", None)
|
|
}
|
|
Ok(Outcome::Ignored(why)) => (DeliveryResult::Handled, *why, None),
|
|
Err(NotHandled::Refused(why)) => (DeliveryResult::Refused, why.as_str(), None),
|
|
Err(NotHandled::Failed(why)) => (DeliveryResult::Failed, why.as_str(), None),
|
|
};
|
|
let mut delivery = WebhookDelivery::new(SOURCE, event, outcome, detail);
|
|
delivery.target_id = target_id;
|
|
delivery
|
|
}
|
|
|
|
fn header<'a>(headers: &'a HeaderMap, name: &str) -> &'a str {
|
|
headers
|
|
.get(name)
|
|
.and_then(|v| v.to_str().ok())
|
|
.unwrap_or("")
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
|
mod tests {
|
|
use hmac::{Hmac, Mac};
|
|
use sha2::Sha256;
|
|
|
|
use super::*;
|
|
use crate::webhooks::gitea::verify_signature;
|
|
|
|
#[test]
|
|
fn a_refusal_is_recorded_with_its_reason_and_no_target() {
|
|
let d = delivery_of(
|
|
"push",
|
|
&Err(NotHandled::Refused("not entitled: no licence".into())),
|
|
);
|
|
assert_eq!(d.result, DeliveryResult::Refused);
|
|
assert_eq!(d.detail, "not entitled: no licence");
|
|
assert_eq!((d.source.as_str(), d.event.as_str()), (SOURCE, "push"));
|
|
assert!(d.target_id.is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn a_failure_and_the_handled_outcomes_are_recorded() {
|
|
let d = delivery_of("push", &Err(NotHandled::Failed("db down".into())));
|
|
assert_eq!(
|
|
(d.result, d.detail.as_str()),
|
|
(DeliveryResult::Failed, "db down")
|
|
);
|
|
|
|
let ensured = |scan| Outcome::Ensured {
|
|
target_id: "t1".into(),
|
|
scan,
|
|
};
|
|
let d = delivery_of("push", &Ok(ensured(true)));
|
|
assert_eq!(
|
|
(d.result, d.detail.as_str()),
|
|
(DeliveryResult::Handled, "scan queued")
|
|
);
|
|
assert_eq!(d.target_id.as_deref(), Some("t1"));
|
|
let d = delivery_of("repository", &Ok(ensured(false)));
|
|
assert_eq!(d.detail, "target ready, nothing to scan yet");
|
|
|
|
let d = delivery_of("repository", &Ok(Outcome::Archived(true)));
|
|
assert_eq!(
|
|
(d.result, d.detail.as_str()),
|
|
(DeliveryResult::Handled, "target archived")
|
|
);
|
|
assert!(d.target_id.is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn a_refusal_reads_as_one_in_the_log() {
|
|
assert_eq!(
|
|
NotHandled::Refused("read-only".into()).to_string(),
|
|
"refused: read-only"
|
|
);
|
|
assert_eq!(NotHandled::Failed("db".into()).to_string(), "db");
|
|
}
|
|
|
|
fn sign(secret: &str, body: &[u8]) -> String {
|
|
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
|
|
mac.update(body);
|
|
hex::encode(mac.finalize().into_bytes())
|
|
}
|
|
|
|
#[test]
|
|
fn signature_valid_invalid_missing() {
|
|
let body = br#"{"action":"created"}"#;
|
|
let good = sign("s3cret", body);
|
|
assert!(verify_signature("s3cret", body, &good));
|
|
// another secret, another body, a tampered or non-hex signature
|
|
assert!(!verify_signature("other", body, &good));
|
|
assert!(!verify_signature(
|
|
"s3cret",
|
|
br#"{"action":"deleted"}"#,
|
|
&good
|
|
));
|
|
let mut tampered = good.clone();
|
|
tampered.replace_range(0..1, if good.starts_with('0') { "1" } else { "0" });
|
|
assert!(!verify_signature("s3cret", body, &tampered));
|
|
assert!(!verify_signature("s3cret", body, "zz"));
|
|
// GitHub-style prefix is not Gitea's format
|
|
assert!(!verify_signature("s3cret", body, &format!("sha256={good}")));
|
|
// missing header
|
|
assert!(!verify_signature("s3cret", body, ""));
|
|
}
|
|
}
|