steid

@jamesgill /

steid/src/application/webhook.rs
Rust49.4 KBCode·Blame·History·Raw
1//! Registering webhooks, and delivering a push to them.
2//!
3//! A webhook is the one place Steid makes an outbound connection to an address a person
4//! typed. Everything defensive about that lives either in
5//! [`WebhookUrl`](crate::domain::WebhookUrl) — which refuses the address at the moment
6//! it is saved, when there is somebody to tell — or in the sending adapter, which
7//! re-checks what the name resolved to.
8//!
9//! **Nothing here survives a restart.** Retries live in the task that started them, so a
10//! process that stops between attempts loses the remaining ones; the delivery rows
11//! written so far stay, so what happened is still readable. A durable queue is the
12//! answer when deliveries have to be reliable, and it is a different feature.
13
14use std::time::{Duration, SystemTime};
15
16use futures_util::future::join_all;
17
18use 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
27use 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/// The payload's own version, carried in every body.
36///
37/// Steid's shape rather than an imitation of GitHub's: a receiver that thinks it is
38/// talking to GitHub and finds three quarters of the fields missing is worse served
39/// than one told plainly what this is. The number is what lets the shape change later
40/// without every receiver having to guess.
41pub const PAYLOAD_VERSION: u32 = 1;
42
43/// How many commits a payload carries.
44///
45/// A body is a thing a receiver parses in a request handler, and a push of ten thousand
46/// commits must not become a ten-megabyte POST. The `before`/`after` pair is in the
47/// payload precisely so a receiver that wants the rest can ask git for it.
48pub const MAX_PAYLOAD_COMMITS: usize = 20;
49
50/// How long to wait before each retry.
51///
52/// One initial attempt plus these, so four sends at most and a delivery row for each.
53/// The spread is deliberate: 5 seconds catches a receiver that was restarting, 30 a
54/// deploy, and 2 minutes an outage short enough to be worth waiting out. Anything longer
55/// belongs to a durable queue rather than to a task holding a `Vec` in memory.
56pub const RETRY_BACKOFF: [Duration; 3] = [
57 Duration::from_secs(5),
58 Duration::from_secs(30),
59 Duration::from_secs(120),
60];
61
62/// How many attempts one page of the deliveries list shows.
63pub const DELIVERY_LIMIT: usize = 50;
64
65/// A hook as it appears in a listing.
66///
67/// Carries no secret. The secret is shown once, at creation, and a list has nothing to
68/// do with it.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct WebhookSummary {
71 pub id: WebhookId,
72 pub url: WebhookUrl,
73 pub active: bool,
74 pub created_at: SystemTime,
75 /// The most recent attempt, which is what the status dot reads. `None` for a hook
76 /// nothing has been pushed to yet — a real state, and a different one from failing.
77 pub last: Option<WebhookDelivery>,
78}
79
80/// A hook and its recent attempts.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct WebhookDetail {
83 pub id: WebhookId,
84 pub url: WebhookUrl,
85 pub active: bool,
86 pub created_at: SystemTime,
87 /// One page of the hook's attempts, newest first.
88 pub deliveries: Paged<WebhookDelivery>,
89}
90
91/// A hook and the one and only chance to read its secret.
92#[derive(Debug)]
93pub struct CreatedWebhook {
94 pub webhook: Webhook,
95 pub secret: WebhookSecret,
96}
97
98/// Registers a hook on a repository.
99///
100/// Owner only, through the same predicate the settings page uses — a member's read
101/// access is not permission to point someone's pushes at a server they chose.
102///
103/// The secret is minted here rather than accepted from the form. A person choosing it
104/// would choose a weak one, and the value has no purpose outside signing.
105///
106/// `targets` is [`PrivateTargets::Refused`] on any instance that has not deliberately
107/// opted out — the caller reads it from configuration rather than this deciding, because
108/// the domain must not know that an environment variable exists.
109#[allow(clippy::too_many_arguments)]
110pub 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/// Every hook on a repository, with the outcome of its most recent attempt.
140///
141/// One extra query per hook. A repository has a handful of hooks, and the alternative —
142/// a join expressed in both repository implementations — buys nothing at that size.
143#[allow(clippy::too_many_arguments)]
144pub 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/// One hook and its recent attempts.
174///
175/// A hook belonging to a *different* repository answers `NotFound`, for the reason a
176/// token belonging to someone else does: that an id exists elsewhere is not a fact this
177/// caller should be able to learn by trying ids.
178#[allow(clippy::too_many_arguments)]
179pub 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/// Removes a hook, and its delivery history with it.
215#[allow(clippy::too_many_arguments)]
216pub 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/// Turns a hook on or off, and answers with the hook as it now stands.
240///
241/// Idempotent: the caller passes the state it wants rather than "the other one", so a
242/// double submit — a reload, a second click — lands on the same answer instead of
243/// flipping back. The page reads the current state when it renders the button, which is
244/// what makes that the natural shape here.
245///
246/// A hook that is off keeps its deliveries and its secret. That is the whole reason for
247/// having an off switch rather than only a delete: the delivery log is usually the
248/// evidence of *why* it was turned off.
249#[allow(clippy::too_many_arguments)]
250pub 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/// Sends one recorded event to one hook again, as a fresh attempt.
276///
277/// **The payload is rebuilt, not replayed from a column.** A delivery row keeps what
278/// came back, not what went out — storing every body would put a copy of the repository's
279/// commit list in the database once per attempt — so the body is assembled from the same
280/// [`PushEvent`] by the same [`push_payload`] the original used. In practice that is the
281/// same bytes; where it can differ is the commit list, which is read from git now and
282/// would notice history having been rewritten under it. That is the honest answer for a
283/// redelivery: it says what the repository holds today.
284///
285/// One attempt and no retry schedule. A retry is what happens to a delivery nobody asked
286/// about; this one has somebody watching the page, and they can press the button again.
287///
288/// The attempt number continues the event's own sequence rather than restarting at 1, so
289/// the log reads as "the fifth time we tried this push" rather than as a second first
290/// try. It is taken from the attempts already recorded against this hook — the same page
291/// of them the deliveries page shows, which is also where the button was pressed.
292///
293/// **An inactive hook can still be redelivered to.** Turning a hook off stops Steid
294/// calling it on its own; a person pressing Redeliver is asking for exactly this one
295/// call, which is usually how you check whether the endpoint is fixed before turning it
296/// back on.
297#[allow(clippy::too_many_arguments)]
298pub async fn redeliver(
299 actor: &Actor,
300 handle: &OrgName,
301 name: &RepoName,
302 hook_id: &WebhookId,
303 delivery_id: &WebhookDeliveryId,
304 // The origin this instance is reached on, e.g. `https://steid.example` — the same
305 // value a push derives its payload's repository URL from.
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 // One read serves three purposes: finding the attempt the button names, learning
327 // which event it belongs to, and counting how many attempts that event has had. The
328 // button only ever appears on a row this page rendered, so the row being outside the
329 // window is the same "no such attempt" as it never having existed.
330 // The whole history, not a page of it: the button is on a row the reader is looking
331 // at, which may be on any page, and the attempt number below counts every attempt
332 // the *event* has had — a number the old 50-row window got wrong as soon as an event
333 // fell out of it. See `plans/current.md` for what this costs a long-lived hook.
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/// What a payload needs to know about the world outside the event.
391#[derive(Debug, Clone)]
392pub struct DeliveryContext {
393 pub handle: OrgName,
394 pub name: RepoName,
395 /// The repository's own page, absolute — a receiver has no way to build one.
396 /// Derived from the request the push arrived on, so an instance never has to be
397 /// told its own address.
398 pub repo_url: String,
399 /// The handle of whoever pushed. `None` only if their user record has gone between
400 /// the push and the delivery.
401 pub pusher: Option<String>,
402}
403
404/// Builds the JSON body for one event.
405///
406/// Steid's own shape, versioned — see [`PAYLOAD_VERSION`]. Timestamps are Unix seconds
407/// rather than a formatted date: Steid has no date formatter, and a receiver parsing an
408/// integer cannot be caught out by a timezone.
409pub 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 // `to_vec`, not `to_string`: the signature is over the bytes actually sent, and
440 // re-encoding a string to sign it is how the two drift apart.
441 serde_json::to_vec(&body).unwrap_or_else(|_| b"{}".to_vec())
442}
443
444/// The headers every delivery carries.
445///
446/// `X-Steid-Delivery` is the **push event's** id, not the attempt's, so all four
447/// attempts at one event carry the same value — deduplicating on it is the whole reason
448/// a receiver would read it, and an id that changed per retry could not be used for
449/// that.
450fn 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/// Delivers every event of one push to every active hook on the repository.
464///
465/// Takes no `Actor`: its only input is a list of [`PushEvent`]s, which nothing but
466/// [`record_push`](super::push::record_push) produces and which that function will not
467/// produce for anyone but an owner. Authorization is settled upstream, once.
468///
469/// **Hooks run concurrently, events run in order.** A dead endpoint holds its own task
470/// for two and a half minutes of backoff, and must not hold anybody else's; but two
471/// pushes to one hook arriving out of order would be a receiver's bug to work around
472/// forever.
473///
474/// `backoff` is a parameter rather than a constant so the tests do not sleep. Production
475/// passes [`RETRY_BACKOFF`].
476#[allow(clippy::too_many_arguments)]
477pub 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 // Built once for all hooks: the body is identical, and only the signature differs.
503 // Asking git for the same commits once per hook would multiply the forks by the
504 // number of endpoints somebody happened to register.
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/// The commits a payload lists, newest first.
523///
524/// A deletion has none. A creation is diffed against nothing, which is every commit the
525/// new ref reaches — capped like any other, because a first push of a large repository
526/// would otherwise put its whole history in a POST.
527///
528/// A read that fails costs the payload its commit list and nothing else: the ref, the
529/// two ids and the repository are the parts a receiver cannot reconstruct, and refusing
530/// to deliver at all because git was slow would be the wrong trade.
531async 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/// Sends one event to one hook, retrying on failure, recording every attempt.
565///
566/// Never returns an error. A delivery that could not be made is a row saying so, and a
567/// row that could not be written is a log line — neither is something the push that
568/// caused it should ever hear about. The last attempt is handed back for the one caller
569/// that has somebody waiting on the answer — [`redeliver`] — and ignored by the push
570/// path, which has nobody to tell.
571///
572/// `first` is the number the first attempt is recorded under. A push starts at 1; a
573/// redelivery continues the event's own sequence, so its row does not claim to be a
574/// first try.
575#[allow(clippy::too_many_arguments)]
576async 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 // Asked per attempt, not once for the delivery: attempts are minutes apart
610 // and a single timestamp would have the deliveries page claim four of them
611 // in one instant. This is the case the [`Clock`] port exists for.
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 // The loop body runs at least once — `0..=backoff.len()` is never empty — so there
629 // is always an attempt to report.
630 recorded.expect("a delivery always makes at least one attempt")
631}
632
633fn 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
639fn missing() -> Error {
640 DomainError::NotFound { entity: "webhook" }.into()
641}
642
643#[cfg(test)]
644mod 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 /// No waiting between retries. The schedule is production's business; what these
664 /// tests are about is how many attempts happen and what each records.
665 const INSTANT: [Duration; 3] = [Duration::ZERO, Duration::ZERO, Duration::ZERO];
666
667 /// The clock every test delivery is stamped by. Fixed, so a recorded time is
668 /// something a test can assert rather than something it has to allow for.
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 // A real user record for the owner, because a redelivery resolves the pusher of
714 // the *event* rather than being handed one — see [`redeliver`].
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 // The same person `context()` names, so a redelivery — which resolves the
854 // pusher from the event — rebuilds the identical payload.
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 /// Records an event the way a push would, so a redelivery has one to find.
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 // --- registering ---------------------------------------------------------------
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 // The SSRF rule, reached through the use case rather than only unit-tested on
948 // the value object: this is the path a form actually takes.
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 // Trying ids must not tell anyone which ones exist elsewhere.
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 // --- the payload ---------------------------------------------------------------
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 // --- delivering ----------------------------------------------------------------
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 // Stamped by the clock the caller handed in, not by one read inside — which is
1120 // the whole of what the `Clock` port buys here.
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 // --- on and off -----------------------------------------------------------------
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 // The point of off rather than delete: the evidence stays readable.
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 // A reload of the POST, or a second click: the caller says what it wants rather
1299 // than "the other one", so this cannot flip back.
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 // --- redelivering ----------------------------------------------------------------
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 // The event's own sequence continues rather than restarting.
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 // Somebody is watching the page. A schedule of retries is what happens to a
1393 // delivery nobody asked about.
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}