From 243c4e4e642c6c1200f4a8c76e01f4c659fec5bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 12:24:14 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20service=20health=20probe=20?= =?UTF-8?q?every=2060=20s;=20oversized=20pictures=20get=20their=20own=20me?= =?UTF-8?q?ssage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/im-core/src/error.rs | 3 + crates/im-core/src/photo.rs | 20 ++-- crates/im-core/src/store/services.rs | 47 +++++++++- crates/im-web/src/boot.rs | 3 + crates/im-web/src/i18n/account.rs | 8 ++ crates/im-web/src/main.rs | 1 + crates/im-web/src/pages/profile.rs | 8 ++ crates/im-web/src/service_probe.rs | 135 +++++++++++++++++++++++++++ 8 files changed, 216 insertions(+), 9 deletions(-) create mode 100644 crates/im-web/src/service_probe.rs diff --git a/crates/im-core/src/error.rs b/crates/im-core/src/error.rs index c0af2ea..c6cf1e8 100644 --- a/crates/im-core/src/error.rs +++ b/crates/im-core/src/error.rs @@ -33,6 +33,9 @@ pub enum Error { /// The input is malformed or breaks a policy. Shown to the user. #[error("invalid value: {0}")] Invalid(String), + /// A picture has a side longer than the decoder accepts. The web layer shows its own message for it. + #[error("picture too large")] + PictureTooLarge, } /// `Result` with the crate error. diff --git a/crates/im-core/src/photo.rs b/crates/im-core/src/photo.rs index 0e8f554..e18ee94 100644 --- a/crates/im-core/src/photo.rs +++ b/crates/im-core/src/photo.rs @@ -55,9 +55,10 @@ fn refused() -> Error { /// Turns an upload into the stored picture: a square WebP of at most [`MAX_SIDE`] pixels. /// -/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says, and any -/// image that is larger than the input limits or cannot be decoded. Only the first frame of an -/// animated GIF is kept. +/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says. A picture with a side +/// longer than [`MAX_INPUT_SIDE`] is refused with [`Error::PictureTooLarge`], so the uploader sees the size +/// as the reason. Any other image that is larger than the input limits or cannot be decoded is refused too. +/// Only the first frame of an animated GIF is kept. pub fn normalize_photo(input: &[u8]) -> Result> { let format = image::guess_format(input).map_err(|_| refused())?; let accepted = matches!( @@ -72,14 +73,17 @@ pub fn normalize_photo(input: &[u8]) -> Result> { limits.max_image_width = Some(MAX_INPUT_SIDE); limits.max_image_height = Some(MAX_INPUT_SIDE); limits.max_alloc = Some(MAX_DECODE_ALLOC); + // Reading the header is cheap; the dimensions are checked here, before any pixel is decoded. The + // size is checked before the decoder limits, so an oversized picture gets its own answer. + let (declared_width, declared_height) = ImageReader::with_format(Cursor::new(input), format) + .into_dimensions() + .map_err(decode_error)?; + if declared_width > MAX_INPUT_SIDE || declared_height > MAX_INPUT_SIDE { + return Err(Error::PictureTooLarge); + } let mut reader = ImageReader::with_format(Cursor::new(input), format); reader.limits(limits); - // Reading the header is cheap; the dimensions are checked here, before any pixel is decoded. let mut decoder = reader.into_decoder().map_err(decode_error)?; - let (declared_width, declared_height) = decoder.dimensions(); - if declared_width > MAX_INPUT_SIDE || declared_height > MAX_INPUT_SIDE { - return Err(refused()); - } // Phones store the rotation in EXIF and leave the pixels sideways; apply it before cropping. let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); let mut image = DynamicImage::from_decoder(decoder).map_err(decode_error)?; diff --git a/crates/im-core/src/store/services.rs b/crates/im-core/src/store/services.rs index 44cd240..736540b 100644 --- a/crates/im-core/src/store/services.rs +++ b/crates/im-core/src/store/services.rs @@ -1,7 +1,8 @@ //! The service switcher list (contracts.md 4): one row per family app, plus im's own row. //! //! im's row is kept at boot from `base_url`, so it cannot drift from the configuration. The other rows -//! are written by the admin pages, which are not built yet. +//! are written by the admin services page. The health worker writes `healthy` and `checked_at` of every row +//! through [`Store::record_health`]. use crate::error::Result; use crate::model::Service; @@ -40,4 +41,48 @@ impl Store { .map_err(db_err)?; Ok(()) } + + /// Records the answer of one health probe: whether the service is healthy, and when it was checked. + /// Its name, address and position stay as they are. A key that no longer exists is a no-op. + pub async fn record_health(&self, key: &str, healthy: bool, checked_at: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE services SET healthy = ?2, checked_at = ?3 WHERE key = ?1", + (key.to_string(), i64::from(healthy), checked_at.to_string()), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn a_health_answer_is_stored_on_the_row() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + store + .upsert_home_service("Account", "https://im.example.com") + .await + .unwrap(); + store + .record_health("im", false, "2026-10-28T09:00:00.000000000Z") + .await + .unwrap(); + let home = store + .list_services() + .await + .unwrap() + .into_iter() + .find(|service| service.key == "im") + .unwrap(); + assert_eq!(home.healthy, Some(false)); + assert_eq!( + home.checked_at.as_deref(), + Some("2026-10-28T09:00:00.000000000Z") + ); + } } diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index 8787497..817f414 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -28,6 +28,7 @@ use crate::oidc::signing; use crate::pages::not_found::NotFoundLayer; use crate::pages::profile::PHOTO_ROUTE; use crate::security::{self, SecurityHeaders}; +use crate::service_probe; use crate::state::AppState; use crate::sweeper; use crate::throttle::Throttle; @@ -97,6 +98,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { stop_rx.clone(), ); let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone()); + let probe_worker = service_probe::spawn(state.store.clone(), stop_rx.clone()); let mail_worker = mail::worker::spawn( state.store.clone(), state.key.clone(), @@ -113,6 +115,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { let _ = signing_worker.await; let _ = backchannel_worker.await; let _ = sweeper_task.await; + let _ = probe_worker.await; let _ = mail_worker.await; if let Some(task) = backup_task { let _ = task.await; diff --git a/crates/im-web/src/i18n/account.rs b/crates/im-web/src/i18n/account.rs index ed9db8f..22350ef 100644 --- a/crates/im-web/src/i18n/account.rs +++ b/crates/im-web/src/i18n/account.rs @@ -208,6 +208,8 @@ pub enum Txt { ErrPhotoType, /// Shown when the upload is over the size limit. ErrPhotoTooLarge, + /// Shown when the picture has a side longer than the decoder accepts (4096 pixels). + ErrPhotoDimensions, /// Shown when the upload form was sent without a file. ErrPhotoMissing, /// Shown when the account has used its photo uploads for the hour. @@ -501,6 +503,12 @@ pub fn text(lang: Lang, key: Txt) -> &'static str { (Txt::ErrPhotoType, Lang::Tr) => "Lütfen bir PNG, JPEG, WebP veya GIF resmi seçin.", (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.", (Txt::ErrPhotoTooLarge, Lang::Tr) => "Fotoğraf 5 MB'tan büyük.", + (Txt::ErrPhotoDimensions, Lang::En) => { + "The picture is too large; use one at most 4096 pixels on each side." + } + (Txt::ErrPhotoDimensions, Lang::Tr) => { + "Resim çok büyük; en fazla her kenarı 4096 piksel olan bir resim kullanın." + } (Txt::ErrPhotoRateLimited, Lang::En) => { "Too many photos were uploaded. Try again in an hour." } diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 067fd99..f5bef04 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -20,6 +20,7 @@ mod mail; mod oidc; mod pages; mod security; +mod service_probe; mod state; mod sweeper; mod throttle; diff --git a/crates/im-web/src/pages/profile.rs b/crates/im-web/src/pages/profile.rs index eda5ab3..717125b 100644 --- a/crates/im-web/src/pages/profile.rs +++ b/crates/im-web/src/pages/profile.rs @@ -199,6 +199,14 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result { text(lang, Txt::ErrPhotoType), )); } + Err(im_core::Error::PictureTooLarge) => { + return Ok(upload_problem( + cx, + lang, + viewer, + text(lang, Txt::ErrPhotoDimensions), + )); + } Err(error) => return Err(error.into()), }; diff --git a/crates/im-web/src/service_probe.rs b/crates/im-web/src/service_probe.rs new file mode 100644 index 0000000..02c05d2 --- /dev/null +++ b/crates/im-web/src/service_probe.rs @@ -0,0 +1,135 @@ +//! The health probe worker (contracts.md 4): every minute it asks each listed service for `GET /healthz` +//! and records the answer in that service's row of the `services` table. +//! +//! - A probe is a plain GET of `/healthz`. Redirects are not followed, so a `301` from a service is +//! a failure. The answer is healthy only when its status is `200`. At most [`BODY_LIMIT`] bytes of the +//! body are read, and they are discarded. +//! - A probe has [`PROBE_TIMEOUT`] to finish, from connect to the end of the body. A service that does not +//! answer in time is down. +//! - Only `http` and `https` origins are probed. Any other origin is recorded as down. +//! - im's own row (key `im`) is not probed: im is answering this very round, so it is recorded as healthy. +//! - The rows are probed a few at a time ([`PROBE_CONCURRENCY`]), so one slow service does not hold up the +//! others. Each row is recorded as soon as its own probe is done. +//! +//! The list is read again at every round, so a service the admin adds or removes is picked up within a minute. +//! Nothing here fails the server: a store error or a failed probe is logged, and the next round tries again. + +use std::time::Duration; + +use futures_util::{StreamExt, stream}; +use im_core::model::Service; +use im_core::store::Store; +use im_core::time::now_stamp; +use reqwest::{StatusCode, Url}; +use tokio::sync::watch; +use tokio::task::JoinHandle; + +/// The key of im's own row. im is never probed over HTTP: its answer is known. +const HOME_KEY: &str = "im"; + +/// The time between two rounds (contracts.md 4: every 60 seconds). +const EVERY: Duration = Duration::from_secs(60); + +/// How long a service has to answer one probe (contracts.md 4: 2 seconds). +pub const PROBE_TIMEOUT: Duration = Duration::from_secs(2); + +/// The most body bytes read from a probe answer. Only the status decides, so the body is read to drain it +/// and then discarded. +const BODY_LIMIT: usize = 256; + +/// How many probes run at once. +const PROBE_CONCURRENCY: usize = 8; + +/// Starts the worker. It runs one round at boot and then every [`EVERY`], until `stop` is set. +pub fn spawn(store: Store, mut stop: watch::Receiver) -> JoinHandle<()> { + tokio::spawn(async move { + let http = probe_client(); + loop { + round(&store, &http).await; + tokio::select! { + () = tokio::time::sleep(EVERY) => {} + _ = stop.wait_for(|stopped| *stopped) => return, + } + } + }) +} + +/// The HTTP client of the probes: two-second timeouts and no redirects. +fn probe_client() -> reqwest::Client { + reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(PROBE_TIMEOUT) + .connect_timeout(PROBE_TIMEOUT) + .build() + .expect("the probe HTTP client can be built with fixed settings") +} + +/// One round: im's own row is recorded as healthy, and every other row is probed and recorded. +/// Failures are logged per row. +pub async fn round(store: &Store, http: &reqwest::Client) { + let services = match store.list_services().await { + Ok(services) => services, + Err(error) => { + tracing::error!(error = %error, "service probes: cannot list the services"); + return; + } + }; + if let Err(error) = store.record_health(HOME_KEY, true, &now_stamp()).await { + tracing::error!(error = %error, "service probes: cannot record im's own health"); + } + // The probes are built in a loop and polled `PROBE_CONCURRENCY` at a time, as the back-channel worker does. + let mut pending = Vec::with_capacity(services.len()); + for service in &services { + if service.key != HOME_KEY { + pending.push(probe_and_record(store, http, service)); + } + } + stream::iter(pending) + .buffer_unordered(PROBE_CONCURRENCY) + .collect::>() + .await; +} + +/// Probes one row and records the answer with the time it was recorded. +async fn probe_and_record(store: &Store, http: &reqwest::Client, service: &Service) { + let healthy = probe(http, &service.key, &service.url).await; + if let Err(error) = store + .record_health(&service.key, healthy, &now_stamp()) + .await + { + tracing::error!(service = %service.key, error = %error, "service probes: cannot record the answer"); + } +} + +/// True when `origin` is an http or https origin whose `/healthz` answers `200` within the timeout. +async fn probe(http: &reqwest::Client, key: &str, origin: &str) -> bool { + let parsed = match Url::parse(origin) { + Ok(url) if matches!(url.scheme(), "http" | "https") => url, + _ => { + tracing::warn!(service = %key, "service probes: the origin is not an http or https address"); + return false; + } + }; + let target = format!("{}/healthz", parsed.as_str().trim_end_matches('/')); + let mut response = match http.get(&target).send().await { + Ok(response) => response, + Err(error) => { + tracing::warn!(service = %key, error = %error, "service probe failed"); + return false; + } + }; + let healthy = response.status() == StatusCode::OK; + // Drain the body up to the limit so the connection can be reused. The last chunk may pass the limit; + // it is discarded either way. + let mut read = 0; + while read < BODY_LIMIT { + match response.chunk().await { + Ok(Some(chunk)) => read += chunk.len(), + _ => break, + } + } + if !healthy { + tracing::warn!(service = %key, status = %response.status(), "service probe answered unhealthy"); + } + healthy +}