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