forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

mod.rs626 lines, 22.5 KiBHistoryRawDownload
1//! Web Push: a notification for the inbox also reaches the user's devices when no tab is open. A
2//! browser (or an installed app) subscribes through the service worker, the server keeps the
3//! subscription, and [`queue`] sends the message to every device of a user.
4//!
5//! Delivery never blocks the caller: [`queue`] spawns the work, which looks up the user's devices,
6//! encrypts the message per device (RFC 8291), signs the request with the instance's VAPID key
7//! (RFC 8292) and posts it to the push service. A device the service reports gone (404 or 410) is
8//! removed. Every change to a user's devices is announced on [`PushLive`], so an open settings page
9//! refreshes through its event stream.
10
11pub mod crypto;
12
13use std::sync::OnceLock;
14use std::time::Duration;
15
16use serde::Serialize;
17use tokio::sync::broadcast;
18
19use forge_core::store::web_push::PushSubscription;
20use forge_core::{Error, Result};
21
22use crate::i18n::{self, Lang, misc, push as text};
23use crate::state::AppState;
24use crate::webhooks::client::{WebhookPolicy, policy_client, validate_url};
25
26/// How long one push request may take before it counts as failed.
27const SEND_TIMEOUT: Duration = Duration::from_secs(15);
28/// Longest body text in a notification, in characters.
29const BODY_CHARS: usize = 140;
30
31/// Announces changes to a user's devices to the settings pages that show them. Only the event
32/// stream reads it; nothing here is stored, and a second server process would not see it.
33pub struct PushLive {
34 tx: broadcast::Sender<String>,
35}
36
37impl Default for PushLive {
38 fn default() -> Self {
39 Self {
40 tx: broadcast::channel(64).0,
41 }
42 }
43}
44
45impl PushLive {
46 /// Says that the devices of `user_id` changed. Nobody listening is fine.
47 pub fn publish(&self, user_id: &str) {
48 let _ = self.tx.send(user_id.to_owned());
49 }
50
51 /// A receiver for every change, from every user. A stream filters for its own user.
52 pub fn subscribe(&self) -> broadcast::Receiver<String> {
53 self.tx.subscribe()
54 }
55}
56
57/// What a notification says. Built per recipient, in the recipient's language.
58#[derive(Clone)]
59pub enum Alert {
60 /// Activity on an issue or pull request the user hears about.
61 Activity {
62 /// `owner/repo`.
63 repo: String,
64 number: i64,
65 title: String,
66 /// The verb of the activity (`misc::K::VerbOpened` and so on).
67 verb: misc::K,
68 actor: Option<String>,
69 /// The relative link the notification opens.
70 url: String,
71 /// The thread id. A newer notification for the same thread replaces the older one.
72 thread: String,
73 },
74 /// New security advisory alerts on a repo.
75 Advisories {
76 repo: String,
77 count: u64,
78 url: String,
79 },
80 /// A site admin alert.
81 Admin { subject: String, detail: String },
82 /// The test button.
83 Test,
84}
85
86/// The JSON the service worker reads. Small, and nothing in it is a secret.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
88pub struct Message {
89 pub title: String,
90 pub body: String,
91 /// A relative link on this origin.
92 pub url: String,
93 /// Notifications with the same tag replace each other on the device.
94 pub tag: String,
95}
96
97impl Alert {
98 /// The message for a recipient who reads `lang`.
99 pub fn message(&self, lang: Lang) -> Message {
100 match self {
101 Alert::Activity {
102 repo,
103 number,
104 title,
105 verb,
106 actor,
107 url,
108 thread,
109 } => {
110 let line = misc::activity_line(lang, *verb, actor.as_deref());
111 Message {
112 title: format!("{repo}#{number}"),
113 body: clip(&format!("{line}: {title}")),
114 url: safe_url(url),
115 tag: format!("thread-{thread}"),
116 }
117 }
118 Alert::Advisories { repo, count, url } => Message {
119 title: clip(repo),
120 body: text::advisory_alerts(lang, *count),
121 url: safe_url(url),
122 tag: format!("advisories-{repo}"),
123 },
124 Alert::Admin { subject, detail } => Message {
125 title: clip(subject),
126 body: clip(detail),
127 url: "/notifications".to_owned(),
128 tag: "admin-alert".to_owned(),
129 },
130 Alert::Test => Message {
131 title: text::t(lang, text::K::TestTitle).to_owned(),
132 body: text::t(lang, text::K::TestBody).to_owned(),
133 url: "/settings/notifications".to_owned(),
134 tag: "test".to_owned(),
135 },
136 }
137 }
138}
139
140/// Shortens text to the body limit, in characters, one line.
141fn clip(text: &str) -> String {
142 let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
143 if one_line.chars().count() <= BODY_CHARS {
144 return one_line;
145 }
146 let mut short: String = one_line.chars().take(BODY_CHARS - 3).collect();
147 short.push_str("...");
148 short
149}
150
151/// A relative link only. The service worker opens it on this origin, so anything that could leave
152/// the origin (a scheme, a protocol-relative `//host`) falls back to the notifications page.
153pub fn safe_url(url: &str) -> String {
154 if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') {
155 url.to_owned()
156 } else {
157 "/notifications".to_owned()
158 }
159}
160
161/// A short label for a device, from its User-Agent: "Chrome on Android", "Safari on iPhone".
162pub fn agent_label(user_agent: &str) -> String {
163 agent_label_in(Lang::En, user_agent)
164}
165
166/// [`agent_label`] in the viewer's language: "Chrome on Linux", "Linux üzerinde Chrome".
167pub fn agent_label_in(lang: Lang, user_agent: &str) -> String {
168 let os = if user_agent.contains("iPhone") {
169 "iPhone"
170 } else if user_agent.contains("iPad") {
171 "iPad"
172 } else if user_agent.contains("Android") {
173 "Android"
174 } else if user_agent.contains("Windows") {
175 "Windows"
176 } else if user_agent.contains("Macintosh") {
177 "Mac"
178 } else if user_agent.contains("CrOS") {
179 "ChromeOS"
180 } else if user_agent.contains("Linux") {
181 "Linux"
182 } else if lang == Lang::Tr {
183 "bilinmeyen sistem"
184 } else {
185 "Unknown system"
186 };
187 let browser = if user_agent.contains("Edg/") {
188 "Edge"
189 } else if user_agent.contains("OPR/") {
190 "Opera"
191 } else if user_agent.contains("Firefox/") {
192 "Firefox"
193 } else if user_agent.contains("Chrome/") || user_agent.contains("Chromium/") {
194 "Chrome"
195 } else if user_agent.contains("Safari/") {
196 "Safari"
197 } else if lang == Lang::Tr {
198 "Tarayıcı"
199 } else {
200 "Browser"
201 };
202 match lang {
203 Lang::Tr if os == "bilinmeyen sistem" => format!("{browser}, {os}"),
204 Lang::Tr => format!("{os} üzerinde {browser}"),
205 Lang::En => format!("{browser} on {os}"),
206 }
207}
208
209/// The HTTP client for push requests: the webhook outbound policy (no internal addresses, no
210/// redirects, no proxy). An endpoint is any URL a signed-in browser sent, so it gets the same
211/// treatment as a hook URL. Built once; the policy comes from the config, which does not change.
212fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> {
213 static CLIENT: OnceLock<Option<reqwest::Client>> = OnceLock::new();
214 CLIENT
215 .get_or_init(
216 || match policy_client(policy.clone(), SEND_TIMEOUT, "forge-web-push") {
217 Ok(client) => Some(client),
218 Err(e) => {
219 tracing::error!(error = %e, "web push: the client does not build");
220 None
221 }
222 },
223 )
224 .as_ref()
225}
226
227/// The instance's VAPID key pair. The private key is stored sealed with the instance key; the
228/// first call creates the pair.
229pub struct VapidKeys {
230 pub private: [u8; 32],
231 /// The public key, base64url. The browser subscribes with it.
232 pub public: String,
233}
234
235/// The VAPID keys of this instance, creating and storing them on first use.
236pub async fn vapid_keys(state: &AppState) -> Result<VapidKeys> {
237 let (public, sealed) = match state.store.web_push_keys().await? {
238 Some(pair) => pair,
239 None => {
240 let private = crypto::new_vapid_private();
241 let public = crypto::vapid_public_key(&private)?;
242 let sealed = forge_core::secret::seal(&state.key, &private)?;
243 state.store.save_web_push_keys(&public, &sealed).await?
244 }
245 };
246 let opened = forge_core::secret::open(&state.key, &sealed)?;
247 let private: [u8; 32] = opened
248 .try_into()
249 .map_err(|_| Error::Crypto("the stored VAPID key has the wrong length".into()))?;
250 Ok(VapidKeys { private, public })
251}
252
253/// The contact the push service may use about this instance: the base URL when it is https.
254fn subject(base_url: &str) -> String {
255 let base = base_url.trim_end_matches('/');
256 if base.starts_with("https://") {
257 base.to_owned()
258 } else {
259 "https://localhost".to_owned()
260 }
261}
262
263/// What the push service answered for one device.
264#[derive(Debug, PartialEq, Eq)]
265pub enum Outcome {
266 Delivered,
267 /// 404 or 410: the subscription is gone and the device must be forgotten.
268 Gone,
269 Failed(String),
270}
271
272/// Encrypts `payload` for one device and posts it to the device's push service.
273pub async fn send_one(
274 client: &reqwest::Client,
275 policy: &WebhookPolicy,
276 keys: &VapidKeys,
277 subject: &str,
278 sub: &PushSubscription,
279 payload: &[u8],
280) -> Outcome {
281 // Checked again on each send: an address literal never reaches the resolver's filter.
282 if let Err(e) = validate_url(&sub.endpoint, policy) {
283 return Outcome::Failed(e.to_string());
284 }
285 let built = (|| {
286 let p256dh = crypto::decode_b64(&sub.p256dh)?;
287 let auth = crypto::decode_b64(&sub.auth)?;
288 let key_pair = crypto::vapid_key_pair(&keys.private)?;
289 crypto::push_request(
290 &sub.endpoint,
291 &p256dh,
292 &auth,
293 subject,
294 &key_pair,
295 payload.to_vec(),
296 )
297 })();
298 let request = match built {
299 Ok(request) => request,
300 Err(e) => return Outcome::Failed(e.to_string()),
301 };
302 let request = match reqwest::Request::try_from(request) {
303 Ok(request) => request,
304 Err(e) => return Outcome::Failed(e.to_string()),
305 };
306 match client.execute(request).await {
307 Ok(res) => match res.status().as_u16() {
308 200..=299 => Outcome::Delivered,
309 404 | 410 => Outcome::Gone,
310 status => Outcome::Failed(format!("the push service answered {status}")),
311 },
312 Err(e) => Outcome::Failed(e.to_string()),
313 }
314}
315
316/// Queues `alert` for every device of `user_id`. Returns at once: the work runs on a spawned task.
317pub fn queue(state: &AppState, user_id: &str, alert: Alert) {
318 let state = state.clone();
319 let user_id = user_id.to_owned();
320 tokio::spawn(async move {
321 if let Err(e) = deliver(&state, &user_id, &alert).await {
322 tracing::error!(error = %e, user_id, "web push: delivery failed");
323 }
324 });
325}
326
327/// Sends `alert` to every device of `user_id` now and returns how many devices there are. Devices
328/// the push service reports gone are removed. [`queue`] is the caller's entry point.
329pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<usize> {
330 let devices = state.store.push_subscriptions(user_id).await?;
331 if devices.is_empty() {
332 return Ok(0);
333 }
334 let lang = match state.store.user_by_id(user_id).await? {
335 Some(user) => i18n::resolve(Some(user.language.as_str()), &http::HeaderMap::new()),
336 None => Lang::En,
337 };
338 let payload = serde_json::to_vec(&alert.message(lang))
339 .map_err(|e| Error::Invalid(format!("the push payload does not encode: {e}")))?;
340 let keys = vapid_keys(state).await?;
341 let subject = subject(&state.live().base_url);
342 let policy = crate::mirrors::policy(state);
343 let Some(client) = client(&policy) else {
344 return Err(Error::Invalid("the web push client does not build".into()));
345 };
346 for device in &devices {
347 match send_one(client, &policy, &keys, &subject, device, &payload).await {
348 Outcome::Delivered => {
349 state.store.mark_push_delivered(&device.id).await?;
350 state.push_live.publish(user_id);
351 }
352 Outcome::Gone => {
353 state.store.delete_push_endpoint(&device.endpoint).await?;
354 state.push_live.publish(user_id);
355 }
356 Outcome::Failed(reason) => {
357 tracing::warn!(reason, device = %device.id, "web push: a device was not reached");
358 }
359 }
360 }
361 Ok(devices.len())
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367 use p256::elliptic_curve::sec1::ToSec1Point;
368
369 fn activity(actor: Option<&str>) -> Alert {
370 Alert::Activity {
371 repo: "tahinli/forge".into(),
372 number: 42,
373 title: "Crash on startup\nwhen the cache is cold".into(),
374 verb: misc::K::VerbCommented,
375 actor: actor.map(str::to_owned),
376 url: "/tahinli/forge/issues/42".into(),
377 thread: "issue-1".into(),
378 }
379 }
380
381 #[test]
382 fn an_activity_payload_is_short_and_names_the_thread() {
383 let msg = activity(Some("tahinli")).message(Lang::En);
384 assert_eq!(msg.title, "tahinli/forge#42");
385 assert_eq!(
386 msg.body,
387 "commented by tahinli: Crash on startup when the cache is cold"
388 );
389 assert_eq!(msg.url, "/tahinli/forge/issues/42");
390 assert_eq!(msg.tag, "thread-issue-1");
391 }
392
393 #[test]
394 fn the_body_is_clipped_to_the_limit() {
395 let long = Alert::Admin {
396 subject: "Backup".into(),
397 detail: "x".repeat(400),
398 };
399 let msg = long.message(Lang::En);
400 assert_eq!(msg.body.chars().count(), BODY_CHARS);
401 assert!(msg.body.ends_with("..."));
402 }
403
404 #[test]
405 fn the_payload_follows_the_recipient_language() {
406 let msg = activity(None).message(Lang::Tr);
407 assert!(msg.body.starts_with("Yorumlandı"), "{}", msg.body);
408 let advisories = Alert::Advisories {
409 repo: "tahinli/forge".into(),
410 count: 3,
411 url: "/tahinli/forge/security".into(),
412 };
413 assert_eq!(advisories.message(Lang::En).body, "3 new security alerts");
414 assert_eq!(advisories.message(Lang::Tr).body, "3 yeni güvenlik uyarısı");
415 }
416
417 #[test]
418 fn a_link_must_stay_on_this_origin() {
419 assert_eq!(safe_url("/tahinli/forge"), "/tahinli/forge");
420 assert_eq!(safe_url("https://evil.example/x"), "/notifications");
421 assert_eq!(safe_url("//evil.example/x"), "/notifications");
422 assert_eq!(safe_url("/\\evil.example"), "/notifications");
423 }
424
425 #[test]
426 fn device_labels_name_the_browser_and_the_system() {
427 let chrome_android = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36";
428 assert_eq!(agent_label(chrome_android), "Chrome on Android");
429 let safari_iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1";
430 assert_eq!(agent_label(safari_iphone), "Safari on iPhone");
431 assert_eq!(agent_label("curl/8.0"), "Browser on Unknown system");
432 }
433
434 #[test]
435 fn the_subject_is_https_or_the_fallback() {
436 assert_eq!(
437 subject("https://forge.example.test/"),
438 "https://forge.example.test"
439 );
440 assert_eq!(subject("http://127.0.0.1:7660"), "https://localhost");
441 }
442
443 #[test]
444 fn push_live_reaches_a_listener_and_tolerates_none() {
445 let live = PushLive::default();
446 live.publish("nobody");
447 let mut rx = live.subscribe();
448 live.publish("tahinli");
449 assert_eq!(rx.try_recv().expect("event"), "tahinli");
450 }
451
452 /// A local stand-in for a push service: `/gone` answers 410, `/ok` answers 201, and each
453 /// request is read in full (headers and body) before it is answered.
454 async fn mock_push_service() -> std::net::SocketAddr {
455 use tokio::io::{AsyncReadExt, AsyncWriteExt};
456 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
457 .await
458 .expect("bind");
459 let addr = listener.local_addr().expect("addr");
460 tokio::spawn(async move {
461 loop {
462 let Ok((mut socket, _)) = listener.accept().await else {
463 return;
464 };
465 tokio::spawn(async move {
466 let mut buf = Vec::new();
467 let mut chunk = [0u8; 4096];
468 let (head_end, length) = loop {
469 let n = socket.read(&mut chunk).await.unwrap_or(0);
470 if n == 0 {
471 return;
472 }
473 buf.extend_from_slice(&chunk[..n]);
474 if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
475 let head = String::from_utf8_lossy(&buf[..end]).to_ascii_lowercase();
476 let length = head
477 .lines()
478 .find_map(|l| l.strip_prefix("content-length:"))
479 .and_then(|v| v.trim().parse::<usize>().ok())
480 .unwrap_or(0);
481 break (end + 4, length);
482 }
483 };
484 while buf.len() < head_end + length {
485 let n = socket.read(&mut chunk).await.unwrap_or(0);
486 if n == 0 {
487 break;
488 }
489 buf.extend_from_slice(&chunk[..n]);
490 }
491 let request = String::from_utf8_lossy(&buf[..head_end]).into_owned();
492 let status = if request.starts_with("POST /gone") {
493 "410 Gone"
494 } else {
495 "201 Created"
496 };
497 let reply = format!(
498 "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
499 );
500 let _ = socket.write_all(reply.as_bytes()).await;
501 });
502 }
503 });
504 addr
505 }
506
507 fn device(endpoint: String) -> PushSubscription {
508 let secret = p256::SecretKey::from_slice(&crypto::new_vapid_private()).expect("scalar");
509 let point = secret.public_key().to_sec1_point(false);
510 PushSubscription {
511 id: endpoint.clone(),
512 user_id: String::new(),
513 endpoint,
514 p256dh: crypto::encode_b64(point.as_bytes()),
515 auth: crypto::encode_b64(&[9u8; 16]),
516 agent_label: "Chrome on Linux".into(),
517 created_at: String::new(),
518 last_success_at: None,
519 }
520 }
521
522 #[tokio::test]
523 async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() {
524 let dir = tempfile::tempdir().expect("tempdir");
525 let mut state = crate::test_support::test_state(dir.path()).await;
526 // The mock push service is on loopback over http, which the policy refuses by default.
527 let mut config = crate::test_support::test_config(dir.path());
528 config.webhooks = forge_core::config::WebhookConfig {
529 allow_http: true,
530 allowed_hosts: vec!["127.0.0.1".into()],
531 };
532 state.config = std::sync::Arc::new(config);
533 let user = state
534 .store
535 .create_user("tahinli", None, "h", false)
536 .await
537 .expect("user");
538 let addr = mock_push_service().await;
539 let gone = format!("http://{addr}/gone");
540 let ok = format!("http://{addr}/ok");
541 state
542 .store
543 .save_push_subscription(
544 &user.id,
545 &gone,
546 &device(gone.clone()).p256dh,
547 &device(gone.clone()).auth,
548 "Chrome on Linux",
549 )
550 .await
551 .expect("save gone");
552 state
553 .store
554 .save_push_subscription(
555 &user.id,
556 &ok,
557 &device(ok.clone()).p256dh,
558 &device(ok.clone()).auth,
559 "Chrome on Linux",
560 )
561 .await
562 .expect("save ok");
563
564 let sent = deliver(&state, &user.id, &Alert::Test)
565 .await
566 .expect("deliver");
567 assert_eq!(sent, 2);
568 let left = state
569 .store
570 .push_subscriptions(&user.id)
571 .await
572 .expect("list");
573 assert_eq!(left.len(), 1, "the 410 device is forgotten");
574 assert_eq!(left[0].endpoint, ok);
575 assert!(
576 left[0].last_success_at.is_some(),
577 "the delivered device is stamped"
578 );
579 }
580
581 #[tokio::test]
582 async fn the_payload_is_encrypted_for_the_device_and_the_status_is_read() {
583 let addr = mock_push_service().await;
584 let private = crypto::new_vapid_private();
585 let keys = VapidKeys {
586 public: crypto::vapid_public_key(&private).expect("public"),
587 private,
588 };
589 let payload = serde_json::to_vec(&Alert::Test.message(Lang::En)).expect("json");
590 let open = WebhookPolicy::from_config(&forge_core::config::WebhookConfig {
591 allow_http: true,
592 allowed_hosts: vec!["127.0.0.1".into()],
593 })
594 .expect("policy");
595 let client = reqwest::Client::new();
596 let send = |endpoint: String, policy: WebhookPolicy| {
597 let (client, keys, payload) = (&client, &keys, &payload);
598 async move {
599 send_one(
600 client,
601 &policy,
602 keys,
603 "https://localhost",
604 &device(endpoint),
605 payload,
606 )
607 .await
608 }
609 };
610 assert_eq!(
611 send(format!("http://{addr}/ok"), open.clone()).await,
612 Outcome::Delivered
613 );
614 assert_eq!(
615 send(format!("http://{addr}/gone"), open).await,
616 Outcome::Gone
617 );
618 // The default policy refuses an internal address before anything is sent.
619 let strict = WebhookPolicy::from_config(&forge_core::config::WebhookConfig::default())
620 .expect("policy");
621 assert!(matches!(
622 send(format!("http://{addr}/ok"), strict).await,
623 Outcome::Failed(_)
624 ));
625 }
626}