| 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 | error::{Error, Result}, |
| 29 | identity::describe_identity, |
| 30 | paging::{Paged, clamp, offset, page_count}, |
| 31 | port::{Clock, GitQuery, WebhookOutcome, WebhookRequest, WebhookSender}, |
| 32 | repo::changeable_repo, |
| 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 | orgs: &impl OrgRepository, |
| 118 | memberships: &impl MembershipRepository, |
| 119 | repos: &impl RepoRepository, |
| 120 | webhooks: &impl WebhookRepository, |
| 121 | ) -> Result<CreatedWebhook> { |
| 122 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 123 | |
| 124 | let secret = WebhookSecret::generate(); |
| 125 | let webhook = Webhook::new( |
| 126 | WebhookId::generate(), |
| 127 | repo.id, |
| 128 | url, |
| 129 | secret.clone(), |
| 130 | now, |
| 131 | targets, |
| 132 | )?; |
| 133 | |
| 134 | webhooks.save(&webhook).await?; |
| 135 | |
| 136 | Ok(CreatedWebhook { webhook, secret }) |
| 137 | } |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | #[allow(clippy::too_many_arguments)] |
| 144 | pub async fn list_webhooks( |
| 145 | actor: &Actor, |
| 146 | handle: &OrgName, |
| 147 | name: &RepoName, |
| 148 | orgs: &impl OrgRepository, |
| 149 | memberships: &impl MembershipRepository, |
| 150 | repos: &impl RepoRepository, |
| 151 | webhooks: &impl WebhookRepository, |
| 152 | deliveries: &impl WebhookDeliveryRepository, |
| 153 | ) -> Result<Vec<WebhookSummary>> { |
| 154 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 155 | |
| 156 | let mut listed = Vec::new(); |
| 157 | |
| 158 | for webhook in webhooks.list_by_repo(&repo.id).await? { |
| 159 | let last = deliveries.latest_by_webhook(&webhook.id).await?; |
| 160 | |
| 161 | listed.push(WebhookSummary { |
| 162 | id: webhook.id, |
| 163 | url: webhook.url, |
| 164 | active: webhook.active, |
| 165 | created_at: webhook.created_at, |
| 166 | last, |
| 167 | }); |
| 168 | } |
| 169 | |
| 170 | Ok(listed) |
| 171 | } |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | #[allow(clippy::too_many_arguments)] |
| 179 | pub async fn view_webhook( |
| 180 | actor: &Actor, |
| 181 | handle: &OrgName, |
| 182 | name: &RepoName, |
| 183 | id: &WebhookId, |
| 184 | page: usize, |
| 185 | orgs: &impl OrgRepository, |
| 186 | memberships: &impl MembershipRepository, |
| 187 | repos: &impl RepoRepository, |
| 188 | webhooks: &impl WebhookRepository, |
| 189 | deliveries: &impl WebhookDeliveryRepository, |
| 190 | ) -> Result<WebhookDetail> { |
| 191 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 192 | |
| 193 | let webhook = webhooks |
| 194 | .find(id) |
| 195 | .await? |
| 196 | .filter(|webhook| webhook.repo_id == repo.id) |
| 197 | .ok_or_else(missing)?; |
| 198 | |
| 199 | let total = deliveries.count_by_webhook(&webhook.id).await?; |
| 200 | let page = clamp(page, page_count(total, DELIVERY_LIMIT)); |
| 201 | let recorded = deliveries |
| 202 | .list_by_webhook(&webhook.id, offset(page, DELIVERY_LIMIT), DELIVERY_LIMIT) |
| 203 | .await?; |
| 204 | |
| 205 | Ok(WebhookDetail { |
| 206 | deliveries: Paged::of(recorded, total, page, DELIVERY_LIMIT), |
| 207 | id: webhook.id, |
| 208 | url: webhook.url, |
| 209 | active: webhook.active, |
| 210 | created_at: webhook.created_at, |
| 211 | }) |
| 212 | } |
| 213 | |
| 214 | |
| 215 | #[allow(clippy::too_many_arguments)] |
| 216 | pub async fn delete_webhook( |
| 217 | actor: &Actor, |
| 218 | handle: &OrgName, |
| 219 | name: &RepoName, |
| 220 | id: &WebhookId, |
| 221 | orgs: &impl OrgRepository, |
| 222 | memberships: &impl MembershipRepository, |
| 223 | repos: &impl RepoRepository, |
| 224 | webhooks: &impl WebhookRepository, |
| 225 | ) -> Result<()> { |
| 226 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 227 | |
| 228 | let webhook = webhooks |
| 229 | .find(id) |
| 230 | .await? |
| 231 | .filter(|webhook| webhook.repo_id == repo.id) |
| 232 | .ok_or_else(missing)?; |
| 233 | |
| 234 | webhooks.delete(&webhook.id).await?; |
| 235 | |
| 236 | Ok(()) |
| 237 | } |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | #[allow(clippy::too_many_arguments)] |
| 250 | pub async fn set_webhook_active( |
| 251 | actor: &Actor, |
| 252 | handle: &OrgName, |
| 253 | name: &RepoName, |
| 254 | id: &WebhookId, |
| 255 | active: bool, |
| 256 | orgs: &impl OrgRepository, |
| 257 | memberships: &impl MembershipRepository, |
| 258 | repos: &impl RepoRepository, |
| 259 | webhooks: &impl WebhookRepository, |
| 260 | ) -> Result<Webhook> { |
| 261 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 262 | |
| 263 | let mut webhook = webhooks |
| 264 | .find(id) |
| 265 | .await? |
| 266 | .filter(|webhook| webhook.repo_id == repo.id) |
| 267 | .ok_or_else(missing)?; |
| 268 | |
| 269 | webhook.active = active; |
| 270 | webhooks.save(&webhook).await?; |
| 271 | |
| 272 | Ok(webhook) |
| 273 | } |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | #[allow(clippy::too_many_arguments)] |
| 298 | pub async fn redeliver( |
| 299 | actor: &Actor, |
| 300 | handle: &OrgName, |
| 301 | name: &RepoName, |
| 302 | hook_id: &WebhookId, |
| 303 | delivery_id: &WebhookDeliveryId, |
| 304 | |
| 305 | |
| 306 | origin: &str, |
| 307 | orgs: &impl OrgRepository, |
| 308 | memberships: &impl MembershipRepository, |
| 309 | repos: &impl RepoRepository, |
| 310 | users: &impl UserRepository, |
| 311 | webhooks: &impl WebhookRepository, |
| 312 | deliveries: &impl WebhookDeliveryRepository, |
| 313 | events: &impl PushEventRepository, |
| 314 | git: &impl GitQuery, |
| 315 | sender: &impl WebhookSender, |
| 316 | clock: &impl Clock, |
| 317 | ) -> Result<WebhookDelivery> { |
| 318 | let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?; |
| 319 | |
| 320 | let hook = webhooks |
| 321 | .find(hook_id) |
| 322 | .await? |
| 323 | .filter(|hook| hook.repo_id == repo.id) |
| 324 | .ok_or_else(missing)?; |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | let recorded = deliveries.list_by_webhook(&hook.id, 0, usize::MAX).await?; |
| 335 | |
| 336 | let event_id: PushEventId = recorded |
| 337 | .iter() |
| 338 | .find(|delivery| &delivery.id == delivery_id) |
| 339 | .map(|delivery| delivery.event_id.clone()) |
| 340 | .ok_or(DomainError::NotFound { |
| 341 | entity: "webhook delivery", |
| 342 | })?; |
| 343 | |
| 344 | let event = events |
| 345 | .find(&event_id) |
| 346 | .await? |
| 347 | .filter(|event| event.repo_id == repo.id) |
| 348 | .ok_or(DomainError::NotFound { |
| 349 | entity: "push event", |
| 350 | })?; |
| 351 | |
| 352 | let attempt = recorded |
| 353 | .iter() |
| 354 | .filter(|delivery| delivery.event_id == event_id) |
| 355 | .map(|delivery| delivery.attempt) |
| 356 | .max() |
| 357 | .unwrap_or(0) |
| 358 | + 1; |
| 359 | |
| 360 | let pusher = match &event.pusher { |
| 361 | Some(user_id) => describe_identity(&Actor::User(user_id.clone()), users, orgs) |
| 362 | .await? |
| 363 | .map(|identity| identity.handle.to_string()), |
| 364 | None => None, |
| 365 | }; |
| 366 | |
| 367 | let context = DeliveryContext { |
| 368 | handle: handle.clone(), |
| 369 | name: name.clone(), |
| 370 | repo_url: format!("{origin}/{handle}/repos/{name}"), |
| 371 | pusher, |
| 372 | }; |
| 373 | |
| 374 | let commits = commits_for(&event, &context, git).await; |
| 375 | let body = push_payload(&event, &context, &commits); |
| 376 | |
| 377 | Ok(deliver_one( |
| 378 | &hook, |
| 379 | &event, |
| 380 | &body, |
| 381 | deliveries, |
| 382 | sender, |
| 383 | clock, |
| 384 | &[], |
| 385 | attempt, |
| 386 | ) |
| 387 | .await) |
| 388 | } |
| 389 | |
| 390 | |
| 391 | #[derive(Debug, Clone)] |
| 392 | pub struct DeliveryContext { |
| 393 | pub handle: OrgName, |
| 394 | pub name: RepoName, |
| 395 | |
| 396 | |
| 397 | |
| 398 | pub repo_url: String, |
| 399 | |
| 400 | |
| 401 | pub pusher: Option<String>, |
| 402 | } |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | |
| 409 | pub fn push_payload( |
| 410 | event: &PushEvent, |
| 411 | context: &DeliveryContext, |
| 412 | commits: &[crate::domain::CommitSummary], |
| 413 | ) -> Vec<u8> { |
| 414 | let body = serde_json::json!({ |
| 415 | "version": PAYLOAD_VERSION, |
| 416 | "event": "push", |
| 417 | "repository": { |
| 418 | "handle": context.handle.as_str(), |
| 419 | "name": context.name.as_str(), |
| 420 | "url": context.repo_url, |
| 421 | }, |
| 422 | "ref": event.ref_name.as_str(), |
| 423 | "before": event.before.as_str(), |
| 424 | "after": event.after.as_str(), |
| 425 | "commits": commits |
| 426 | .iter() |
| 427 | .map(|commit| { |
| 428 | serde_json::json!({ |
| 429 | "id": commit.id.as_str(), |
| 430 | "summary": commit.summary, |
| 431 | "author": commit.author_name, |
| 432 | "timestamp": unix(commit.committed_at), |
| 433 | }) |
| 434 | }) |
| 435 | .collect::<Vec<_>>(), |
| 436 | "pusher": { "handle": context.pusher }, |
| 437 | }); |
| 438 | |
| 439 | |
| 440 | |
| 441 | serde_json::to_vec(&body).unwrap_or_else(|_| b"{}".to_vec()) |
| 442 | } |
| 443 | |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | fn delivery_headers( |
| 451 | event: &PushEvent, |
| 452 | secret: &WebhookSecret, |
| 453 | body: &[u8], |
| 454 | ) -> Vec<(String, String)> { |
| 455 | vec![ |
| 456 | ("Content-Type".to_owned(), "application/json".to_owned()), |
| 457 | ("X-Steid-Event".to_owned(), "push".to_owned()), |
| 458 | ("X-Steid-Delivery".to_owned(), event.id.to_string()), |
| 459 | ("X-Steid-Signature-256".to_owned(), secret.sign(body)), |
| 460 | ] |
| 461 | } |
| 462 | |
| 463 | |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 468 | |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | #[allow(clippy::too_many_arguments)] |
| 477 | pub async fn deliver_push( |
| 478 | events: &[PushEvent], |
| 479 | context: &DeliveryContext, |
| 480 | git: &impl GitQuery, |
| 481 | webhooks: &impl WebhookRepository, |
| 482 | deliveries: &impl WebhookDeliveryRepository, |
| 483 | sender: &impl WebhookSender, |
| 484 | clock: &impl Clock, |
| 485 | backoff: &[Duration], |
| 486 | ) -> Result<()> { |
| 487 | let Some(first) = events.first() else { |
| 488 | return Ok(()); |
| 489 | }; |
| 490 | |
| 491 | let hooks: Vec<Webhook> = webhooks |
| 492 | .list_by_repo(&first.repo_id) |
| 493 | .await? |
| 494 | .into_iter() |
| 495 | .filter(|hook| hook.active) |
| 496 | .collect(); |
| 497 | |
| 498 | if hooks.is_empty() { |
| 499 | return Ok(()); |
| 500 | } |
| 501 | |
| 502 | |
| 503 | |
| 504 | |
| 505 | let mut bodies = Vec::with_capacity(events.len()); |
| 506 | |
| 507 | for event in events { |
| 508 | let commits = commits_for(event, context, git).await; |
| 509 | bodies.push((event, push_payload(event, context, &commits))); |
| 510 | } |
| 511 | |
| 512 | join_all(hooks.iter().map(|hook| async { |
| 513 | for (event, body) in &bodies { |
| 514 | deliver_one(hook, event, body, deliveries, sender, clock, backoff, 1).await; |
| 515 | } |
| 516 | })) |
| 517 | .await; |
| 518 | |
| 519 | Ok(()) |
| 520 | } |
| 521 | |
| 522 | |
| 523 | |
| 524 | |
| 525 | |
| 526 | |
| 527 | |
| 528 | |
| 529 | |
| 530 | |
| 531 | async fn commits_for( |
| 532 | event: &PushEvent, |
| 533 | context: &DeliveryContext, |
| 534 | git: &impl GitQuery, |
| 535 | ) -> Vec<crate::domain::CommitSummary> { |
| 536 | if event.is_delete() { |
| 537 | return Vec::new(); |
| 538 | } |
| 539 | |
| 540 | let base: Option<&ObjectId> = (!is_zero(&event.before)).then_some(&event.before); |
| 541 | |
| 542 | match git |
| 543 | .log_between( |
| 544 | &context.handle, |
| 545 | &context.name, |
| 546 | base, |
| 547 | &event.after, |
| 548 | 0, |
| 549 | MAX_PAYLOAD_COMMITS, |
| 550 | ) |
| 551 | .await |
| 552 | { |
| 553 | Ok(commits) => commits, |
| 554 | Err(error) => { |
| 555 | eprintln!( |
| 556 | "steid: could not list the commits of a push to {}/{}: {error}", |
| 557 | context.handle, context.name |
| 558 | ); |
| 559 | Vec::new() |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | |
| 565 | |
| 566 | |
| 567 | |
| 568 | |
| 569 | |
| 570 | |
| 571 | |
| 572 | |
| 573 | |
| 574 | |
| 575 | #[allow(clippy::too_many_arguments)] |
| 576 | async fn deliver_one( |
| 577 | hook: &Webhook, |
| 578 | event: &PushEvent, |
| 579 | body: &[u8], |
| 580 | deliveries: &impl WebhookDeliveryRepository, |
| 581 | sender: &impl WebhookSender, |
| 582 | clock: &impl Clock, |
| 583 | backoff: &[Duration], |
| 584 | first: u32, |
| 585 | ) -> WebhookDelivery { |
| 586 | let mut recorded = None; |
| 587 | |
| 588 | for attempt in 0..=backoff.len() { |
| 589 | if attempt > 0 { |
| 590 | tokio::time::sleep(backoff[attempt - 1]).await; |
| 591 | } |
| 592 | |
| 593 | let outcome: WebhookOutcome = sender |
| 594 | .send(WebhookRequest { |
| 595 | url: hook.url.as_str().to_owned(), |
| 596 | headers: delivery_headers(event, &hook.secret, body), |
| 597 | body: body.to_vec(), |
| 598 | }) |
| 599 | .await; |
| 600 | |
| 601 | let delivery = WebhookDelivery::record( |
| 602 | WebhookDeliveryId::generate(), |
| 603 | hook.id.clone(), |
| 604 | event.id.clone(), |
| 605 | first + attempt as u32, |
| 606 | outcome.status, |
| 607 | &outcome.body, |
| 608 | outcome.duration.as_millis().min(u128::from(u64::MAX)) as u64, |
| 609 | |
| 610 | |
| 611 | |
| 612 | clock.now(), |
| 613 | ); |
| 614 | |
| 615 | let succeeded = delivery.ok; |
| 616 | |
| 617 | if let Err(error) = deliveries.save(&delivery).await { |
| 618 | eprintln!("steid: a webhook delivery could not be recorded: {error}"); |
| 619 | } |
| 620 | |
| 621 | recorded = Some(delivery); |
| 622 | |
| 623 | if succeeded { |
| 624 | break; |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | |
| 629 | |
| 630 | recorded.expect("a delivery always makes at least one attempt") |
| 631 | } |
| 632 | |
| 633 | fn unix(time: SystemTime) -> i64 { |
| 634 | time.duration_since(SystemTime::UNIX_EPOCH) |
| 635 | .map(|elapsed| elapsed.as_secs() as i64) |
| 636 | .unwrap_or(0) |
| 637 | } |
| 638 | |
| 639 | fn missing() -> Error { |
| 640 | DomainError::NotFound { entity: "webhook" }.into() |
| 641 | } |
| 642 | |
| 643 | #[cfg(test)] |
| 644 | mod tests { |
| 645 | use super::*; |
| 646 | use crate::{ |
| 647 | domain::{ |
| 648 | CommitSummary, Email, Membership, MembershipId, ObjectId, OrgId, Organization, |
| 649 | PasswordHash, PushEvent, PushEventId, RefName, RepoId, Repository, Role, User, UserId, |
| 650 | Visibility, |
| 651 | }, |
| 652 | infrastructure::{ |
| 653 | clock::FixedClock, |
| 654 | git::InMemoryGitQuery, |
| 655 | repository::{ |
| 656 | InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryPushEventRepo, InMemoryRepoRepo, |
| 657 | InMemoryUserRepo, InMemoryWebhookDeliveryRepo, InMemoryWebhookRepo, |
| 658 | }, |
| 659 | webhook::InMemoryWebhookSender, |
| 660 | }, |
| 661 | }; |
| 662 | |
| 663 | |
| 664 | |
| 665 | const INSTANT: [Duration; 3] = [Duration::ZERO, Duration::ZERO, Duration::ZERO]; |
| 666 | |
| 667 | |
| 668 | |
| 669 | fn delivered_at() -> FixedClock { |
| 670 | FixedClock::at_epoch_plus(1_700_000_000) |
| 671 | } |
| 672 | |
| 673 | fn oid(prefix: &str) -> ObjectId { |
| 674 | ObjectId::new(format!("{prefix:0>40}")).expect("valid id") |
| 675 | } |
| 676 | |
| 677 | fn outcome(status: Option<u16>, body: &str) -> WebhookOutcome { |
| 678 | WebhookOutcome { |
| 679 | status, |
| 680 | body: body.to_owned(), |
| 681 | duration: Duration::from_millis(7), |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | struct Fixture { |
| 686 | orgs: InMemoryOrgRepo, |
| 687 | memberships: InMemoryMembershipRepo, |
| 688 | repos: InMemoryRepoRepo, |
| 689 | users: InMemoryUserRepo, |
| 690 | events: InMemoryPushEventRepo, |
| 691 | webhooks: InMemoryWebhookRepo, |
| 692 | deliveries: InMemoryWebhookDeliveryRepo, |
| 693 | git: InMemoryGitQuery, |
| 694 | owner: Actor, |
| 695 | owner_id: UserId, |
| 696 | member: Actor, |
| 697 | handle: OrgName, |
| 698 | name: RepoName, |
| 699 | repo_id: RepoId, |
| 700 | } |
| 701 | |
| 702 | async fn fixture() -> Fixture { |
| 703 | let orgs = InMemoryOrgRepo::new(); |
| 704 | let memberships = InMemoryMembershipRepo::new(); |
| 705 | let repos = InMemoryRepoRepo::new(); |
| 706 | |
| 707 | let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org"); |
| 708 | orgs.save(&org).await.expect("save org"); |
| 709 | |
| 710 | let owner = UserId::generate(); |
| 711 | let member = UserId::generate(); |
| 712 | |
| 713 | |
| 714 | |
| 715 | let users = InMemoryUserRepo::new(); |
| 716 | users |
| 717 | .save(&User::new( |
| 718 | owner.clone(), |
| 719 | Email::new("ada@example.com").expect("valid email"), |
| 720 | PasswordHash::from_trusted("$argon2id$test"), |
| 721 | org.id.clone(), |
| 722 | )) |
| 723 | .await |
| 724 | .expect("save user"); |
| 725 | |
| 726 | for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] { |
| 727 | memberships |
| 728 | .save(&Membership::new( |
| 729 | MembershipId::generate(), |
| 730 | org.id.clone(), |
| 731 | user.clone(), |
| 732 | role, |
| 733 | )) |
| 734 | .await |
| 735 | .expect("save membership"); |
| 736 | } |
| 737 | |
| 738 | let repo = Repository::new( |
| 739 | RepoId::generate(), |
| 740 | org.id.clone(), |
| 741 | "steid", |
| 742 | None, |
| 743 | Visibility::Public, |
| 744 | SystemTime::UNIX_EPOCH, |
| 745 | ) |
| 746 | .expect("valid repo"); |
| 747 | repos.save(&repo).await.expect("save repo"); |
| 748 | |
| 749 | Fixture { |
| 750 | orgs, |
| 751 | memberships, |
| 752 | repos, |
| 753 | users, |
| 754 | events: InMemoryPushEventRepo::new(), |
| 755 | webhooks: InMemoryWebhookRepo::new(), |
| 756 | deliveries: InMemoryWebhookDeliveryRepo::new(), |
| 757 | git: InMemoryGitQuery::default(), |
| 758 | owner: Actor::User(owner.clone()), |
| 759 | owner_id: owner, |
| 760 | member: Actor::User(member), |
| 761 | handle: org.name, |
| 762 | name: repo.name, |
| 763 | repo_id: repo.id, |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | impl Fixture { |
| 768 | async fn create(&self, actor: &Actor, url: &str) -> Result<CreatedWebhook> { |
| 769 | create_webhook( |
| 770 | actor, |
| 771 | &self.handle, |
| 772 | &self.name, |
| 773 | url, |
| 774 | SystemTime::UNIX_EPOCH, |
| 775 | PrivateTargets::Refused, |
| 776 | &self.orgs, |
| 777 | &self.memberships, |
| 778 | &self.repos, |
| 779 | &self.webhooks, |
| 780 | ) |
| 781 | .await |
| 782 | } |
| 783 | |
| 784 | async fn list(&self, actor: &Actor) -> Result<Vec<WebhookSummary>> { |
| 785 | list_webhooks( |
| 786 | actor, |
| 787 | &self.handle, |
| 788 | &self.name, |
| 789 | &self.orgs, |
| 790 | &self.memberships, |
| 791 | &self.repos, |
| 792 | &self.webhooks, |
| 793 | &self.deliveries, |
| 794 | ) |
| 795 | .await |
| 796 | } |
| 797 | |
| 798 | async fn view(&self, actor: &Actor, id: &WebhookId) -> Result<WebhookDetail> { |
| 799 | self.view_page(actor, id, 1).await |
| 800 | } |
| 801 | |
| 802 | async fn view_page( |
| 803 | &self, |
| 804 | actor: &Actor, |
| 805 | id: &WebhookId, |
| 806 | page: usize, |
| 807 | ) -> Result<WebhookDetail> { |
| 808 | view_webhook( |
| 809 | actor, |
| 810 | &self.handle, |
| 811 | &self.name, |
| 812 | id, |
| 813 | page, |
| 814 | &self.orgs, |
| 815 | &self.memberships, |
| 816 | &self.repos, |
| 817 | &self.webhooks, |
| 818 | &self.deliveries, |
| 819 | ) |
| 820 | .await |
| 821 | } |
| 822 | |
| 823 | async fn remove(&self, actor: &Actor, id: &WebhookId) -> Result<()> { |
| 824 | delete_webhook( |
| 825 | actor, |
| 826 | &self.handle, |
| 827 | &self.name, |
| 828 | id, |
| 829 | &self.orgs, |
| 830 | &self.memberships, |
| 831 | &self.repos, |
| 832 | &self.webhooks, |
| 833 | ) |
| 834 | .await |
| 835 | } |
| 836 | |
| 837 | fn context(&self) -> DeliveryContext { |
| 838 | DeliveryContext { |
| 839 | handle: self.handle.clone(), |
| 840 | name: self.name.clone(), |
| 841 | repo_url: "https://steid.example/acme/repos/steid".to_owned(), |
| 842 | pusher: Some("acme".to_owned()), |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | fn event(&self, name: &str, before: ObjectId, after: ObjectId) -> PushEvent { |
| 847 | PushEvent::new( |
| 848 | PushEventId::generate(), |
| 849 | self.repo_id.clone(), |
| 850 | RefName::from_trusted(name), |
| 851 | before, |
| 852 | after, |
| 853 | |
| 854 | |
| 855 | Some(self.owner_id.clone()), |
| 856 | SystemTime::UNIX_EPOCH, |
| 857 | ) |
| 858 | .expect("valid event") |
| 859 | } |
| 860 | |
| 861 | async fn set_active(&self, actor: &Actor, id: &WebhookId, active: bool) -> Result<Webhook> { |
| 862 | set_webhook_active( |
| 863 | actor, |
| 864 | &self.handle, |
| 865 | &self.name, |
| 866 | id, |
| 867 | active, |
| 868 | &self.orgs, |
| 869 | &self.memberships, |
| 870 | &self.repos, |
| 871 | &self.webhooks, |
| 872 | ) |
| 873 | .await |
| 874 | } |
| 875 | |
| 876 | async fn again( |
| 877 | &self, |
| 878 | actor: &Actor, |
| 879 | hook: &WebhookId, |
| 880 | delivery: &WebhookDeliveryId, |
| 881 | sender: &InMemoryWebhookSender, |
| 882 | ) -> Result<WebhookDelivery> { |
| 883 | redeliver( |
| 884 | actor, |
| 885 | &self.handle, |
| 886 | &self.name, |
| 887 | hook, |
| 888 | delivery, |
| 889 | "https://steid.example", |
| 890 | &self.orgs, |
| 891 | &self.memberships, |
| 892 | &self.repos, |
| 893 | &self.users, |
| 894 | &self.webhooks, |
| 895 | &self.deliveries, |
| 896 | &self.events, |
| 897 | &self.git, |
| 898 | sender, |
| 899 | &delivered_at(), |
| 900 | ) |
| 901 | .await |
| 902 | } |
| 903 | |
| 904 | |
| 905 | async fn record(&self, event: &PushEvent) { |
| 906 | self.events.save(event).await.expect("save event"); |
| 907 | } |
| 908 | |
| 909 | async fn deliver(&self, events: &[PushEvent], sender: &InMemoryWebhookSender) { |
| 910 | deliver_push( |
| 911 | events, |
| 912 | &self.context(), |
| 913 | &self.git, |
| 914 | &self.webhooks, |
| 915 | &self.deliveries, |
| 916 | sender, |
| 917 | &delivered_at(), |
| 918 | &INSTANT, |
| 919 | ) |
| 920 | .await |
| 921 | .expect("delivery should not fail the push"); |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | |
| 926 | |
| 927 | #[tokio::test] |
| 928 | async fn a_hook_is_created_active_and_its_secret_shown_once() { |
| 929 | let f = fixture().await; |
| 930 | |
| 931 | let created = f |
| 932 | .create(&f.owner, "https://example.com/hook") |
| 933 | .await |
| 934 | .expect("should create"); |
| 935 | |
| 936 | assert!(created.webhook.active); |
| 937 | assert!(created.secret.reveal().starts_with("steid_whs_")); |
| 938 | |
| 939 | let listed = f.list(&f.owner).await.expect("should list"); |
| 940 | assert_eq!(listed.len(), 1); |
| 941 | assert_eq!(listed[0].url.as_str(), "https://example.com/hook"); |
| 942 | assert_eq!(listed[0].last, None, "nothing has been delivered yet"); |
| 943 | } |
| 944 | |
| 945 | #[tokio::test] |
| 946 | async fn a_url_that_would_reach_this_machine_is_refused() { |
| 947 | |
| 948 | |
| 949 | let f = fixture().await; |
| 950 | |
| 951 | assert!( |
| 952 | f.create(&f.owner, "http://127.0.0.1:3000/hook") |
| 953 | .await |
| 954 | .is_err() |
| 955 | ); |
| 956 | assert!(f.create(&f.owner, "file:///etc/passwd").await.is_err()); |
| 957 | assert!(f.list(&f.owner).await.expect("list").is_empty()); |
| 958 | } |
| 959 | |
| 960 | #[tokio::test] |
| 961 | async fn only_an_owner_can_add_read_or_remove_a_hook() { |
| 962 | let f = fixture().await; |
| 963 | let created = f |
| 964 | .create(&f.owner, "https://example.com/hook") |
| 965 | .await |
| 966 | .expect("should create"); |
| 967 | |
| 968 | for actor in [&f.member, &Actor::Anonymous] { |
| 969 | assert!(f.create(actor, "https://example.com/other").await.is_err()); |
| 970 | assert!(f.list(actor).await.is_err()); |
| 971 | assert!(f.view(actor, &created.webhook.id).await.is_err()); |
| 972 | assert!(f.remove(actor, &created.webhook.id).await.is_err()); |
| 973 | } |
| 974 | |
| 975 | assert_eq!(f.list(&f.owner).await.expect("list").len(), 1); |
| 976 | } |
| 977 | |
| 978 | #[tokio::test] |
| 979 | async fn a_hook_id_from_another_repository_is_not_found_rather_than_forbidden() { |
| 980 | |
| 981 | let f = fixture().await; |
| 982 | |
| 983 | let error = f |
| 984 | .view(&f.owner, &WebhookId::generate()) |
| 985 | .await |
| 986 | .expect_err("should refuse"); |
| 987 | |
| 988 | assert!(matches!( |
| 989 | error, |
| 990 | Error::Domain(DomainError::NotFound { entity: "webhook" }) |
| 991 | )); |
| 992 | } |
| 993 | |
| 994 | #[tokio::test] |
| 995 | async fn removing_a_hook_takes_it_off_the_list() { |
| 996 | let f = fixture().await; |
| 997 | let created = f |
| 998 | .create(&f.owner, "https://example.com/hook") |
| 999 | .await |
| 1000 | .expect("should create"); |
| 1001 | |
| 1002 | f.remove(&f.owner, &created.webhook.id) |
| 1003 | .await |
| 1004 | .expect("should remove"); |
| 1005 | |
| 1006 | assert!(f.list(&f.owner).await.expect("list").is_empty()); |
| 1007 | } |
| 1008 | |
| 1009 | |
| 1010 | |
| 1011 | #[test] |
| 1012 | fn a_payload_names_the_ref_both_ends_and_the_repository() { |
| 1013 | let context = DeliveryContext { |
| 1014 | handle: OrgName::new("acme").expect("valid"), |
| 1015 | name: RepoName::new("steid").expect("valid"), |
| 1016 | repo_url: "https://steid.example/acme/repos/steid".to_owned(), |
| 1017 | pusher: Some("acme".to_owned()), |
| 1018 | }; |
| 1019 | let event = PushEvent::new( |
| 1020 | PushEventId::generate(), |
| 1021 | RepoId::generate(), |
| 1022 | RefName::from_trusted("refs/heads/main"), |
| 1023 | oid("a"), |
| 1024 | oid("b"), |
| 1025 | None, |
| 1026 | SystemTime::UNIX_EPOCH, |
| 1027 | ) |
| 1028 | .expect("valid event"); |
| 1029 | |
| 1030 | let body = push_payload( |
| 1031 | &event, |
| 1032 | &context, |
| 1033 | &[CommitSummary { |
| 1034 | id: oid("b"), |
| 1035 | summary: "docs: say what changed".to_owned(), |
| 1036 | author_name: "Ada Lovelace".to_owned(), |
| 1037 | committed_at: SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000), |
| 1038 | }], |
| 1039 | ); |
| 1040 | |
| 1041 | let parsed: serde_json::Value = serde_json::from_slice(&body).expect("valid json"); |
| 1042 | |
| 1043 | assert_eq!(parsed["version"], PAYLOAD_VERSION); |
| 1044 | assert_eq!(parsed["event"], "push"); |
| 1045 | assert_eq!(parsed["ref"], "refs/heads/main"); |
| 1046 | assert_eq!(parsed["before"], oid("a").as_str()); |
| 1047 | assert_eq!(parsed["after"], oid("b").as_str()); |
| 1048 | assert_eq!(parsed["repository"]["handle"], "acme"); |
| 1049 | assert_eq!(parsed["repository"]["name"], "steid"); |
| 1050 | assert_eq!( |
| 1051 | parsed["repository"]["url"], |
| 1052 | "https://steid.example/acme/repos/steid" |
| 1053 | ); |
| 1054 | assert_eq!(parsed["pusher"]["handle"], "acme"); |
| 1055 | assert_eq!(parsed["commits"][0]["id"], oid("b").as_str()); |
| 1056 | assert_eq!(parsed["commits"][0]["summary"], "docs: say what changed"); |
| 1057 | assert_eq!(parsed["commits"][0]["author"], "Ada Lovelace"); |
| 1058 | assert_eq!(parsed["commits"][0]["timestamp"], 1_700_000_000_i64); |
| 1059 | } |
| 1060 | |
| 1061 | |
| 1062 | |
| 1063 | #[tokio::test] |
| 1064 | async fn a_delivery_carries_a_signature_the_receiver_can_check() { |
| 1065 | let f = fixture().await; |
| 1066 | let created = f |
| 1067 | .create(&f.owner, "https://example.com/hook") |
| 1068 | .await |
| 1069 | .expect("should create"); |
| 1070 | let sender = InMemoryWebhookSender::new(); |
| 1071 | |
| 1072 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 1073 | .await; |
| 1074 | |
| 1075 | let sent = sender.sent(); |
| 1076 | assert_eq!(sent.len(), 1); |
| 1077 | assert_eq!(sent[0].url, "https://example.com/hook"); |
| 1078 | |
| 1079 | let header = |name: &str| { |
| 1080 | sent[0] |
| 1081 | .headers |
| 1082 | .iter() |
| 1083 | .find(|(key, _)| key == name) |
| 1084 | .map(|(_, value)| value.clone()) |
| 1085 | }; |
| 1086 | |
| 1087 | assert_eq!(header("Content-Type").as_deref(), Some("application/json")); |
| 1088 | assert_eq!(header("X-Steid-Event").as_deref(), Some("push")); |
| 1089 | assert_eq!( |
| 1090 | header("X-Steid-Signature-256"), |
| 1091 | Some(created.secret.sign(&sent[0].body)), |
| 1092 | "the signature must be over the exact bytes sent" |
| 1093 | ); |
| 1094 | } |
| 1095 | |
| 1096 | #[tokio::test] |
| 1097 | async fn a_success_is_recorded_once_and_not_retried() { |
| 1098 | let f = fixture().await; |
| 1099 | let created = f |
| 1100 | .create(&f.owner, "https://example.com/hook") |
| 1101 | .await |
| 1102 | .expect("should create"); |
| 1103 | |
| 1104 | f.deliver( |
| 1105 | &[f.event("refs/heads/main", oid("a"), oid("b"))], |
| 1106 | &InMemoryWebhookSender::new(), |
| 1107 | ) |
| 1108 | .await; |
| 1109 | |
| 1110 | let recorded = f |
| 1111 | .deliveries |
| 1112 | .list_by_webhook(&created.webhook.id, 0, 10) |
| 1113 | .await |
| 1114 | .expect("list"); |
| 1115 | |
| 1116 | assert_eq!(recorded.len(), 1); |
| 1117 | assert_eq!(recorded[0].attempt, 1); |
| 1118 | assert!(recorded[0].ok); |
| 1119 | |
| 1120 | |
| 1121 | assert_eq!(recorded[0].delivered_at, delivered_at().now()); |
| 1122 | } |
| 1123 | |
| 1124 | #[tokio::test] |
| 1125 | async fn a_dead_endpoint_is_retried_and_every_attempt_is_recorded() { |
| 1126 | let f = fixture().await; |
| 1127 | let created = f |
| 1128 | .create(&f.owner, "https://example.com/hook") |
| 1129 | .await |
| 1130 | .expect("should create"); |
| 1131 | let sender = InMemoryWebhookSender::scripted(vec![outcome(None, "connection refused")]); |
| 1132 | |
| 1133 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 1134 | .await; |
| 1135 | |
| 1136 | let recorded = f |
| 1137 | .deliveries |
| 1138 | .list_by_webhook(&created.webhook.id, 0, 10) |
| 1139 | .await |
| 1140 | .expect("list"); |
| 1141 | |
| 1142 | assert_eq!( |
| 1143 | recorded.len(), |
| 1144 | INSTANT.len() + 1, |
| 1145 | "one initial send plus retries" |
| 1146 | ); |
| 1147 | assert_eq!(sender.sent().len(), INSTANT.len() + 1); |
| 1148 | assert!(recorded.iter().all(|delivery| !delivery.ok)); |
| 1149 | assert!( |
| 1150 | recorded |
| 1151 | .iter() |
| 1152 | .all(|delivery| delivery.response == "connection refused") |
| 1153 | ); |
| 1154 | } |
| 1155 | |
| 1156 | #[tokio::test] |
| 1157 | async fn retrying_stops_as_soon_as_it_is_accepted() { |
| 1158 | let f = fixture().await; |
| 1159 | let created = f |
| 1160 | .create(&f.owner, "https://example.com/hook") |
| 1161 | .await |
| 1162 | .expect("should create"); |
| 1163 | let sender = InMemoryWebhookSender::scripted(vec![ |
| 1164 | outcome(Some(500), "boom"), |
| 1165 | outcome(Some(204), ""), |
| 1166 | outcome(Some(500), "should never be reached"), |
| 1167 | ]); |
| 1168 | |
| 1169 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 1170 | .await; |
| 1171 | |
| 1172 | let recorded = f |
| 1173 | .deliveries |
| 1174 | .list_by_webhook(&created.webhook.id, 0, 10) |
| 1175 | .await |
| 1176 | .expect("list"); |
| 1177 | |
| 1178 | assert_eq!(recorded.len(), 2); |
| 1179 | assert_eq!(sender.sent().len(), 2); |
| 1180 | assert_eq!( |
| 1181 | f.list(&f.owner).await.expect("list")[0].last, |
| 1182 | recorded.first().cloned() |
| 1183 | ); |
| 1184 | } |
| 1185 | |
| 1186 | #[tokio::test] |
| 1187 | async fn a_hook_that_is_off_is_not_delivered_to_but_stays_listed() { |
| 1188 | let f = fixture().await; |
| 1189 | let created = f |
| 1190 | .create(&f.owner, "https://example.com/hook") |
| 1191 | .await |
| 1192 | .expect("should create"); |
| 1193 | |
| 1194 | f.webhooks |
| 1195 | .save(&Webhook { |
| 1196 | active: false, |
| 1197 | ..created.webhook.clone() |
| 1198 | }) |
| 1199 | .await |
| 1200 | .expect("save"); |
| 1201 | |
| 1202 | let sender = InMemoryWebhookSender::new(); |
| 1203 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 1204 | .await; |
| 1205 | |
| 1206 | assert!(sender.sent().is_empty()); |
| 1207 | assert_eq!(f.list(&f.owner).await.expect("list").len(), 1); |
| 1208 | } |
| 1209 | |
| 1210 | #[tokio::test] |
| 1211 | async fn every_event_of_one_push_reaches_every_hook() { |
| 1212 | let f = fixture().await; |
| 1213 | f.create(&f.owner, "https://example.com/one") |
| 1214 | .await |
| 1215 | .expect("should create"); |
| 1216 | f.create(&f.owner, "https://example.com/two") |
| 1217 | .await |
| 1218 | .expect("should create"); |
| 1219 | |
| 1220 | let sender = InMemoryWebhookSender::new(); |
| 1221 | f.deliver( |
| 1222 | &[ |
| 1223 | f.event("refs/heads/main", oid("a"), oid("b")), |
| 1224 | f.event("refs/tags/v1", PushEvent::zero(), oid("c")), |
| 1225 | ], |
| 1226 | &sender, |
| 1227 | ) |
| 1228 | .await; |
| 1229 | |
| 1230 | let sent = sender.sent(); |
| 1231 | assert_eq!(sent.len(), 4, "two events times two hooks"); |
| 1232 | assert_eq!(sent.iter().filter(|r| r.url.ends_with("/one")).count(), 2); |
| 1233 | } |
| 1234 | |
| 1235 | #[tokio::test] |
| 1236 | async fn a_push_with_no_hooks_costs_nothing() { |
| 1237 | let f = fixture().await; |
| 1238 | let sender = InMemoryWebhookSender::new(); |
| 1239 | |
| 1240 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 1241 | .await; |
| 1242 | |
| 1243 | assert!(sender.sent().is_empty()); |
| 1244 | } |
| 1245 | |
| 1246 | #[tokio::test] |
| 1247 | async fn a_deletion_carries_no_commits() { |
| 1248 | let f = fixture().await; |
| 1249 | f.create(&f.owner, "https://example.com/hook") |
| 1250 | .await |
| 1251 | .expect("should create"); |
| 1252 | |
| 1253 | let sender = InMemoryWebhookSender::new(); |
| 1254 | f.deliver( |
| 1255 | &[f.event("refs/heads/gone", oid("a"), PushEvent::zero())], |
| 1256 | &sender, |
| 1257 | ) |
| 1258 | .await; |
| 1259 | |
| 1260 | let parsed: serde_json::Value = |
| 1261 | serde_json::from_slice(&sender.sent()[0].body).expect("valid json"); |
| 1262 | |
| 1263 | assert_eq!(parsed["after"], PushEvent::zero().as_str()); |
| 1264 | assert_eq!(parsed["commits"].as_array().map(Vec::len), Some(0)); |
| 1265 | } |
| 1266 | |
| 1267 | |
| 1268 | |
| 1269 | #[tokio::test] |
| 1270 | async fn a_hook_that_is_off_is_skipped_but_keeps_its_history() { |
| 1271 | let f = fixture().await; |
| 1272 | let created = f |
| 1273 | .create(&f.owner, "https://example.com/hook") |
| 1274 | .await |
| 1275 | .expect("should create"); |
| 1276 | |
| 1277 | let sender = InMemoryWebhookSender::new(); |
| 1278 | f.deliver(&[f.event("refs/heads/main", oid("a"), oid("b"))], &sender) |
| 1279 | .await; |
| 1280 | |
| 1281 | f.set_active(&f.owner, &created.webhook.id, false) |
| 1282 | .await |
| 1283 | .expect("should turn off"); |
| 1284 | |
| 1285 | f.deliver(&[f.event("refs/heads/main", oid("b"), oid("c"))], &sender) |
| 1286 | .await; |
| 1287 | |
| 1288 | assert_eq!(sender.sent().len(), 1, "the second push is not delivered"); |
| 1289 | |
| 1290 | |
| 1291 | let detail = f.view(&f.owner, &created.webhook.id).await.expect("view"); |
| 1292 | assert!(!detail.active); |
| 1293 | assert_eq!(detail.deliveries.items.len(), 1); |
| 1294 | } |
| 1295 | |
| 1296 | #[tokio::test] |
| 1297 | async fn setting_the_state_it_already_has_changes_nothing() { |
| 1298 | |
| 1299 | |
| 1300 | let f = fixture().await; |
| 1301 | let created = f |
| 1302 | .create(&f.owner, "https://example.com/hook") |
| 1303 | .await |
| 1304 | .expect("should create"); |
| 1305 | |
| 1306 | for _ in 0..2 { |
| 1307 | assert!( |
| 1308 | !f.set_active(&f.owner, &created.webhook.id, false) |
| 1309 | .await |
| 1310 | .expect("should turn off") |
| 1311 | .active |
| 1312 | ); |
| 1313 | } |
| 1314 | |
| 1315 | assert!( |
| 1316 | f.set_active(&f.owner, &created.webhook.id, true) |
| 1317 | .await |
| 1318 | .expect("should turn on") |
| 1319 | .active |
| 1320 | ); |
| 1321 | } |
| 1322 | |
| 1323 | #[tokio::test] |
| 1324 | async fn only_an_owner_can_turn_a_hook_off() { |
| 1325 | let f = fixture().await; |
| 1326 | let created = f |
| 1327 | .create(&f.owner, "https://example.com/hook") |
| 1328 | .await |
| 1329 | .expect("should create"); |
| 1330 | |
| 1331 | for actor in [&f.member, &Actor::Anonymous] { |
| 1332 | assert!( |
| 1333 | f.set_active(actor, &created.webhook.id, false) |
| 1334 | .await |
| 1335 | .is_err() |
| 1336 | ); |
| 1337 | } |
| 1338 | |
| 1339 | assert!(f.list(&f.owner).await.expect("list")[0].active); |
| 1340 | } |
| 1341 | |
| 1342 | |
| 1343 | |
| 1344 | #[tokio::test] |
| 1345 | async fn a_redelivery_repeats_the_body_and_continues_the_attempt_count() { |
| 1346 | let f = fixture().await; |
| 1347 | let created = f |
| 1348 | .create(&f.owner, "https://example.com/hook") |
| 1349 | .await |
| 1350 | .expect("should create"); |
| 1351 | |
| 1352 | let event = f.event("refs/heads/main", oid("a"), oid("b")); |
| 1353 | f.record(&event).await; |
| 1354 | |
| 1355 | let sender = InMemoryWebhookSender::new(); |
| 1356 | f.deliver(std::slice::from_ref(&event), &sender).await; |
| 1357 | |
| 1358 | let first = f |
| 1359 | .view(&f.owner, &created.webhook.id) |
| 1360 | .await |
| 1361 | .expect("view") |
| 1362 | .deliveries |
| 1363 | .items[0] |
| 1364 | .id |
| 1365 | .clone(); |
| 1366 | |
| 1367 | let repeated = f |
| 1368 | .again(&f.owner, &created.webhook.id, &first, &sender) |
| 1369 | .await |
| 1370 | .expect("should redeliver"); |
| 1371 | |
| 1372 | let sent = sender.sent(); |
| 1373 | assert_eq!(sent.len(), 2); |
| 1374 | assert_eq!(sent[0].body, sent[1].body, "the same payload, resigned"); |
| 1375 | assert_eq!(sent[0].headers, sent[1].headers); |
| 1376 | |
| 1377 | |
| 1378 | assert_eq!(repeated.attempt, 2); |
| 1379 | assert_eq!( |
| 1380 | f.view(&f.owner, &created.webhook.id) |
| 1381 | .await |
| 1382 | .expect("view") |
| 1383 | .deliveries |
| 1384 | .items |
| 1385 | .len(), |
| 1386 | 2 |
| 1387 | ); |
| 1388 | } |
| 1389 | |
| 1390 | #[tokio::test] |
| 1391 | async fn a_redelivery_makes_one_attempt_and_does_not_retry() { |
| 1392 | |
| 1393 | |
| 1394 | let f = fixture().await; |
| 1395 | let created = f |
| 1396 | .create(&f.owner, "https://example.com/hook") |
| 1397 | .await |
| 1398 | .expect("should create"); |
| 1399 | |
| 1400 | let event = f.event("refs/heads/main", oid("a"), oid("b")); |
| 1401 | f.record(&event).await; |
| 1402 | |
| 1403 | let sender = InMemoryWebhookSender::scripted(vec![outcome(Some(200), "")]); |
| 1404 | f.deliver(std::slice::from_ref(&event), &sender).await; |
| 1405 | |
| 1406 | let first = f |
| 1407 | .view(&f.owner, &created.webhook.id) |
| 1408 | .await |
| 1409 | .expect("view") |
| 1410 | .deliveries |
| 1411 | .items[0] |
| 1412 | .id |
| 1413 | .clone(); |
| 1414 | |
| 1415 | let failing = InMemoryWebhookSender::scripted(vec![outcome(Some(502), "bad gateway")]); |
| 1416 | let repeated = f |
| 1417 | .again(&f.owner, &created.webhook.id, &first, &failing) |
| 1418 | .await |
| 1419 | .expect("should redeliver"); |
| 1420 | |
| 1421 | assert_eq!(failing.sent().len(), 1); |
| 1422 | assert!(!repeated.ok); |
| 1423 | assert_eq!(repeated.response, "bad gateway"); |
| 1424 | } |
| 1425 | |
| 1426 | #[tokio::test] |
| 1427 | async fn a_hook_that_is_off_can_still_be_redelivered_to_by_hand() { |
| 1428 | let f = fixture().await; |
| 1429 | let created = f |
| 1430 | .create(&f.owner, "https://example.com/hook") |
| 1431 | .await |
| 1432 | .expect("should create"); |
| 1433 | |
| 1434 | let event = f.event("refs/heads/main", oid("a"), oid("b")); |
| 1435 | f.record(&event).await; |
| 1436 | |
| 1437 | let sender = InMemoryWebhookSender::new(); |
| 1438 | f.deliver(std::slice::from_ref(&event), &sender).await; |
| 1439 | |
| 1440 | let first = f |
| 1441 | .view(&f.owner, &created.webhook.id) |
| 1442 | .await |
| 1443 | .expect("view") |
| 1444 | .deliveries |
| 1445 | .items[0] |
| 1446 | .id |
| 1447 | .clone(); |
| 1448 | |
| 1449 | f.set_active(&f.owner, &created.webhook.id, false) |
| 1450 | .await |
| 1451 | .expect("should turn off"); |
| 1452 | |
| 1453 | assert!( |
| 1454 | f.again(&f.owner, &created.webhook.id, &first, &sender) |
| 1455 | .await |
| 1456 | .is_ok() |
| 1457 | ); |
| 1458 | assert_eq!(sender.sent().len(), 2); |
| 1459 | } |
| 1460 | |
| 1461 | #[tokio::test] |
| 1462 | async fn an_attempt_nobody_recorded_is_not_found_and_nobody_else_may_ask() { |
| 1463 | let f = fixture().await; |
| 1464 | let created = f |
| 1465 | .create(&f.owner, "https://example.com/hook") |
| 1466 | .await |
| 1467 | .expect("should create"); |
| 1468 | |
| 1469 | let event = f.event("refs/heads/main", oid("a"), oid("b")); |
| 1470 | f.record(&event).await; |
| 1471 | |
| 1472 | let sender = InMemoryWebhookSender::new(); |
| 1473 | f.deliver(std::slice::from_ref(&event), &sender).await; |
| 1474 | |
| 1475 | let first = f |
| 1476 | .view(&f.owner, &created.webhook.id) |
| 1477 | .await |
| 1478 | .expect("view") |
| 1479 | .deliveries |
| 1480 | .items[0] |
| 1481 | .id |
| 1482 | .clone(); |
| 1483 | |
| 1484 | assert!( |
| 1485 | f.again( |
| 1486 | &f.owner, |
| 1487 | &created.webhook.id, |
| 1488 | &WebhookDeliveryId::generate(), |
| 1489 | &sender |
| 1490 | ) |
| 1491 | .await |
| 1492 | .is_err() |
| 1493 | ); |
| 1494 | |
| 1495 | for actor in [&f.member, &Actor::Anonymous] { |
| 1496 | assert!( |
| 1497 | f.again(actor, &created.webhook.id, &first, &sender) |
| 1498 | .await |
| 1499 | .is_err() |
| 1500 | ); |
| 1501 | } |
| 1502 | |
| 1503 | assert_eq!(sender.sent().len(), 1, "nothing left this machine"); |
| 1504 | } |
| 1505 | } |