| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::time::{Duration, SystemTime}; |
| 15 | |
| 16 | use futures_util::future::join_all; |
| 17 | |
| 18 | use crate::domain::{ |
| 19 | Actor, DomainError, ObjectId, OrgName, PrivateTargets, PushEvent, PushEventId, RepoName, |
| 20 | Webhook, WebhookDelivery, WebhookDeliveryId, WebhookId, WebhookSecret, WebhookUrl, is_zero, |
| 21 | repository::{ |
| 22 | MembershipRepository, OrgRepository, PushEventRepository, RepoRepository, UserRepository, |
| 23 | WebhookDeliveryRepository, WebhookRepository, |
| 24 | }, |
| 25 | }; |
| 26 | |
| 27 | use super::{ |
| 28 | access::{Stores, changeable_repo}, |
| 29 | error::{Error, Result}, |
| 30 | identity::describe_identity, |
| 31 | paging::{Paged, clamp, offset, page_count}, |
| 32 | port::{Clock, GitQuery, WebhookOutcome, WebhookRequest, WebhookSender}, |
| 33 | }; |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | pub const PAYLOAD_VERSION: u32 = 1; |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | pub const MAX_PAYLOAD_COMMITS: usize = 20; |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | pub const RETRY_BACKOFF: [Duration; 3] = [ |
| 57 | Duration::from_secs(5), |
| 58 | Duration::from_secs(30), |
| 59 | Duration::from_secs(120), |
| 60 | ]; |
| 61 | |
| 62 | |
| 63 | pub const DELIVERY_LIMIT: usize = 50; |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 70 | pub struct WebhookSummary { |
| 71 | pub id: WebhookId, |
| 72 | pub url: WebhookUrl, |
| 73 | pub active: bool, |
| 74 | pub created_at: SystemTime, |
| 75 | |
| 76 | |
| 77 | pub last: Option<WebhookDelivery>, |
| 78 | } |
| 79 | |
| 80 | |
| 81 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 82 | pub struct WebhookDetail { |
| 83 | pub id: WebhookId, |
| 84 | pub url: WebhookUrl, |
| 85 | pub active: bool, |
| 86 | pub created_at: SystemTime, |
| 87 | |
| 88 | pub deliveries: Paged<WebhookDelivery>, |
| 89 | } |
| 90 | |
| 91 | |
| 92 | #[derive(Debug)] |
| 93 | pub struct CreatedWebhook { |
| 94 | pub webhook: Webhook, |
| 95 | pub secret: WebhookSecret, |
| 96 | } |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | #[allow(clippy::too_many_arguments)] |
| 110 | pub async fn create_webhook( |
| 111 | actor: &Actor, |
| 112 | handle: &OrgName, |
| 113 | name: &RepoName, |
| 114 | url: &str, |
| 115 | now: SystemTime, |
| 116 | targets: PrivateTargets, |
| 117 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 118 | webhooks: &impl WebhookRepository, |
| 119 | ) -> Result<CreatedWebhook> { |
| 120 | let repo = changeable_repo(actor, handle, name, stores).await?; |
| 121 | |
| 122 | let secret = WebhookSecret::generate(); |
| 123 | let webhook = Webhook::new( |
| 124 | WebhookId::generate(), |
| 125 | repo.id, |
| 126 | url, |
| 127 | secret.clone(), |
| 128 | now, |
| 129 | targets, |
| 130 | )?; |
| 131 | |
| 132 | webhooks.save(&webhook).await?; |
| 133 | |
| 134 | Ok(CreatedWebhook { webhook, secret }) |
| 135 | } |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | pub async fn list_webhooks( |
| 142 | actor: &Actor, |
| 143 | handle: &OrgName, |
| 144 | name: &RepoName, |
| 145 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 146 | webhooks: &impl WebhookRepository, |
| 147 | deliveries: &impl WebhookDeliveryRepository, |
| 148 | ) -> Result<Vec<WebhookSummary>> { |
| 149 | let repo = changeable_repo(actor, handle, name, stores).await?; |
| 150 | |
| 151 | let mut listed = Vec::new(); |
| 152 | |
| 153 | for webhook in webhooks.list_by_repo(&repo.id).await? { |
| 154 | let last = deliveries.latest_by_webhook(&webhook.id).await?; |
| 155 | |
| 156 | listed.push(WebhookSummary { |
| 157 | id: webhook.id, |
| 158 | url: webhook.url, |
| 159 | active: webhook.active, |
| 160 | created_at: webhook.created_at, |
| 161 | last, |
| 162 | }); |
| 163 | } |
| 164 | |
| 165 | Ok(listed) |
| 166 | } |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | #[allow(clippy::too_many_arguments)] |
| 174 | pub async fn view_webhook( |
| 175 | actor: &Actor, |
| 176 | handle: &OrgName, |
| 177 | name: &RepoName, |
| 178 | id: &WebhookId, |
| 179 | page: usize, |
| 180 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 181 | webhooks: &impl WebhookRepository, |
| 182 | deliveries: &impl WebhookDeliveryRepository, |
| 183 | ) -> Result<WebhookDetail> { |
| 184 | let repo = changeable_repo(actor, handle, name, stores).await?; |
| 185 | |
| 186 | let webhook = webhooks |
| 187 | .find(id) |
| 188 | .await? |
| 189 | .filter(|webhook| webhook.repo_id == repo.id) |
| 190 | .ok_or_else(missing)?; |
| 191 | |
| 192 | let total = deliveries.count_by_webhook(&webhook.id).await?; |
| 193 | let page = clamp(page, page_count(total, DELIVERY_LIMIT)); |
| 194 | let recorded = deliveries |
| 195 | .list_by_webhook(&webhook.id, offset(page, DELIVERY_LIMIT), DELIVERY_LIMIT) |
| 196 | .await?; |
| 197 | |
| 198 | Ok(WebhookDetail { |
| 199 | deliveries: Paged::of(recorded, total, page, DELIVERY_LIMIT), |
| 200 | id: webhook.id, |
| 201 | url: webhook.url, |
| 202 | active: webhook.active, |
| 203 | created_at: webhook.created_at, |
| 204 | }) |
| 205 | } |
| 206 | |
| 207 | |
| 208 | pub async fn delete_webhook( |
| 209 | actor: &Actor, |
| 210 | handle: &OrgName, |
| 211 | name: &RepoName, |
| 212 | id: &WebhookId, |
| 213 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 214 | webhooks: &impl WebhookRepository, |
| 215 | ) -> Result<()> { |
| 216 | let repo = changeable_repo(actor, handle, name, stores).await?; |
| 217 | |
| 218 | let webhook = webhooks |
| 219 | .find(id) |
| 220 | .await? |
| 221 | .filter(|webhook| webhook.repo_id == repo.id) |
| 222 | .ok_or_else(missing)?; |
| 223 | |
| 224 | webhooks.delete(&webhook.id).await?; |
| 225 | |
| 226 | Ok(()) |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | pub async fn set_webhook_active( |
| 240 | actor: &Actor, |
| 241 | handle: &OrgName, |
| 242 | name: &RepoName, |
| 243 | id: &WebhookId, |
| 244 | active: bool, |
| 245 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 246 | webhooks: &impl WebhookRepository, |
| 247 | ) -> Result<Webhook> { |
| 248 | let repo = changeable_repo(actor, handle, name, stores).await?; |
| 249 | |
| 250 | let mut webhook = webhooks |
| 251 | .find(id) |
| 252 | .await? |
| 253 | .filter(|webhook| webhook.repo_id == repo.id) |
| 254 | .ok_or_else(missing)?; |
| 255 | |
| 256 | webhook.active = active; |
| 257 | webhooks.save(&webhook).await?; |
| 258 | |
| 259 | Ok(webhook) |
| 260 | } |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | #[allow(clippy::too_many_arguments)] |
| 285 | pub async fn redeliver( |
| 286 | actor: &Actor, |
| 287 | handle: &OrgName, |
| 288 | name: &RepoName, |
| 289 | hook_id: &WebhookId, |
| 290 | delivery_id: &WebhookDeliveryId, |
| 291 | |
| 292 | |
| 293 | origin: &str, |
| 294 | stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>, |
| 295 | users: &impl UserRepository, |
| 296 | webhooks: &impl WebhookRepository, |
| 297 | deliveries: &impl WebhookDeliveryRepository, |
| 298 | events: &impl PushEventRepository, |
| 299 | git: &impl GitQuery, |
| 300 | sender: &impl WebhookSender, |
| 301 | clock: &impl Clock, |
| 302 | ) -> Result<WebhookDelivery> { |
| 303 | let repo = changeable_repo(actor, handle, name, stores).await?; |
| 304 | |
| 305 | let hook = webhooks |
| 306 | .find(hook_id) |
| 307 | .await? |
| 308 | .filter(|hook| hook.repo_id == repo.id) |
| 309 | .ok_or_else(missing)?; |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | let recorded = deliveries.list_by_webhook(&hook.id, 0, usize::MAX).await?; |
| 320 | |
| 321 | let event_id: PushEventId = recorded |
| 322 | .iter() |
| 323 | .find(|delivery| &delivery.id == delivery_id) |
| 324 | .map(|delivery| delivery.event_id.clone()) |
| 325 | .ok_or(DomainError::NotFound { |
| 326 | entity: "webhook delivery", |
| 327 | })?; |
| 328 | |
| 329 | let event = events |
| 330 | .find(&event_id) |
| 331 | .await? |
| 332 | .filter(|event| event.repo_id == repo.id) |
| 333 | .ok_or(DomainError::NotFound { |
| 334 | entity: "push event", |
| 335 | })?; |
| 336 | |
| 337 | let attempt = recorded |
| 338 | .iter() |
| 339 | .filter(|delivery| delivery.event_id == event_id) |
| 340 | .map(|delivery| delivery.attempt) |
| 341 | .max() |
| 342 | .unwrap_or(0) |
| 343 | + 1; |
| 344 | |
| 345 | let pusher = match &event.pusher { |
| 346 | Some(user_id) => describe_identity(&Actor::User(user_id.clone()), users, stores.orgs) |
| 347 | .await? |
| 348 | .map(|identity| identity.handle.to_string()), |
| 349 | None => None, |
| 350 | }; |
| 351 | |
| 352 | let context = DeliveryContext { |
| 353 | handle: handle.clone(), |
| 354 | name: name.clone(), |
| 355 | repo_url: format!("{origin}/{handle}/repos/{name}"), |
| 356 | pusher, |
| 357 | }; |
| 358 | |
| 359 | let commits = commits_for(&event, &context, git).await; |
| 360 | let body = push_payload(&event, &context, &commits); |
| 361 | |
| 362 | Ok(deliver_one( |
| 363 | &hook, |
| 364 | &event, |
| 365 | &body, |
| 366 | deliveries, |
| 367 | sender, |
| 368 | clock, |
| 369 | &[], |
| 370 | attempt, |
| 371 | ) |
| 372 | .await) |
| 373 | } |
| 374 | |
| 375 | |
| 376 | #[derive(Debug, Clone)] |
| 377 | pub struct DeliveryContext { |
| 378 | pub handle: OrgName, |
| 379 | pub name: RepoName, |
| 380 | |
| 381 | |
| 382 | |
| 383 | pub repo_url: String, |
| 384 | |
| 385 | |
| 386 | pub pusher: Option<String>, |
| 387 | } |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | pub fn push_payload( |
| 395 | event: &PushEvent, |
| 396 | context: &DeliveryContext, |
| 397 | commits: &[crate::domain::CommitSummary], |
| 398 | ) -> Vec<u8> { |
| 399 | let body = serde_json::json!({ |
| 400 | "version": PAYLOAD_VERSION, |
| 401 | "event": "push", |
| 402 | "repository": { |
| 403 | "handle": context.handle.as_str(), |
| 404 | "name": context.name.as_str(), |
| 405 | "url": context.repo_url, |
| 406 | }, |
| 407 | "ref": event.ref_name.as_str(), |
| 408 | "before": event.before.as_str(), |
| 409 | "after": event.after.as_str(), |
| 410 | "commits": commits |
| 411 | .iter() |
| 412 | .map(|commit| { |
| 413 | serde_json::json!({ |
| 414 | "id": commit.id.as_str(), |
| 415 | "summary": commit.summary, |
| 416 | "author": commit.author_name, |
| 417 | "timestamp": unix(commit.committed_at), |
| 418 | }) |
| 419 | }) |
| 420 | .collect::<Vec<_>>(), |
| 421 | "pusher": { "handle": context.pusher }, |
| 422 | }); |
| 423 | |
| 424 | |
| 425 | |
| 426 | serde_json::to_vec(&body).unwrap_or_else(|_| b"{}".to_vec()) |
| 427 | } |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | |
| 433 | |
| 434 | |
| 435 | fn delivery_headers( |
| 436 | event: &PushEvent, |
| 437 | secret: &WebhookSecret, |
| 438 | body: &[u8], |
| 439 | ) -> Vec<(String, String)> { |
| 440 | vec![ |
| 441 | ("Content-Type".to_owned(), "application/json".to_owned()), |
| 442 | ("X-Steid-Event".to_owned(), "push".to_owned()), |
| 443 | ("X-Steid-Delivery".to_owned(), event.id.to_string()), |
| 444 | ("X-Steid-Signature-256".to_owned(), secret.sign(body)), |
| 445 | ] |
| 446 | } |
| 447 | |
| 448 | |
| 449 | |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | |
| 460 | |
| 461 | #[allow(clippy::too_many_arguments)] |
| 462 | pub async fn deliver_push( |
| 463 | events: &[PushEvent], |
| 464 | context: &DeliveryContext, |
| 465 | git: &impl GitQuery, |
| 466 | webhooks: &impl WebhookRepository, |
| 467 | deliveries: &impl WebhookDeliveryRepository, |
| 468 | sender: &impl WebhookSender, |
| 469 | clock: &impl Clock, |
| 470 | backoff: &[Duration], |
| 471 | ) -> Result<()> { |
| 472 | let Some(first) = events.first() else { |
| 473 | return Ok(()); |
| 474 | }; |
| 475 | |
| 476 | let hooks: Vec<Webhook> = webhooks |
| 477 | .list_by_repo(&first.repo_id) |
| 478 | .await? |
| 479 | .into_iter() |
| 480 | .filter(|hook| hook.active) |
| 481 | .collect(); |
| 482 | |
| 483 | if hooks.is_empty() { |
| 484 | return Ok(()); |
| 485 | } |
| 486 | |
| 487 | |
| 488 | |
| 489 | |
| 490 | let mut bodies = Vec::with_capacity(events.len()); |
| 491 | |
| 492 | for event in events { |
| 493 | let commits = commits_for(event, context, git).await; |
| 494 | bodies.push((event, push_payload(event, context, &commits))); |
| 495 | } |
| 496 | |
| 497 | join_all(hooks.iter().map(|hook| async { |
| 498 | for (event, body) in &bodies { |
| 499 | deliver_one(hook, event, body, deliveries, sender, clock, backoff, 1).await; |
| 500 | } |
| 501 | })) |
| 502 | .await; |
| 503 | |
| 504 | Ok(()) |
| 505 | } |
| 506 | |
| 507 | |
| 508 | |
| 509 | |
| 510 | |
| 511 | |
| 512 | |
| 513 | |
| 514 | |
| 515 | |
| 516 | async fn commits_for( |
| 517 | event: &PushEvent, |
| 518 | context: &DeliveryContext, |
| 519 | git: &impl GitQuery, |
| 520 | ) -> Vec<crate::domain::CommitSummary> { |
| 521 | if event.is_delete() { |
| 522 | return Vec::new(); |
| 523 | } |
| 524 | |
| 525 | let base: Option<&ObjectId> = (!is_zero(&event.before)).then_some(&event.before); |
| 526 | |
| 527 | match git |
| 528 | .log_between( |
| 529 | &context.handle, |
| 530 | &context.name, |
| 531 | base, |
| 532 | &event.after, |
| 533 | 0, |
| 534 | MAX_PAYLOAD_COMMITS, |
| 535 | ) |
| 536 | .await |
| 537 | { |
| 538 | Ok(commits) => commits, |
| 539 | Err(error) => { |
| 540 | eprintln!( |
| 541 | "steid: could not list the commits of a push to {}/{}: {error}", |
| 542 | context.handle, context.name |
| 543 | ); |
| 544 | Vec::new() |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | |
| 550 | |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | #[allow(clippy::too_many_arguments)] |
| 561 | async fn deliver_one( |
| 562 | hook: &Webhook, |
| 563 | event: &PushEvent, |
| 564 | body: &[u8], |
| 565 | deliveries: &impl WebhookDeliveryRepository, |
| 566 | sender: &impl WebhookSender, |
| 567 | clock: &impl Clock, |
| 568 | backoff: &[Duration], |
| 569 | first: u32, |
| 570 | ) -> WebhookDelivery { |
| 571 | let mut recorded = None; |
| 572 | |
| 573 | for attempt in 0..=backoff.len() { |
| 574 | if attempt > 0 { |
| 575 | tokio::time::sleep(backoff[attempt - 1]).await; |
| 576 | } |
| 577 | |
| 578 | let outcome: WebhookOutcome = sender |
| 579 | .send(WebhookRequest { |
| 580 | url: hook.url.as_str().to_owned(), |
| 581 | headers: delivery_headers(event, &hook.secret, body), |
| 582 | body: body.to_vec(), |
| 583 | }) |
| 584 | .await; |
| 585 | |
| 586 | let delivery = WebhookDelivery::record( |
| 587 | WebhookDeliveryId::generate(), |
| 588 | hook.id.clone(), |
| 589 | event.id.clone(), |
| 590 | first + attempt as u32, |
| 591 | outcome.status, |
| 592 | &outcome.body, |
| 593 | outcome.duration.as_millis().min(u128::from(u64::MAX)) as u64, |
| 594 | |
| 595 | |
| 596 | |
| 597 | clock.now(), |
| 598 | ); |
| 599 | |
| 600 | let succeeded = delivery.ok; |
| 601 | |
| 602 | if let Err(error) = deliveries.save(&delivery).await { |
| 603 | eprintln!("steid: a webhook delivery could not be recorded: {error}"); |
| 604 | } |
| 605 | |
| 606 | recorded = Some(delivery); |
| 607 | |
| 608 | if succeeded { |
| 609 | break; |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | |
| 614 | |
| 615 | recorded.expect("a delivery always makes at least one attempt") |
| 616 | } |
| 617 | |
| 618 | fn unix(time: SystemTime) -> i64 { |
| 619 | time.duration_since(SystemTime::UNIX_EPOCH) |
| 620 | .map(|elapsed| elapsed.as_secs() as i64) |
| 621 | .unwrap_or(0) |
| 622 | } |
| 623 | |
| 624 | fn missing() -> Error { |
| 625 | DomainError::NotFound { entity: "webhook" }.into() |
| 626 | } |
| 627 | |
| 628 | #[cfg(test)] |
| 629 | #[path = "webhook_tests.rs"] |
| 630 | mod tests; |