| 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, PushEvent, RepoName, Webhook, WebhookDelivery, |
| 20 | WebhookDeliveryId, WebhookId, WebhookSecret, WebhookUrl, is_zero, |
| 21 | repository::{ |
| 22 | MembershipRepository, OrgRepository, RepoRepository, WebhookDeliveryRepository, |
| 23 | WebhookRepository, |
| 24 | }, |
| 25 | }; |
| 26 | |
| 27 | use super::{ |
| 28 | error::{Error, Result}, |
| 29 | port::{GitQuery, WebhookOutcome, WebhookRequest, WebhookSender}, |
| 30 | repo::changeable_repo, |
| 31 | }; |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | pub const PAYLOAD_VERSION: u32 = 1; |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | pub const MAX_PAYLOAD_COMMITS: usize = 20; |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | pub const RETRY_BACKOFF: [Duration; 3] = [ |
| 55 | Duration::from_secs(5), |
| 56 | Duration::from_secs(30), |
| 57 | Duration::from_secs(120), |
| 58 | ]; |
| 59 | |
| 60 | |
| 61 | pub const DELIVERY_LIMIT: usize = 50; |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 68 | pub struct WebhookSummary { |
| 69 | pub id: WebhookId, |
| 70 | pub url: WebhookUrl, |
| 71 | pub active: bool, |
| 72 | pub created_at: SystemTime, |
| 73 | |
| 74 | |
| 75 | pub last: Option<WebhookDelivery>, |
| 76 | } |
| 77 | |
| 78 | |
| 79 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 80 | pub struct WebhookDetail { |
| 81 | pub id: WebhookId, |
| 82 | pub url: WebhookUrl, |
| 83 | pub active: bool, |
| 84 | pub created_at: SystemTime, |
| 85 | pub deliveries: Vec<WebhookDelivery>, |
| 86 | } |
| 87 | |
| 88 | |
| 89 | #[derive(Debug)] |
| 90 | pub struct CreatedWebhook { |
| 91 | pub webhook: Webhook, |
| 92 | pub secret: WebhookSecret, |
| 93 | } |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | #[allow(clippy::too_many_arguments)] |
| 103 | pub async fn create_webhook( |
| 104 | actor: &Actor, |
| 105 | handle: &OrgName, |
| 106 | name: &RepoName, |
| 107 | url: &str, |
| 108 | now: SystemTime, |
| 109 | orgs: &impl OrgRepository, |
| 110 | memberships: &impl MembershipRepository, |
| 111 | repos: &impl RepoRepository, |
| 112 | webhooks: &impl WebhookRepository, |
| 113 | ) -> Result<CreatedWebhook> { |
| 114 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 115 | |
| 116 | let secret = WebhookSecret::generate(); |
| 117 | let webhook = Webhook::new(WebhookId::generate(), repo.id, url, secret.clone(), now)?; |
| 118 | |
| 119 | webhooks.save(&webhook).await?; |
| 120 | |
| 121 | Ok(CreatedWebhook { webhook, secret }) |
| 122 | } |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | #[allow(clippy::too_many_arguments)] |
| 129 | pub async fn list_webhooks( |
| 130 | actor: &Actor, |
| 131 | handle: &OrgName, |
| 132 | name: &RepoName, |
| 133 | orgs: &impl OrgRepository, |
| 134 | memberships: &impl MembershipRepository, |
| 135 | repos: &impl RepoRepository, |
| 136 | webhooks: &impl WebhookRepository, |
| 137 | deliveries: &impl WebhookDeliveryRepository, |
| 138 | ) -> Result<Vec<WebhookSummary>> { |
| 139 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 140 | |
| 141 | let mut listed = Vec::new(); |
| 142 | |
| 143 | for webhook in webhooks.list_by_repo(&repo.id).await? { |
| 144 | let last = deliveries.latest_by_webhook(&webhook.id).await?; |
| 145 | |
| 146 | listed.push(WebhookSummary { |
| 147 | id: webhook.id, |
| 148 | url: webhook.url, |
| 149 | active: webhook.active, |
| 150 | created_at: webhook.created_at, |
| 151 | last, |
| 152 | }); |
| 153 | } |
| 154 | |
| 155 | Ok(listed) |
| 156 | } |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | #[allow(clippy::too_many_arguments)] |
| 164 | pub async fn view_webhook( |
| 165 | actor: &Actor, |
| 166 | handle: &OrgName, |
| 167 | name: &RepoName, |
| 168 | id: &WebhookId, |
| 169 | orgs: &impl OrgRepository, |
| 170 | memberships: &impl MembershipRepository, |
| 171 | repos: &impl RepoRepository, |
| 172 | webhooks: &impl WebhookRepository, |
| 173 | deliveries: &impl WebhookDeliveryRepository, |
| 174 | ) -> Result<WebhookDetail> { |
| 175 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 176 | |
| 177 | let webhook = webhooks |
| 178 | .find(id) |
| 179 | .await? |
| 180 | .filter(|webhook| webhook.repo_id == repo.id) |
| 181 | .ok_or_else(missing)?; |
| 182 | |
| 183 | Ok(WebhookDetail { |
| 184 | deliveries: deliveries |
| 185 | .list_by_webhook(&webhook.id, DELIVERY_LIMIT) |
| 186 | .await?, |
| 187 | id: webhook.id, |
| 188 | url: webhook.url, |
| 189 | active: webhook.active, |
| 190 | created_at: webhook.created_at, |
| 191 | }) |
| 192 | } |
| 193 | |
| 194 | |
| 195 | #[allow(clippy::too_many_arguments)] |
| 196 | pub async fn delete_webhook( |
| 197 | actor: &Actor, |
| 198 | handle: &OrgName, |
| 199 | name: &RepoName, |
| 200 | id: &WebhookId, |
| 201 | orgs: &impl OrgRepository, |
| 202 | memberships: &impl MembershipRepository, |
| 203 | repos: &impl RepoRepository, |
| 204 | webhooks: &impl WebhookRepository, |
| 205 | ) -> Result<()> { |
| 206 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 207 | |
| 208 | let webhook = webhooks |
| 209 | .find(id) |
| 210 | .await? |
| 211 | .filter(|webhook| webhook.repo_id == repo.id) |
| 212 | .ok_or_else(missing)?; |
| 213 | |
| 214 | webhooks.delete(&webhook.id).await?; |
| 215 | |
| 216 | Ok(()) |
| 217 | } |
| 218 | |
| 219 | |
| 220 | #[derive(Debug, Clone)] |
| 221 | pub struct DeliveryContext { |
| 222 | pub handle: OrgName, |
| 223 | pub name: RepoName, |
| 224 | |
| 225 | |
| 226 | |
| 227 | pub repo_url: String, |
| 228 | |
| 229 | |
| 230 | pub pusher: Option<String>, |
| 231 | } |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | pub fn push_payload( |
| 239 | event: &PushEvent, |
| 240 | context: &DeliveryContext, |
| 241 | commits: &[crate::domain::CommitSummary], |
| 242 | ) -> Vec<u8> { |
| 243 | let body = serde_json::json!({ |
| 244 | "version": PAYLOAD_VERSION, |
| 245 | "event": "push", |
| 246 | "repository": { |
| 247 | "handle": context.handle.as_str(), |
| 248 | "name": context.name.as_str(), |
| 249 | "url": context.repo_url, |
| 250 | }, |
| 251 | "ref": event.ref_name.as_str(), |
| 252 | "before": event.before.as_str(), |
| 253 | "after": event.after.as_str(), |
| 254 | "commits": commits |
| 255 | .iter() |
| 256 | .map(|commit| { |
| 257 | serde_json::json!({ |
| 258 | "id": commit.id.as_str(), |
| 259 | "summary": commit.summary, |
| 260 | "author": commit.author_name, |
| 261 | "timestamp": unix(commit.committed_at), |
| 262 | }) |
| 263 | }) |
| 264 | .collect::<Vec<_>>(), |
| 265 | "pusher": { "handle": context.pusher }, |
| 266 | }); |
| 267 | |
| 268 | |
| 269 | |
| 270 | serde_json::to_vec(&body).unwrap_or_else(|_| b"{}".to_vec()) |
| 271 | } |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | fn delivery_headers( |
| 280 | event: &PushEvent, |
| 281 | secret: &WebhookSecret, |
| 282 | body: &[u8], |
| 283 | ) -> Vec<(String, String)> { |
| 284 | vec![ |
| 285 | ("Content-Type".to_owned(), "application/json".to_owned()), |
| 286 | ("X-Steid-Event".to_owned(), "push".to_owned()), |
| 287 | ("X-Steid-Delivery".to_owned(), event.id.to_string()), |
| 288 | ("X-Steid-Signature-256".to_owned(), secret.sign(body)), |
| 289 | ] |
| 290 | } |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 304 | |
| 305 | #[allow(clippy::too_many_arguments)] |
| 306 | pub async fn deliver_push( |
| 307 | events: &[PushEvent], |
| 308 | context: &DeliveryContext, |
| 309 | git: &impl GitQuery, |
| 310 | webhooks: &impl WebhookRepository, |
| 311 | deliveries: &impl WebhookDeliveryRepository, |
| 312 | sender: &impl WebhookSender, |
| 313 | backoff: &[Duration], |
| 314 | ) -> Result<()> { |
| 315 | let Some(first) = events.first() else { |
| 316 | return Ok(()); |
| 317 | }; |
| 318 | |
| 319 | let hooks: Vec<Webhook> = webhooks |
| 320 | .list_by_repo(&first.repo_id) |
| 321 | .await? |
| 322 | .into_iter() |
| 323 | .filter(|hook| hook.active) |
| 324 | .collect(); |
| 325 | |
| 326 | if hooks.is_empty() { |
| 327 | return Ok(()); |
| 328 | } |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | let mut bodies = Vec::with_capacity(events.len()); |
| 334 | |
| 335 | for event in events { |
| 336 | let commits = commits_for(event, context, git).await; |
| 337 | bodies.push((event, push_payload(event, context, &commits))); |
| 338 | } |
| 339 | |
| 340 | join_all(hooks.iter().map(|hook| async { |
| 341 | for (event, body) in &bodies { |
| 342 | deliver_one(hook, event, body, deliveries, sender, backoff).await; |
| 343 | } |
| 344 | })) |
| 345 | .await; |
| 346 | |
| 347 | Ok(()) |
| 348 | } |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | async fn commits_for( |
| 360 | event: &PushEvent, |
| 361 | context: &DeliveryContext, |
| 362 | git: &impl GitQuery, |
| 363 | ) -> Vec<crate::domain::CommitSummary> { |
| 364 | if event.is_delete() { |
| 365 | return Vec::new(); |
| 366 | } |
| 367 | |
| 368 | let base: Option<&ObjectId> = (!is_zero(&event.before)).then_some(&event.before); |
| 369 | |
| 370 | match git |
| 371 | .log_between( |
| 372 | &context.handle, |
| 373 | &context.name, |
| 374 | base, |
| 375 | &event.after, |
| 376 | MAX_PAYLOAD_COMMITS, |
| 377 | ) |
| 378 | .await |
| 379 | { |
| 380 | Ok(commits) => commits, |
| 381 | Err(error) => { |
| 382 | eprintln!( |
| 383 | "steid: could not list the commits of a push to {}/{}: {error}", |
| 384 | context.handle, context.name |
| 385 | ); |
| 386 | Vec::new() |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | |
| 396 | async fn deliver_one( |
| 397 | hook: &Webhook, |
| 398 | event: &PushEvent, |
| 399 | body: &[u8], |
| 400 | deliveries: &impl WebhookDeliveryRepository, |
| 401 | sender: &impl WebhookSender, |
| 402 | backoff: &[Duration], |
| 403 | ) { |
| 404 | for attempt in 0..=backoff.len() { |
| 405 | if attempt > 0 { |
| 406 | tokio::time::sleep(backoff[attempt - 1]).await; |
| 407 | } |
| 408 | |
| 409 | let outcome: WebhookOutcome = sender |
| 410 | .send(WebhookRequest { |
| 411 | url: hook.url.as_str().to_owned(), |
| 412 | headers: delivery_headers(event, &hook.secret, body), |
| 413 | body: body.to_vec(), |
| 414 | }) |
| 415 | .await; |
| 416 | |
| 417 | let delivery = WebhookDelivery::record( |
| 418 | WebhookDeliveryId::generate(), |
| 419 | hook.id.clone(), |
| 420 | event.id.clone(), |
| 421 | attempt as u32 + 1, |
| 422 | outcome.status, |
| 423 | &outcome.body, |
| 424 | outcome.duration.as_millis().min(u128::from(u64::MAX)) as u64, |
| 425 | |
| 426 | |
| 427 | |
| 428 | SystemTime::now(), |
| 429 | ); |
| 430 | |
| 431 | let succeeded = delivery.ok; |
| 432 | |
| 433 | if let Err(error) = deliveries.save(&delivery).await { |
| 434 | eprintln!("steid: a webhook delivery could not be recorded: {error}"); |
| 435 | } |
| 436 | |
| 437 | if succeeded { |
| 438 | return; |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | fn unix(time: SystemTime) -> i64 { |
| 444 | time.duration_since(SystemTime::UNIX_EPOCH) |
| 445 | .map(|elapsed| elapsed.as_secs() as i64) |
| 446 | .unwrap_or(0) |
| 447 | } |
| 448 | |
| 449 | fn missing() -> Error { |
| 450 | DomainError::NotFound { entity: "webhook" }.into() |
| 451 | } |
| 452 | |
| 453 | #[cfg(test)] |
| 454 | mod tests { |
| 455 | use super::*; |
| 456 | use crate::{ |
| 457 | domain::{ |
| 458 | CommitSummary, Membership, MembershipId, ObjectId, OrgId, Organization, PushEvent, |
| 459 | PushEventId, RefName, RepoId, Repository, Role, UserId, Visibility, |
| 460 | }, |
| 461 | infrastructure::{ |
| 462 | git::InMemoryGitQuery, |
| 463 | repository::{ |
| 464 | InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo, |
| 465 | InMemoryWebhookDeliveryRepo, InMemoryWebhookRepo, |
| 466 | }, |
| 467 | webhook::InMemoryWebhookSender, |
| 468 | }, |
| 469 | }; |
| 470 | |
| 471 | |
| 472 | |
| 473 | const INSTANT: [Duration; 3] = [Duration::ZERO, Duration::ZERO, Duration::ZERO]; |
| 474 | |
| 475 | fn oid(prefix: &str) -> ObjectId { |
| 476 | ObjectId::new(format!("{prefix:0>40}")).expect("valid id") |
| 477 | } |
| 478 | |
| 479 | fn outcome(status: Option<u16>, body: &str) -> WebhookOutcome { |
| 480 | WebhookOutcome { |
| 481 | status, |
| 482 | body: body.to_owned(), |
| 483 | duration: Duration::from_millis(7), |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | struct Fixture { |
| 488 | orgs: InMemoryOrgRepo, |
| 489 | memberships: InMemoryMembershipRepo, |
| 490 | repos: InMemoryRepoRepo, |
| 491 | webhooks: InMemoryWebhookRepo, |
| 492 | deliveries: InMemoryWebhookDeliveryRepo, |
| 493 | git: InMemoryGitQuery, |
| 494 | owner: Actor, |
| 495 | member: Actor, |
| 496 | handle: OrgName, |
| 497 | name: RepoName, |
| 498 | repo_id: RepoId, |
| 499 | } |
| 500 | |
| 501 | async fn fixture() -> Fixture { |
| 502 | let orgs = InMemoryOrgRepo::new(); |
| 503 | let memberships = InMemoryMembershipRepo::new(); |
| 504 | let repos = InMemoryRepoRepo::new(); |
| 505 | |
| 506 | let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org"); |
| 507 | orgs.save(&org).await.expect("save org"); |
| 508 | |
| 509 | let owner = UserId::generate(); |
| 510 | let member = UserId::generate(); |
| 511 | |
| 512 | for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] { |
| 513 | memberships |
| 514 | .save(&Membership::new( |
| 515 | MembershipId::generate(), |
| 516 | org.id.clone(), |
| 517 | user.clone(), |
| 518 | role, |
| 519 | )) |
| 520 | .await |
| 521 | .expect("save membership"); |
| 522 | } |
| 523 | |
| 524 | let repo = Repository::new( |
| 525 | RepoId::generate(), |
| 526 | org.id.clone(), |
| 527 | "steid", |
| 528 | None, |
| 529 | Visibility::Public, |
| 530 | SystemTime::UNIX_EPOCH, |
| 531 | ) |
| 532 | .expect("valid repo"); |
| 533 | repos.save(&repo).await.expect("save repo"); |
| 534 | |
| 535 | Fixture { |
| 536 | orgs, |
| 537 | memberships, |
| 538 | repos, |
| 539 | webhooks: InMemoryWebhookRepo::new(), |
| 540 | deliveries: InMemoryWebhookDeliveryRepo::new(), |
| 541 | git: InMemoryGitQuery::default(), |
| 542 | owner: Actor::User(owner), |
| 543 | member: Actor::User(member), |
| 544 | handle: org.name, |
| 545 | name: repo.name, |
| 546 | repo_id: repo.id, |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | impl Fixture { |
| 551 | async fn create(&self, actor: &Actor, url: &str) -> Result<CreatedWebhook> { |
| 552 | create_webhook( |
| 553 | actor, |
| 554 | &self.handle, |
| 555 | &self.name, |
| 556 | url, |
| 557 | SystemTime::UNIX_EPOCH, |
| 558 | &self.orgs, |
| 559 | &self.memberships, |
| 560 | &self.repos, |
| 561 | &self.webhooks, |
| 562 | ) |
| 563 | .await |
| 564 | } |
| 565 | |
| 566 | async fn list(&self, actor: &Actor) -> Result<Vec<WebhookSummary>> { |
| 567 | list_webhooks( |
| 568 | actor, |
| 569 | &self.handle, |
| 570 | &self.name, |
| 571 | &self.orgs, |
| 572 | &self.memberships, |
| 573 | &self.repos, |
| 574 | &self.webhooks, |
| 575 | &self.deliveries, |
| 576 | ) |
| 577 | .await |
| 578 | } |
| 579 | |
| 580 | async fn view(&self, actor: &Actor, id: &WebhookId) -> Result<WebhookDetail> { |
| 581 | view_webhook( |
| 582 | actor, |
| 583 | &self.handle, |
| 584 | &self.name, |
| 585 | id, |
| 586 | &self.orgs, |
| 587 | &self.memberships, |
| 588 | &self.repos, |
| 589 | &self.webhooks, |
| 590 | &self.deliveries, |
| 591 | ) |
| 592 | .await |
| 593 | } |
| 594 | |
| 595 | async fn remove(&self, actor: &Actor, id: &WebhookId) -> Result<()> { |
| 596 | delete_webhook( |
| 597 | actor, |
| 598 | &self.handle, |
| 599 | &self.name, |
| 600 | id, |
| 601 | &self.orgs, |
| 602 | &self.memberships, |
| 603 | &self.repos, |
| 604 | &self.webhooks, |
| 605 | ) |
| 606 | .await |
| 607 | } |
| 608 | |
| 609 | fn context(&self) -> DeliveryContext { |
| 610 | DeliveryContext { |
| 611 | handle: self.handle.clone(), |
| 612 | name: self.name.clone(), |
| 613 | repo_url: "https://steid.example/acme/repos/steid".to_owned(), |
| 614 | pusher: Some("acme".to_owned()), |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | fn event(&self, name: &str, before: ObjectId, after: ObjectId) -> PushEvent { |
| 619 | PushEvent::new( |
| 620 | PushEventId::generate(), |
| 621 | self.repo_id.clone(), |
| 622 | RefName::from_trusted(name), |
| 623 | before, |
| 624 | after, |
| 625 | None, |
| 626 | SystemTime::UNIX_EPOCH, |
| 627 | ) |
| 628 | .expect("valid event") |
| 629 | } |
| 630 | |
| 631 | async fn deliver(&self, events: &[PushEvent], sender: &InMemoryWebhookSender) { |
| 632 | deliver_push( |
| 633 | events, |
| 634 | &self.context(), |
| 635 | &self.git, |
| 636 | &self.webhooks, |
| 637 | &self.deliveries, |
| 638 | sender, |
| 639 | &INSTANT, |
| 640 | ) |
| 641 | .await |
| 642 | .expect("delivery should not fail the push"); |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | |
| 647 | |
| 648 | #[tokio::test] |
| 649 | async fn a_hook_is_created_active_and_its_secret_shown_once() { |
| 650 | let f = fixture().await; |
| 651 | |
| 652 | let created = f |
| 653 | .create(&f.owner, "https://example.com/hook") |
| 654 | .await |
| 655 | .expect("should create"); |
| 656 | |
| 657 | assert!(created.webhook.active); |
| 658 | assert!(created.secret.reveal().starts_with("steid_whs_")); |
| 659 | |
| 660 | let listed = f.list(&f.owner).await.expect("should list"); |
| 661 | assert_eq!(listed.len(), 1); |
| 662 | assert_eq!(listed[0].url.as_str(), "https://example.com/hook"); |
| 663 | assert_eq!(listed[0].last, None, "nothing has been delivered yet"); |
| 664 | } |
| 665 | |
| 666 | #[tokio::test] |
| 667 | async fn a_url_that_would_reach_this_machine_is_refused() { |
| 668 | |
| 669 | |
| 670 | let f = fixture().await; |
| 671 | |
| 672 | assert!( |
| 673 | f.create(&f.owner, "http://127.0.0.1:3000/hook") |
| 674 | .await |
| 675 | .is_err() |
| 676 | ); |
| 677 | assert!(f.create(&f.owner, "file:///etc/passwd").await.is_err()); |
| 678 | assert!(f.list(&f.owner).await.expect("list").is_empty()); |
| 679 | } |
| 680 | |
| 681 | #[tokio::test] |
| 682 | async fn only_an_owner_can_add_read_or_remove_a_hook() { |
| 683 | let f = fixture().await; |
| 684 | let created = f |
| 685 | .create(&f.owner, "https://example.com/hook") |
| 686 | .await |
| 687 | .expect("should create"); |
| 688 | |
| 689 | for actor in [&f.member, &Actor::Anonymous] { |
| 690 | assert!(f.create(actor, "https://example.com/other").await.is_err()); |
| 691 | assert!(f.list(actor).await.is_err()); |
| 692 | assert!(f.view(actor, &created.webhook.id).await.is_err()); |
| 693 | assert!(f.remove(actor, &created.webhook.id).await.is_err()); |
| 694 | } |
| 695 | |
| 696 | assert_eq!(f.list(&f.owner).await.expect("list").len(), 1); |
| 697 | } |
| 698 | |
| 699 | #[tokio::test] |
| 700 | async fn a_hook_id_from_another_repository_is_not_found_rather_than_forbidden() { |
| 701 | |
| 702 | let f = fixture().await; |
| 703 | |
| 704 | let error = f |
| 705 | .view(&f.owner, &WebhookId::generate()) |
| 706 | .await |
| 707 | .expect_err("should refuse"); |
| 708 | |
| 709 | assert!(matches!( |
| 710 | error, |
| 711 | Error::Domain(DomainError::NotFound { entity: "webhook" }) |
| 712 | )); |
| 713 | } |
| 714 | |
| 715 | #[tokio::test] |
| 716 | async fn removing_a_hook_takes_it_off_the_list() { |
| 717 | let f = fixture().await; |
| 718 | let created = f |
| 719 | .create(&f.owner, "https://example.com/hook") |
| 720 | .await |
| 721 | .expect("should create"); |
| 722 | |
| 723 | f.remove(&f.owner, &created.webhook.id) |
| 724 | .await |
| 725 | .expect("should remove"); |
| 726 | |
| 727 | assert!(f.list(&f.owner).await.expect("list").is_empty()); |
| 728 | } |
| 729 | |
| 730 | |
| 731 | |
| 732 | #[test] |
| 733 | fn a_payload_names_the_ref_both_ends_and_the_repository() { |
| 734 | let context = DeliveryContext { |
| 735 | handle: OrgName::new("acme").expect("valid"), |
| 736 | name: RepoName::new("steid").expect("valid"), |
| 737 | repo_url: "https://steid.example/acme/repos/steid".to_owned(), |
| 738 | pusher: Some("acme".to_owned()), |
| 739 | }; |
| 740 | let event = PushEvent::new( |
| 741 | PushEventId::generate(), |
| 742 | RepoId::generate(), |
| 743 | RefName::from_trusted("refs/heads/main"), |
| 744 | oid("a"), |
| 745 | oid("b"), |
| 746 | None, |
| 747 | SystemTime::UNIX_EPOCH, |
| 748 | ) |
| 749 | .expect("valid event"); |
| 750 | |
| 751 | let body = push_payload( |
| 752 | &event, |
| 753 | &context, |
| 754 | &[CommitSummary { |
| 755 | id: oid("b"), |
| 756 | summary: "docs: say what changed".to_owned(), |
| 757 | author_name: "Ada Lovelace".to_owned(), |
| 758 | committed_at: SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000), |
| 759 | }], |
| 760 | ); |
| 761 | |
| 762 | let parsed: serde_json::Value = serde_json::from_slice(&body).expect("valid json"); |
| 763 | |
| 764 | assert_eq!(parsed["version"], PAYLOAD_VERSION); |
| 765 | assert_eq!(parsed["event"], "push"); |
| 766 | assert_eq!(parsed["ref"], "refs/heads/main"); |
| 767 | assert_eq!(parsed["before"], oid("a").as_str()); |
| 768 | assert_eq!(parsed["after"], oid("b").as_str()); |
| 769 | assert_eq!(parsed["repository"]["handle"], "acme"); |
| 770 | assert_eq!(parsed["repository"]["name"], "steid"); |
| 771 | assert_eq!( |
| 772 | parsed["repository"]["url"], |
| 773 | "https://steid.example/acme/repos/steid" |
| 774 | ); |
| 775 | assert_eq!(parsed["pusher"]["handle"], "acme"); |
| 776 | assert_eq!(parsed["commits"][0]["id"], oid("b").as_str()); |
| 777 | assert_eq!(parsed["commits"][0]["summary"], "docs: say what changed"); |
| 778 | assert_eq!(parsed["commits"][0]["author"], "Ada Lovelace"); |
| 779 | assert_eq!(parsed["commits"][0]["timestamp"], 1_700_000_000_i64); |
| 780 | } |
| 781 | |
| 782 | |
| 783 | |
| 784 | #[tokio::test] |
| 785 | async fn a_delivery_carries_a_signature_the_receiver_can_check() { |
| 786 | let f = fixture().await; |
| 787 | let created = f |
| 788 | .create(&f.owner, "https://example.com/hook") |
| 789 | .await |
| 790 | .expect("should create"); |
| 791 | let sender = InMemoryWebhookSender::new(); |
| 792 | |
| 793 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 794 | .await; |
| 795 | |
| 796 | let sent = sender.sent(); |
| 797 | assert_eq!(sent.len(), 1); |
| 798 | assert_eq!(sent[0].url, "https://example.com/hook"); |
| 799 | |
| 800 | let header = |name: &str| { |
| 801 | sent[0] |
| 802 | .headers |
| 803 | .iter() |
| 804 | .find(|(key, _)| key == name) |
| 805 | .map(|(_, value)| value.clone()) |
| 806 | }; |
| 807 | |
| 808 | assert_eq!(header("Content-Type").as_deref(), Some("application/json")); |
| 809 | assert_eq!(header("X-Steid-Event").as_deref(), Some("push")); |
| 810 | assert_eq!( |
| 811 | header("X-Steid-Signature-256"), |
| 812 | Some(created.secret.sign(&sent[0].body)), |
| 813 | "the signature must be over the exact bytes sent" |
| 814 | ); |
| 815 | } |
| 816 | |
| 817 | #[tokio::test] |
| 818 | async fn a_success_is_recorded_once_and_not_retried() { |
| 819 | let f = fixture().await; |
| 820 | let created = f |
| 821 | .create(&f.owner, "https://example.com/hook") |
| 822 | .await |
| 823 | .expect("should create"); |
| 824 | |
| 825 | f.deliver( |
| 826 | &[f.event("refs/heads/main", oid("a"), oid("b"))], |
| 827 | &InMemoryWebhookSender::new(), |
| 828 | ) |
| 829 | .await; |
| 830 | |
| 831 | let recorded = f |
| 832 | .deliveries |
| 833 | .list_by_webhook(&created.webhook.id, 10) |
| 834 | .await |
| 835 | .expect("list"); |
| 836 | |
| 837 | assert_eq!(recorded.len(), 1); |
| 838 | assert_eq!(recorded[0].attempt, 1); |
| 839 | assert!(recorded[0].ok); |
| 840 | } |
| 841 | |
| 842 | #[tokio::test] |
| 843 | async fn a_dead_endpoint_is_retried_and_every_attempt_is_recorded() { |
| 844 | let f = fixture().await; |
| 845 | let created = f |
| 846 | .create(&f.owner, "https://example.com/hook") |
| 847 | .await |
| 848 | .expect("should create"); |
| 849 | let sender = InMemoryWebhookSender::scripted(vec![outcome(None, "connection refused")]); |
| 850 | |
| 851 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 852 | .await; |
| 853 | |
| 854 | let recorded = f |
| 855 | .deliveries |
| 856 | .list_by_webhook(&created.webhook.id, 10) |
| 857 | .await |
| 858 | .expect("list"); |
| 859 | |
| 860 | assert_eq!( |
| 861 | recorded.len(), |
| 862 | INSTANT.len() + 1, |
| 863 | "one initial send plus retries" |
| 864 | ); |
| 865 | assert_eq!(sender.sent().len(), INSTANT.len() + 1); |
| 866 | assert!(recorded.iter().all(|delivery| !delivery.ok)); |
| 867 | assert!( |
| 868 | recorded |
| 869 | .iter() |
| 870 | .all(|delivery| delivery.response == "connection refused") |
| 871 | ); |
| 872 | } |
| 873 | |
| 874 | #[tokio::test] |
| 875 | async fn retrying_stops_as_soon_as_it_is_accepted() { |
| 876 | let f = fixture().await; |
| 877 | let created = f |
| 878 | .create(&f.owner, "https://example.com/hook") |
| 879 | .await |
| 880 | .expect("should create"); |
| 881 | let sender = InMemoryWebhookSender::scripted(vec![ |
| 882 | outcome(Some(500), "boom"), |
| 883 | outcome(Some(204), ""), |
| 884 | outcome(Some(500), "should never be reached"), |
| 885 | ]); |
| 886 | |
| 887 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 888 | .await; |
| 889 | |
| 890 | let recorded = f |
| 891 | .deliveries |
| 892 | .list_by_webhook(&created.webhook.id, 10) |
| 893 | .await |
| 894 | .expect("list"); |
| 895 | |
| 896 | assert_eq!(recorded.len(), 2); |
| 897 | assert_eq!(sender.sent().len(), 2); |
| 898 | assert_eq!( |
| 899 | f.list(&f.owner).await.expect("list")[0].last, |
| 900 | recorded.first().cloned() |
| 901 | ); |
| 902 | } |
| 903 | |
| 904 | #[tokio::test] |
| 905 | async fn a_hook_that_is_off_is_not_delivered_to_but_stays_listed() { |
| 906 | let f = fixture().await; |
| 907 | let created = f |
| 908 | .create(&f.owner, "https://example.com/hook") |
| 909 | .await |
| 910 | .expect("should create"); |
| 911 | |
| 912 | f.webhooks |
| 913 | .save(&Webhook { |
| 914 | active: false, |
| 915 | ..created.webhook.clone() |
| 916 | }) |
| 917 | .await |
| 918 | .expect("save"); |
| 919 | |
| 920 | let sender = InMemoryWebhookSender::new(); |
| 921 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 922 | .await; |
| 923 | |
| 924 | assert!(sender.sent().is_empty()); |
| 925 | assert_eq!(f.list(&f.owner).await.expect("list").len(), 1); |
| 926 | } |
| 927 | |
| 928 | #[tokio::test] |
| 929 | async fn every_event_of_one_push_reaches_every_hook() { |
| 930 | let f = fixture().await; |
| 931 | f.create(&f.owner, "https://example.com/one") |
| 932 | .await |
| 933 | .expect("should create"); |
| 934 | f.create(&f.owner, "https://example.com/two") |
| 935 | .await |
| 936 | .expect("should create"); |
| 937 | |
| 938 | let sender = InMemoryWebhookSender::new(); |
| 939 | f.deliver( |
| 940 | &[ |
| 941 | f.event("refs/heads/main", oid("a"), oid("b")), |
| 942 | f.event("refs/tags/v1", PushEvent::zero(), oid("c")), |
| 943 | ], |
| 944 | &sender, |
| 945 | ) |
| 946 | .await; |
| 947 | |
| 948 | let sent = sender.sent(); |
| 949 | assert_eq!(sent.len(), 4, "two events times two hooks"); |
| 950 | assert_eq!(sent.iter().filter(|r| r.url.ends_with("/one")).count(), 2); |
| 951 | } |
| 952 | |
| 953 | #[tokio::test] |
| 954 | async fn a_push_with_no_hooks_costs_nothing() { |
| 955 | let f = fixture().await; |
| 956 | let sender = InMemoryWebhookSender::new(); |
| 957 | |
| 958 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 959 | .await; |
| 960 | |
| 961 | assert!(sender.sent().is_empty()); |
| 962 | } |
| 963 | |
| 964 | #[tokio::test] |
| 965 | async fn a_deletion_carries_no_commits() { |
| 966 | let f = fixture().await; |
| 967 | f.create(&f.owner, "https://example.com/hook") |
| 968 | .await |
| 969 | .expect("should create"); |
| 970 | |
| 971 | let sender = InMemoryWebhookSender::new(); |
| 972 | f.deliver( |
| 973 | &[f.event("refs/heads/gone", oid("a"), PushEvent::zero())], |
| 974 | &sender, |
| 975 | ) |
| 976 | .await; |
| 977 | |
| 978 | let parsed: serde_json::Value = |
| 979 | serde_json::from_slice(&sender.sent()[0].body).expect("valid json"); |
| 980 | |
| 981 | assert_eq!(parsed["after"], PushEvent::zero().as_str()); |
| 982 | assert_eq!(parsed["commits"].as_array().map(Vec::len), Some(0)); |
| 983 | } |
| 984 | } |