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