steid

@jamesgill /

Rust17.6 KBCode·Blame·History·Raw
1//! Webhooks — `/{handle}/repos/{name}/settings/hooks`.
2//!
3//! Owner-only, and 404 for anyone else, exactly as
4//! [`repo_settings`](super::repo_settings) is: a 403 would confirm that a private
5//! repository by that name exists.
6//!
7//! Two pages. The list is where a hook is added and removed, and where its most recent
8//! delivery is visible as a dot. The detail page is the delivery log — the thing anybody
9//! actually opens, because they are here to find out why their endpoint is not being
10//! called.
11
12use std::time::SystemTime;
13
14use serde::Deserialize;
15use topcoat::{
16 Result,
17 context::Cx,
18 icon::{icon, iconify::iconify_icon},
19 router::{StatusCode, content::Form, error::not_found, page, path_param, query_params},
20 view::{attributes, component, view},
21};
22
23use crate::{
24 application::{
25 DELIVERY_LIMIT, Error, RepoView, WebhookDetail, WebhookSummary, create_webhook,
26 delete_webhook, list_webhooks, view_webhook,
27 },
28 components::{
29 badge::{BadgeVariant, badge},
30 button::{ButtonSize, ButtonVariant, button},
31 flash::{FlashKind, flash},
32 input::input,
33 label::label,
34 },
35 domain::{DomainError, WebhookDelivery, WebhookId, WebhookUrl},
36};
37
38use super::{
39 browse::timestamp,
40 context::{
41 current_actor, deliveries, location, memberships, orgs, private_targets, repos,
42 server_error, webhooks,
43 },
44 layout::narrow,
45 repo::repo_for,
46};
47
48/// `{hook}` from the path — a webhook's id.
49#[path_param]
50struct Hook(str);
51
52#[derive(Debug, Deserialize)]
53struct AddForm {
54 url: String,
55}
56
57/// Set after a delete so the confirmation survives the redirect.
58#[query_params(error = bad_request)]
59struct Removed {
60 removed: Option<String>,
61}
62
63/// The repository in the path, or 404 for anyone who does not own it.
64///
65/// The use cases decide this too; the guard here only keeps a page from rendering for
66/// someone whose submission would be refused anyway.
67async fn owned(cx: &Cx) -> Result<RepoView> {
68 let repo = repo_for(cx).await?;
69
70 if !repo.viewer_is_owner {
71 return Err(not_found().into());
72 }
73
74 Ok(repo)
75}
76
77/// Collapses a use case failure into what a page can do about it.
78///
79/// Validation is the visitor's to fix and is shown; everything else about ownership is
80/// the same 404 the guard above gives.
81fn explain(error: Error) -> Result<String> {
82 match error {
83 Error::Domain(DomainError::Validation { field, reason }) => {
84 Ok(format!("That {field} is no good: {reason}."))
85 }
86 Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. }) => {
87 Err(not_found().into())
88 }
89 other => Err(server_error(std::io::Error::other(other.to_string()))),
90 }
91}
92
93async fn listing(cx: &Cx, repo: &RepoView) -> Result<Vec<WebhookSummary>> {
94 list_webhooks(
95 &current_actor(cx).await?,
96 &repo.handle,
97 &repo.name,
98 &orgs(cx),
99 &memberships(cx),
100 &repos(cx),
101 &webhooks(cx),
102 &deliveries(cx),
103 )
104 .await
105 .map_err(|error| match error {
106 // The guard above already answered this for the page; reaching it here means the
107 // repository went away between the two reads.
108 Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. }) => not_found().into(),
109 other => server_error(std::io::Error::other(other.to_string())),
110 })
111}
112
113#[page("/{handle}/repos/{name}/settings/hooks")]
114async fn hooks_page(cx: &Cx) -> Result {
115 let repo = owned(cx).await?;
116 let listed = listing(cx, &repo).await?;
117 let removed = query_params::<Removed>(cx)?.removed.is_some();
118
119 view! {
120 hooks_view(
121 handle: repo.handle.as_str(),
122 name: repo.name.as_str(),
123 hooks: &listed,
124 notice: Notice { removed, ..Notice::default() },
125 )
126 }
127}
128
129/// Adds a hook and shows its secret, once.
130///
131/// **This deliberately does not redirect**, for the same reason issuing a token does not
132/// — see [`token::issue`](super::token). The secret exists only in this response, and
133/// surviving a redirect would mean putting it in a URL.
134#[page(POST "/{handle}/repos/{name}/settings/hooks")]
135async fn add(cx: &Cx, Form(submitted): Form<AddForm>) -> Result {
136 let repo = owned(cx).await?;
137
138 let outcome = create_webhook(
139 &current_actor(cx).await?,
140 &repo.handle,
141 &repo.name,
142 submitted.url.trim(),
143 SystemTime::now(),
144 private_targets(cx),
145 &orgs(cx),
146 &memberships(cx),
147 &repos(cx),
148 &webhooks(cx),
149 )
150 .await;
151
152 let (created, error) = match outcome {
153 Ok(created) => (created.secret.reveal().to_owned(), String::new()),
154 Err(error) => (String::new(), explain(error)?),
155 };
156
157 let listed = listing(cx, &repo).await?;
158
159 view! {
160 hooks_view(
161 handle: repo.handle.as_str(),
162 name: repo.name.as_str(),
163 hooks: &listed,
164 notice: Notice {
165 created: created.as_str(),
166 removed: false,
167 error: error.as_str(),
168 // Cleared on success so the field is ready for the next one, kept on
169 // failure so a rejected URL is not silently thrown away.
170 url: if created.is_empty() { submitted.url.as_str() } else { "" },
171 },
172 )
173 }
174}
175
176/// Removes a hook, then redirects so a reload cannot repeat it.
177#[page(POST "/{handle}/repos/{name}/settings/hooks/{hook}/delete")]
178async fn remove(cx: &Cx) -> Result {
179 let repo = owned(cx).await?;
180 let id = WebhookId::from_trusted(path_param::<Hook>(cx));
181
182 match delete_webhook(
183 &current_actor(cx).await?,
184 &repo.handle,
185 &repo.name,
186 &id,
187 &orgs(cx),
188 &memberships(cx),
189 &repos(cx),
190 &webhooks(cx),
191 )
192 .await
193 {
194 Ok(()) => {}
195 // Already gone, or never this repository's. Both are "no such hook of yours",
196 // and both leave the list looking the way the visitor wanted it.
197 Err(Error::Domain(DomainError::NotFound { .. })) => {}
198 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
199 }
200
201 view! {
202 (StatusCode::SEE_OTHER)
203 (location(&format!(
204 "/{}/repos/{}/settings/hooks?removed",
205 repo.handle, repo.name
206 ))?)
207 }
208}
209
210#[page("/{handle}/repos/{name}/settings/hooks/{hook}")]
211async fn hook_page(cx: &Cx) -> Result {
212 let repo = owned(cx).await?;
213 let id = WebhookId::from_trusted(path_param::<Hook>(cx));
214
215 let detail = view_webhook(
216 &current_actor(cx).await?,
217 &repo.handle,
218 &repo.name,
219 &id,
220 &orgs(cx),
221 &memberships(cx),
222 &repos(cx),
223 &webhooks(cx),
224 &deliveries(cx),
225 )
226 .await;
227
228 let detail = match detail {
229 Ok(detail) => detail,
230 // A hook id that is not this repository's is not a page.
231 Err(_) => return Err(not_found().into()),
232 };
233
234 view! {
235 hook_view(
236 handle: repo.handle.as_str(),
237 name: repo.name.as_str(),
238 hook: &detail,
239 )
240 }
241}
242
243/// The dot beside a hook, and its label.
244///
245/// Three states, because "never delivered" is not "failing": a hook added a minute ago
246/// has nothing wrong with it. Colour is the only place on these pages it carries
247/// meaning, so the dot is the one coloured thing in a row.
248fn status_of(last: Option<&WebhookDelivery>) -> (&'static str, String) {
249 match last {
250 Some(delivery) if delivery.ok => {
251 ("bg-success", format!("{} · ok", delivery.status_label()))
252 }
253 Some(delivery) => ("bg-destructive", delivery.status_label()),
254 None => ("bg-muted-foreground/40", "no deliveries yet".to_owned()),
255 }
256}
257
258/// What the page has to say about the last thing that happened, grouped so the view
259/// takes one argument for it rather than four that must stay in the same order at three
260/// call sites — the shape `repo_settings`'s `Fields` already uses.
261#[derive(Debug, Clone, Copy, Default)]
262struct Notice<'a> {
263 /// A secret to show exactly once. Empty otherwise.
264 created: &'a str,
265 removed: bool,
266 error: &'a str,
267 /// What was typed, kept on a rejected submission.
268 url: &'a str,
269}
270
271/// The list of hooks, the add form, and the secret when one has just been made.
272#[component]
273async fn hooks_view(
274 handle: &str,
275 name: &str,
276 hooks: &[WebhookSummary],
277 notice: Notice<'_>,
278) -> Result {
279 let Notice {
280 created,
281 removed,
282 error,
283 url,
284 } = notice;
285
286 view! {
287 narrow(
288 <h1 class="text-xl font-semibold tracking-tight">"Webhooks"</h1>
289 <p class="mt-1 font-mono text-sm text-muted-foreground">
290 "@" (handle) " / " (name)
291 </p>
292 <p class="mt-2 text-sm text-muted-foreground">
293 "Every push to this repository is POSTed to each hook as signed JSON, "
294 "once per ref that moved."
295 </p>
296
297 if !created.is_empty() {
298 <div class="mt-6 space-y-2">
299 flash(
300 kind: FlashKind::Success,
301 "Copy this secret now — it is not shown again."
302 )
303 <pre class="overflow-x-auto rounded-lg border border-border bg-surface px-4 py-3 font-mono text-sm">(created)</pre>
304 <p class="text-xs text-muted-foreground">
305 "Sent as "
306 <code class="font-mono">"X-Steid-Signature-256: sha256=<hex>"</code>
307 " — the HMAC-SHA-256 of the exact body, keyed with this."
308 </p>
309 </div>
310 }
311
312 if removed {
313 <div class="mt-6">
314 flash(kind: FlashKind::Success, "Webhook removed.")
315 </div>
316 }
317
318 if !error.is_empty() {
319 <div class="mt-6">
320 flash(kind: FlashKind::Error, (error))
321 </div>
322 }
323
324 <form
325 method="post"
326 action=(format!("/{handle}/repos/{name}/settings/hooks"))
327 class="mt-6 space-y-5"
328 >
329 <div class="space-y-2">
330 label(attrs: attributes! { for="url" }, "Payload URL")
331 input(attrs: attributes! {
332 id="url"
333 name="url"
334 type="text"
335 value=(url)
336 placeholder="https://example.com/steid-hook"
337 required=(true)
338 autocomplete="off"
339 maxlength=(WebhookUrl::MAX_LEN.to_string())
340 })
341 <p class="text-xs text-muted-foreground">
342 "Must be reachable from the internet. An address on this machine "
343 "or its private network is refused."
344 </p>
345 </div>
346
347 button(attrs: attributes! { type="submit" }, "Add webhook")
348 </form>
349
350 <section class="mt-10">
351 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
352 "Hooks"
353 </h2>
354
355 if hooks.is_empty() {
356 <p class="mt-2 rounded-lg border border-border px-4 py-6 text-center text-sm text-muted-foreground">
357 "No webhooks yet."
358 </p>
359 } else {
360 <ul class="mt-2 divide-y divide-border rounded-lg border border-border">
361 for hook in hooks {
362 <li class="flex items-center gap-3 px-4 py-3">
363 <span
364 class=(format!("size-2 shrink-0 rounded-full {}", status_of(hook.last.as_ref()).0))
365 title=(status_of(hook.last.as_ref()).1)
366 ></span>
367 <a
368 href=(format!("/{handle}/repos/{name}/settings/hooks/{}", hook.id))
369 class="min-w-0 flex-1 truncate font-mono text-sm hover:underline"
370 >(hook.url.as_str())</a>
371 if !hook.active {
372 badge(variant: BadgeVariant::Outline, "Off")
373 }
374 <span class="hidden shrink-0 font-mono text-xs text-muted-foreground sm:inline">
375 (status_of(hook.last.as_ref()).1)
376 </span>
377 <form
378 method="post"
379 action=(format!(
380 "/{handle}/repos/{name}/settings/hooks/{}/delete",
381 hook.id
382 ))
383 class="shrink-0"
384 >
385 // Ghost and small: the dot is the only coloured
386 // thing in a row, and a filled destructive button
387 // per hook would make the list read as a warning.
388 button(
389 attrs: attributes! { type="submit" },
390 variant: ButtonVariant::Ghost,
391 size: ButtonSize::Sm,
392 "Delete"
393 )
394 </form>
395 </li>
396 }
397 </ul>
398 }
399 </section>
400
401 <p class="mt-8">
402 <a
403 href=(format!("/{handle}/repos/{name}/settings"))
404 class="text-sm text-muted-foreground hover:text-foreground"
405 >"Back to repository settings"</a>
406 </p>
407 )
408 }
409}
410
411/// One hook and its recent attempts.
412#[component]
413async fn hook_view(handle: &str, name: &str, hook: &WebhookDetail) -> Result {
414 view! {
415 narrow(
416 <h1 class="text-xl font-semibold tracking-tight">"Webhook"</h1>
417 <p class="mt-1 break-all font-mono text-sm text-muted-foreground">
418 (hook.url.as_str())
419 </p>
420 <p class="mt-1 text-xs text-muted-foreground">
421 "Added " (timestamp(hook.created_at))
422 if !hook.active { " · not active" }
423 </p>
424
425 <section class="mt-6">
426 <div class="flex items-baseline justify-between gap-4">
427 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
428 "Deliveries"
429 </h2>
430 if hook.deliveries.len() >= DELIVERY_LIMIT {
431 <span class="text-xs text-muted-foreground">
432 "Showing the most recent " (DELIVERY_LIMIT.to_string())
433 </span>
434 }
435 </div>
436
437 if hook.deliveries.is_empty() {
438 <p class="mt-2 rounded-lg border border-border px-4 py-6 text-center text-sm text-muted-foreground">
439 "Nothing has been delivered yet. Push to this repository to try it."
440 </p>
441 } else {
442 <ul class="mt-2 divide-y divide-border rounded-lg border border-border">
443 for delivery in &hook.deliveries {
444 delivery_row(delivery: delivery)
445 }
446 </ul>
447 }
448 </section>
449
450 <p class="mt-8">
451 <a
452 href=(format!("/{handle}/repos/{name}/settings/hooks"))
453 class="text-sm text-muted-foreground hover:text-foreground"
454 >"Back to webhooks"</a>
455 </p>
456 )
457 }
458}
459
460/// One attempt: when, which try, what came back, and how long it took.
461///
462/// The response is a `<details>` rather than a column — most of them are empty, and the
463/// one that is not is the whole reason somebody opened this page.
464#[component]
465async fn delivery_row(delivery: &WebhookDelivery) -> Result {
466 let (dot, _) = status_of(Some(delivery));
467
468 view! {
469 <li class="px-4 py-2.5">
470 <div class="flex items-center gap-3 text-xs">
471 <span class=(format!("size-2 shrink-0 rounded-full {dot}"))></span>
472 <span class="font-mono text-muted-foreground">
473 (timestamp(delivery.delivered_at))
474 </span>
475 <span class="font-mono">(delivery.status_label())</span>
476 <span class="ml-auto shrink-0 font-mono text-muted-foreground">
477 "try " (delivery.attempt.to_string())
478 " · " (delivery.duration_ms.to_string()) "ms"
479 </span>
480 </div>
481
482 if !delivery.response.is_empty() {
483 <details class="mt-1.5">
484 <summary class="inline-flex cursor-pointer items-center gap-1 text-xs text-muted-foreground hover:text-foreground">
485 icon(data: iconify_icon!("feather:chevron-right"), attrs: attributes! {
486 class="size-3.5"
487 })
488 "Response"
489 </summary>
490 <pre class="mt-1.5 max-h-48 overflow-auto rounded-md border border-border bg-surface px-3 py-2 font-mono text-xs whitespace-pre-wrap">(delivery.response.as_str())</pre>
491 </details>
492 }
493 </li>
494 }
495}