From 5dda6c98494e976baf6229ed794311aa7cfab9c2 Mon Sep 17 00:00:00 2001 From: Anoop Sundaresh <16442416+theryecatcher@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:08:36 -0500 Subject: [PATCH 1/2] Allow rendering HTML pastes as sandboxed pages Let pastes be viewed as the page itself at `/html/{id}`, so self contained documents with inline CSS, SVG and web fonts can be shared directly instead of as highlighted source. The feature is opt-in through `WASTEBIN_RENDER_UNTRUSTED_HTML`. - Serve the paste unmodified under a CSP `sandbox` with no allow flags. It gets an opaque origin with no access to wastebin cookies, and scripts, forms, pop-ups and automatic redirects are blocked. - Show a toggle to the page on `html` and `htm` pastes. - Have handlers return a typed `Csp` that the security headers layer writes as the only policy, defaulting to strict. As a side effrct Markdown burn, password and error pages now get the strict policy too. - Share the burn confirmation and password prompt flow across the source, Markdown and HTML views, so each view only names the route its prompts post back to. --- CHANGELOG.md | 8 + README.md | 26 ++ crates/wastebin_core/src/env.rs | 2 + crates/wastebin_server/src/csp.rs | 42 +++ crates/wastebin_server/src/env.rs | 16 +- .../src/handlers/html/document.rs | 248 ++++++++++++++++++ .../wastebin_server/src/handlers/html/mod.rs | 92 ++++++- .../src/handlers/html/paste.rs | 67 ++--- .../wastebin_server/src/handlers/html/qr.rs | 5 +- .../src/handlers/html/rendered.rs | 63 ++--- crates/wastebin_server/src/i18n.rs | 2 +- crates/wastebin_server/src/main.rs | 43 +-- crates/wastebin_server/src/page.rs | 3 + crates/wastebin_server/src/test_helpers.rs | 8 + .../wastebin_server/templates/formatted.html | 4 + crates/wastebin_server/templates/paste.html | 2 +- crates/wastebin_server/templates/qr.html | 4 + 17 files changed, 522 insertions(+), 113 deletions(-) create mode 100644 crates/wastebin_server/src/csp.rs create mode 100644 crates/wastebin_server/src/handlers/html/document.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d352978..d149d820 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +### Added + +- Show pastes as standalone pages at `/html/{id}`, with a toggle from the paste + view on `html` and `htm` pastes like rendered Markdown. The page is served + unmodified under a CSP `sandbox` that blocks scripts, forms and access to + wastebin cookies. It is off by default; set + `WASTEBIN_RENDER_UNTRUSTED_HTML=true` to turn it on. + ### Fixed - Reject off-origin and scheme-relative `Referer` values when redirecting back diff --git a/README.md b/README.md index 4a2d058e..8afc374e 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ to released versions here: [syntect](https://github.com/trishume/syntect) * renders Markdown pastes to HTML, including GitHub-flavored tables, task lists and admonitions +* optionally shows HTML pastes as sandboxed pages * comes with [nine color themes](https://matze.github.io/wastebin/) in light and dark mode * encrypts entries using ChaCha20Poly1305 and argon2 hashed passwords @@ -191,6 +192,30 @@ embedded via `![alt](https://…)`, the Content Security Policy is relaxed to `img-src *` for `/md/*` responses only; all other routes keep the strict default. +### HTML pages + +When `WASTEBIN_RENDER_UNTRUSTED_HTML` is set to `true`, any paste can be viewed +as a page of its own at `/html/{id}`. Pastes opened with an `html` or `htm` +extension get a toggle to that page, like rendered Markdown. The extension is +part of the URL rather than the paste, so it only decides whether the toggle is +shown. It is off by default, and `/html/{id}` then returns 404. The paste is +served unmodified, without the wastebin interface, so inline styles, SVG and web +fonts render the way it was written. Burn after reading and password protected +pastes show the usual confirmation and password pages first. + +The page is served with a Content Security Policy `sandbox`, which gives it an +opaque origin, so it cannot read wastebin cookies or act on behalf of the +viewer. Scripts, form submissions, pop-ups and automatic redirects are blocked; +links still work when clicked. Stylesheets may load from Google Fonts and images +from anywhere. + +The sandbox keeps wastebin and its viewers' sessions safe, but it cannot vouch +for what a page says. Anyone who can paste can publish a full screen page +under your domain, such as a convincing fake login form that tells visitors to +send their credentials elsewhere, and loading remote images lets the author +see who opened it. Turn this on only when you trust the people who can paste, +or when a reverse proxy in front of wastebin limits who can reach `/html/`. + ### Configuration The following environment variables can be set to configure the server and @@ -206,6 +231,7 @@ run-time behavior: | `WASTEBIN_MAX_BODY_SIZE` | Number of bytes to accept for POST requests. | `1048576`, i.e. 1 MB | | `WASTEBIN_PASSWORD_SALT` | Salt used to hash user passwords used for encrypting pastes. | `somesalt` | | `WASTEBIN_PASTE_EXPIRATIONS` | Possible paste expirations as a comma-separated list of seconds or values with duration magnitudes (`s`, `m`, `h`, `d`, `M`, `y` for seconds, minutes, hours, days, months and years respectively). Appending `=d` to one of the value makes it the default selection. | see [here](https://github.com/matze/wastebin/blob/eb61c78506a165605f145e8374ed64822405eda0/crates/wastebin_server/src/env.rs#L166) | +| `WASTEBIN_RENDER_UNTRUSTED_HTML` | Set to `true` to show pastes as sandboxed pages at `/html/{id}`. See [HTML pages](#html-pages) before enabling. | `false` | | `WASTEBIN_SIGNING_KEY` | Key to sign cookies. Must be at least 64 bytes long. | Random key generated at startup, i.e. cookies will become invalid after restarts and paste creators will not be able to delete their pastes. | | `WASTEBIN_THEME` | Theme colors, one of `ayu`, `base16ocean`, `catppuccin`, `coldark`, `gruvbox`, `monokai`, `onehalf`, `rosepine`, `solarized`. See [this page](https://matze.github.io/wastebin/) for a preview. | `ayu` | | `WASTEBIN_TITLE` | HTML page title. Pastes with their own title use that title instead. | `wastebin` | diff --git a/crates/wastebin_core/src/env.rs b/crates/wastebin_core/src/env.rs index 87c71a9f..95f313f8 100644 --- a/crates/wastebin_core/src/env.rs +++ b/crates/wastebin_core/src/env.rs @@ -16,6 +16,8 @@ pub mod vars { pub const PASSWORD_SALT: &str = "WASTEBIN_PASSWORD_SALT"; /// Expirations list. pub const PASTE_EXPIRATIONS: &str = "WASTEBIN_PASTE_EXPIRATIONS"; + /// Serve pastes as sandboxed pages at `/html/{id}`. + pub const RENDER_HTML: &str = "WASTEBIN_RENDER_UNTRUSTED_HTML"; /// Signing key for signed cookie store. pub const SIGNING_KEY: &str = "WASTEBIN_SIGNING_KEY"; /// Theme to use. diff --git a/crates/wastebin_server/src/csp.rs b/crates/wastebin_server/src/csp.rs new file mode 100644 index 00000000..3d6f56a4 --- /dev/null +++ b/crates/wastebin_server/src/csp.rs @@ -0,0 +1,42 @@ +use std::convert::Infallible; + +use axum::http::HeaderValue; +use axum::response::{IntoResponseParts, ResponseParts}; + +/// Content Security Policy of a response. Handlers return it as a response part and the security +/// headers layer writes it as the only `Content-Security-Policy` header, defaulting to +/// [`Csp::Strict`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Csp { + /// Wastebin's own pages. + Strict, + /// Rendered Markdown, which may embed remote images via `![](…)`. + Rendered, + /// HTML pastes served as their own page. + Sandbox, +} + +impl Csp { + pub(crate) const fn header(self) -> HeaderValue { + match self { + Self::Strict => HeaderValue::from_static( + "default-src 'none'; script-src 'self'; img-src 'self' data: ; style-src 'self' data: ; font-src 'self' data: ; object-src 'none' ; base-uri 'none' ; frame-ancestors 'none' ; form-action 'self' ;", + ), + Self::Rendered => HeaderValue::from_static( + "default-src 'none'; script-src 'self'; img-src * data: ; style-src 'self' data: ; font-src 'self' data: ; object-src 'none' ; base-uri 'none' ; frame-ancestors 'none' ; form-action 'self' ;", + ), + Self::Sandbox => HeaderValue::from_static( + "sandbox; default-src 'none'; style-src 'unsafe-inline' https://fonts.googleapis.com ; font-src https://fonts.gstatic.com data: ; img-src * data: ; base-uri 'none' ; form-action 'none' ; frame-ancestors 'none' ;", + ), + } + } +} + +impl IntoResponseParts for Csp { + type Error = Infallible; + + fn into_response_parts(self, mut res: ResponseParts) -> Result { + res.extensions_mut().insert(self); + Ok(res) + } +} diff --git a/crates/wastebin_server/src/env.rs b/crates/wastebin_server/src/env.rs index 9bc4ada1..7ff74342 100644 --- a/crates/wastebin_server/src/env.rs +++ b/crates/wastebin_server/src/env.rs @@ -9,7 +9,7 @@ use axum_extra::extract::cookie::Key; use wastebin_core::env::vars::{ self, ADDRESS_PORT, BASE_URL, CACHE_SIZE, DATABASE_PATH, HTTP_TIMEOUT, MAX_BODY_SIZE, - PASTE_EXPIRATIONS, SIGNING_KEY, + PASTE_EXPIRATIONS, RENDER_HTML, SIGNING_KEY, }; use wastebin_core::{db, expiration}; use wastebin_highlight::{Theme, theme::ParseThemeNameError}; @@ -22,6 +22,8 @@ pub(crate) enum Error { CacheConstruction(#[from] cached::BuildError), #[error("failed to parse {CACHE_SIZE}, expected number of elements: {0}")] CacheSize(ParseIntError), + #[error("failed to parse {RENDER_HTML}, expected `true` or `false`")] + RenderHtml, #[error("failed to parse {DATABASE_PATH}, contains non-Unicode data")] DatabasePath, #[error("failed to parse {MAX_BODY_SIZE}, expected number of bytes: {0}")] @@ -77,6 +79,18 @@ pub fn cache_size() -> Result { .map_err(Error::CacheSize) } +pub fn render_html() -> Result { + match std::env::var(vars::RENDER_HTML) { + Err(VarError::NotPresent) => Ok(false), + Err(VarError::NotUnicode(_)) => Err(Error::RenderHtml), + Ok(value) => match value.to_ascii_lowercase().as_str() { + "true" => Ok(true), + "false" => Ok(false), + _ => Err(Error::RenderHtml), + }, + } +} + pub fn database_method() -> Result { match std::env::var(vars::DATABASE_PATH) { Ok(path) => Ok(db::Open::Path(PathBuf::from(path))), diff --git a/crates/wastebin_server/src/handlers/html/document.rs b/crates/wastebin_server/src/handlers/html/document.rs new file mode 100644 index 00000000..4d0a9ea5 --- /dev/null +++ b/crates/wastebin_server/src/handlers/html/document.rs @@ -0,0 +1,248 @@ +use axum::extract::{Form, Path, State}; +use axum::http::{HeaderValue, header}; +use axum::response::{IntoResponse, Response}; + +use crate::cache::Key; +use crate::csp::Csp; +use crate::handlers::NoStore; +use crate::handlers::extract::Theme; +use crate::handlers::html::paste::PasteForm; +use crate::handlers::html::{ErrorResponse, FormAction, Unlock, Unlocked, make_error, unlock}; +use crate::i18n::Lang; +use crate::{Database, Page}; +use wastebin_core::db; + +pub async fn get( + State(page): State, + State(db): State, + Path(id): Path, + theme: Option, + lang: Lang, + form: Result, E>, +) -> Result { + async { + if !page.render_html { + return Err(db::Error::NotFound.into()); + } + + let key: Key = id.parse()?; + let form = form.ok().map(|Form(form)| form); + let action = FormAction::html(&key); + let Unlocked { + data, encrypted, .. + } = match unlock(&db, &page, theme.as_ref(), lang, &key, form, action).await? { + Unlock::Paste(unlocked) => unlocked, + Unlock::Prompt(response) => return Ok(response), + }; + + let response = ( + Csp::Sandbox, + [( + header::CONTENT_TYPE, + HeaderValue::from_static("text/html; charset=utf-8"), + )], + data.text, + ) + .into_response(); + + Ok(if encrypted { + response.no_store() + } else { + response + }) + } + .await + .map_err(|err| make_error(err, page, theme, lang)) +} + +#[cfg(test)] +mod tests { + use crate::handlers::insert::form::Entry; + use crate::test_helpers::{Client, RenderHtml, StoreCookies}; + use reqwest::{StatusCode, header}; + + const PAGE: &str = "Spec

Hello

"; + + fn csp(res: &reqwest::Response) -> String { + res.headers() + .get(header::CONTENT_SECURITY_POLICY) + .unwrap() + .to_str() + .unwrap() + .to_owned() + } + + fn assert_sandboxed(csp: &str) { + assert!(csp.starts_with("sandbox;"), "csp: {csp}"); + assert!(!csp.contains("allow-"), "csp: {csp}"); + assert!(csp.contains("default-src 'none'"), "csp: {csp}"); + } + + fn assert_strict(csp: &str) { + assert!(!csp.contains("sandbox"), "csp: {csp}"); + assert!(csp.contains("script-src 'self'"), "csp: {csp}"); + } + + async fn insert(client: &Client, data: &Entry) -> Result> { + let res = client.post_form().form(data).send().await?; + assert_eq!(res.status(), StatusCode::SEE_OTHER); + let location = res.headers().get("location").unwrap().to_str()?; + Ok(location.replace("burn/", "")) + } + + #[tokio::test] + async fn serves_paste_unmodified_in_sandbox() -> Result<(), Box> { + let client = Client::with_html(StoreCookies(false), RenderHtml(true)).await; + let data = Entry { + text: String::from(PAGE), + extension: Some(String::from("html")), + ..Default::default() + }; + let location = insert(&client, &data).await?; + + let res = client.get(&format!("/html{location}")).send().await?; + assert_eq!(res.status(), StatusCode::OK); + assert_eq!( + res.headers().get(header::CONTENT_TYPE).unwrap(), + "text/html; charset=utf-8" + ); + assert_sandboxed(&csp(&res)); + assert_eq!(res.text().await?, PAGE); + + Ok(()) + } + + #[tokio::test] + async fn burn_requires_confirmation() -> Result<(), Box> { + let client = Client::with_html(StoreCookies(false), RenderHtml(true)).await; + let data = Entry { + text: String::from(PAGE), + extension: Some(String::from("html")), + burn_after_reading: Some(String::from("on")), + ..Default::default() + }; + let location = insert(&client, &data).await?; + let document = format!("/html{location}"); + + let res = client.get(&document).send().await?; + assert_eq!(res.status(), StatusCode::OK); + assert_strict(&csp(&res)); + let body = res.text().await?; + assert!( + body.contains(&format!("action=\"{document}\"")), + "body: {body}" + ); + assert!(!body.contains("

Hello

"), "body: {body}"); + + let res = client.get(&document).send().await?; + assert_eq!(res.status(), StatusCode::OK); + + let res = client + .post(&document) + .form(&[("confirm_burn", "1")]) + .send() + .await?; + assert_eq!(res.status(), StatusCode::OK); + assert_sandboxed(&csp(&res)); + assert_eq!(res.text().await?, PAGE); + + let res = client.get(&document).send().await?; + assert_eq!(res.status(), StatusCode::NOT_FOUND); + + Ok(()) + } + + #[tokio::test] + async fn encrypted_paste_needs_password_and_is_not_stored() + -> Result<(), Box> { + let client = Client::with_html(StoreCookies(false), RenderHtml(true)).await; + let password = "hunter2"; + let data = Entry { + text: String::from(PAGE), + extension: Some(String::from("html")), + password: password.to_string(), + ..Default::default() + }; + let location = insert(&client, &data).await?; + let document = format!("/html{location}"); + + let res = client.get(&document).send().await?; + assert_eq!(res.status(), StatusCode::OK); + assert_eq!( + res.headers().get(header::CACHE_CONTROL).unwrap(), + "no-store" + ); + assert_strict(&csp(&res)); + let body = res.text().await?; + assert!( + body.contains(&format!("action=\"{document}\"")), + "body: {body}" + ); + + let res = client + .post(&document) + .form(&[("password", password)]) + .send() + .await?; + assert_eq!(res.status(), StatusCode::OK); + assert_eq!( + res.headers().get(header::CACHE_CONTROL).unwrap(), + "no-store" + ); + assert_sandboxed(&csp(&res)); + assert_eq!(res.text().await?, PAGE); + + Ok(()) + } + + #[tokio::test] + async fn missing_paste_is_not_found() -> Result<(), Box> { + let client = Client::with_html(StoreCookies(false), RenderHtml(true)).await; + + let res = client.get("/html/000000").send().await?; + assert_eq!(res.status(), StatusCode::NOT_FOUND); + assert_strict(&csp(&res)); + + Ok(()) + } + + #[tokio::test] + async fn source_view_links_to_document() -> Result<(), Box> { + let client = Client::with_html(StoreCookies(false), RenderHtml(true)).await; + let data = Entry { + text: String::from(PAGE), + extension: Some(String::from("html")), + ..Default::default() + }; + let location = insert(&client, &data).await?; + + let body = client.get(&location).send().await?.text().await?; + assert!( + body.contains(&format!("href=\"/html{location}\"")), + "body: {body}" + ); + + Ok(()) + } + + #[tokio::test] + async fn disabled_by_default() -> Result<(), Box> { + let client = Client::new(StoreCookies(false)).await; + let data = Entry { + text: String::from(PAGE), + extension: Some(String::from("html")), + ..Default::default() + }; + let location = insert(&client, &data).await?; + + let res = client.get(&format!("/html{location}")).send().await?; + assert_eq!(res.status(), StatusCode::NOT_FOUND); + assert_strict(&csp(&res)); + assert!(!res.text().await?.contains("

Hello

")); + + let body = client.get(&location).send().await?.text().await?; + assert!(!body.contains("href=\"/html/"), "body: {body}"); + + Ok(()) + } +} diff --git a/crates/wastebin_server/src/handlers/html/mod.rs b/crates/wastebin_server/src/handlers/html/mod.rs index e7507e0f..648c34a8 100644 --- a/crates/wastebin_server/src/handlers/html/mod.rs +++ b/crates/wastebin_server/src/handlers/html/mod.rs @@ -1,4 +1,5 @@ pub mod burn; +pub mod document; pub mod index; pub mod paste; pub mod qr; @@ -9,11 +10,17 @@ use std::fmt; use askama::Template; use askama_web::WebTemplate; use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; -use crate::Page; use crate::cache::Key; +use crate::handlers::NoStore; use crate::handlers::extract::Theme; +use crate::handlers::html::paste::PasteForm; use crate::i18n::Lang; +use crate::{Database, Page}; +use wastebin_core::crypto::Password; +use wastebin_core::db; +use wastebin_core::db::read::{Data, Entry}; /// Target of an interstitial's submit form, i.e. the view the paste was requested from. #[derive(Clone, Debug)] @@ -29,6 +36,11 @@ impl FormAction { pub(crate) fn rendered(key: &Key) -> Self { Self(format!("/md/{key}")) } + + /// Post back to the HTML document view at `/html/{key}`. + pub(crate) fn html(key: &Key) -> Self { + Self(format!("/html/{key}")) + } } impl fmt::Display for FormAction { @@ -69,6 +81,84 @@ pub(crate) struct BurnConfirmation { pub action: FormAction, } +/// A paste the viewer has confirmed burning and supplied the password for, where needed. +pub(crate) struct Unlocked { + pub data: Data, + /// If the paste is still in the database and can be fetched with another request. + pub is_available: bool, + pub encrypted: bool, + pub no_password: bool, +} + +/// Outcome of [`unlock`]: the paste, or the interstitial page to show before it. +pub(crate) enum Unlock { + Paste(Unlocked), + Prompt(Response), +} + +/// Fetch the paste behind `key`, unless it first needs a burn confirmation or a password. Both +/// prompts post back to `action` with the answer in `form`. +pub(crate) async fn unlock( + db: &Database, + page: &Page, + theme: Option<&Theme>, + lang: Lang, + key: &Key, + form: Option, + action: FormAction, +) -> Result { + let password = form + .as_ref() + .and_then(|form| form.password.as_ref()) + .filter(|password| !password.is_empty()) + .map(|password| Password::from(password.as_bytes().to_vec())); + let confirmed = form.as_ref().and_then(|form| form.confirm_burn.as_deref()) == Some("1"); + let no_password = password.is_none(); + let metadata = db.get_metadata(key.id).await?; + + if metadata.must_be_deleted && !confirmed { + return Ok(Unlock::Prompt( + BurnConfirmation { + page: page.clone(), + theme: theme.cloned(), + lang, + title: metadata.title, + action, + } + .into_response(), + )); + } + + let (data, is_available, encrypted) = match db.get(key.id, password).await { + Ok(Entry::Regular(data)) => (data, true, false), + Ok(Entry::Burned(data)) => (data, false, false), + Ok(Entry::Encrypted(data)) => { + let is_available = !data.metadata.must_be_deleted; + (data, is_available, true) + } + Err(db::Error::NoPassword) => { + return Ok(Unlock::Prompt( + PasswordInput { + page: page.clone(), + theme: theme.cloned(), + lang, + action, + } + .into_response() + .no_store(), + )); + } + Err(err) => return Err(err.into()), + }; + + Ok(Unlock::Paste(Unlocked { + data, + is_available, + encrypted, + no_password, + })) +} + /// Error response carrying a status code and the page itself. pub(crate) type ErrorResponse = (StatusCode, Error); diff --git a/crates/wastebin_server/src/handlers/html/paste.rs b/crates/wastebin_server/src/handlers/html/paste.rs index d7ac25b8..099277a6 100644 --- a/crates/wastebin_server/src/handlers/html/paste.rs +++ b/crates/wastebin_server/src/handlers/html/paste.rs @@ -8,15 +8,11 @@ use serde::Deserialize; use crate::cache::{Key, Mode}; use crate::handlers::extract::{Theme, Uids, verify_owner_token}; -use crate::handlers::html::{ - BurnConfirmation, ErrorResponse, FormAction, PasswordInput, make_error, -}; +use crate::handlers::html::{ErrorResponse, FormAction, Unlock, Unlocked, make_error, unlock}; use crate::handlers::{NoStore, uid_cookie}; use crate::i18n::Lang; use crate::{Cache, Database, Highlighter, Page}; -use wastebin_core::crypto::Password; -use wastebin_core::db; -use wastebin_core::db::read::{Data, Entry, Metadata}; +use wastebin_core::db::read::{Data, Metadata}; use wastebin_core::expiration::Expiration; /// Magic-link handoff: when a paste was created via the JSON API, the response contains a signed @@ -53,6 +49,9 @@ pub(crate) struct Paste { title: Option, /// Whether the paste's extension identifies it as Markdown, enabling the rendered-view toggle. is_markdown: bool, + /// Whether the paste's extension identifies it as HTML and HTML rendering is enabled, + /// enabling the document-view toggle. + is_html: bool, } /// Return `true` if `ext` identifies a Markdown paste. @@ -60,6 +59,11 @@ pub(crate) fn is_markdown_ext(ext: Option<&str>) -> bool { ext.is_some_and(|ext| ext.eq_ignore_ascii_case("md") || ext.eq_ignore_ascii_case("markdown")) } +/// Return `true` if `ext` identifies an HTML paste. +pub(crate) fn is_html_ext(ext: Option<&str>) -> bool { + ext.is_some_and(|ext| ext.eq_ignore_ascii_case("html") || ext.eq_ignore_ascii_case("htm")) +} + #[expect(clippy::too_many_arguments)] pub async fn get( State(cache): State, @@ -90,46 +94,17 @@ pub async fn get( } async { - let form = form.ok().map(|Form(form)| form); - let password = form - .as_ref() - .and_then(|form| form.password.as_ref()) - .filter(|password| !password.is_empty()) - .map(|password| Password::from(password.as_bytes().to_vec())); - let confirmed = form.as_ref().and_then(|form| form.confirm_burn.as_deref()) == Some("1"); - let no_password = password.is_none(); let key: Key = id.parse()?; - let metadata = db.get_metadata(key.id).await?; - - if metadata.must_be_deleted && !confirmed { - return Ok(BurnConfirmation { - page: page.clone(), - theme: theme.clone(), - lang, - title: metadata.title.clone(), - action: FormAction::source(&key), - } - .into_response()); - } - - let (data, is_available, encrypted) = match db.get(key.id, password).await { - Ok(Entry::Regular(data)) => (data, true, false), - Ok(Entry::Burned(data)) => (data, false, false), - Ok(Entry::Encrypted(data)) => { - let is_available = !data.metadata.must_be_deleted; - (data, is_available, true) - } - Err(db::Error::NoPassword) => { - return Ok(PasswordInput { - page: page.clone(), - theme: theme.clone(), - lang, - action: FormAction::source(&key), - } - .into_response() - .no_store()); - } - Err(err) => return Err(err.into()), + let form = form.ok().map(|Form(form)| form); + let action = FormAction::source(&key); + let Unlocked { + data, + is_available, + encrypted, + no_password, + } = match unlock(&db, &page, theme.as_ref(), lang, &key, form, action).await? { + Unlock::Paste(unlocked) => unlocked, + Unlock::Prompt(response) => return Ok(response), }; let Data { text, metadata } = data; @@ -163,6 +138,7 @@ pub async fn get( }; let is_markdown = is_markdown_ext(key.ext.as_deref()); + let is_html = page.render_html && is_html_ext(key.ext.as_deref()); let paste = Paste { page: page.clone(), key, @@ -174,6 +150,7 @@ pub async fn get( html, title, is_markdown, + is_html, }; let response = paste.into_response(); diff --git a/crates/wastebin_server/src/handlers/html/qr.rs b/crates/wastebin_server/src/handlers/html/qr.rs index 882856f1..5b4af8ee 100644 --- a/crates/wastebin_server/src/handlers/html/qr.rs +++ b/crates/wastebin_server/src/handlers/html/qr.rs @@ -6,7 +6,7 @@ use url::Url; use crate::cache::Key; use crate::handlers::extract::{Theme, Uids}; -use crate::handlers::html::paste::is_markdown_ext; +use crate::handlers::html::paste::{is_html_ext, is_markdown_ext}; use crate::handlers::html::{ErrorResponse, make_error}; use crate::i18n::Lang; use crate::{Error, Page}; @@ -47,6 +47,7 @@ pub async fn get( }; let is_markdown = is_markdown_ext(key.ext.as_deref()); + let is_html = page.render_html && is_html_ext(key.ext.as_deref()); Ok(Qr { page: page.clone(), @@ -59,6 +60,7 @@ pub async fn get( title, expiration, is_markdown, + is_html, }) } .await @@ -76,6 +78,7 @@ pub(crate) struct Qr { can_delete: bool, is_available: bool, is_markdown: bool, + is_html: bool, code: qrcodegen::QrCode, title: Option, expiration: Option, diff --git a/crates/wastebin_server/src/handlers/html/rendered.rs b/crates/wastebin_server/src/handlers/html/rendered.rs index d8c4f893..31da7a86 100644 --- a/crates/wastebin_server/src/handlers/html/rendered.rs +++ b/crates/wastebin_server/src/handlers/html/rendered.rs @@ -4,17 +4,14 @@ use axum::extract::{Form, Path, State}; use axum::response::{IntoResponse, Response}; use crate::cache::{Key, Mode}; +use crate::csp::Csp; use crate::handlers::NoStore; use crate::handlers::extract::{Theme, Uids}; use crate::handlers::html::paste::PasteForm; -use crate::handlers::html::{ - BurnConfirmation, ErrorResponse, FormAction, PasswordInput, make_error, -}; +use crate::handlers::html::{ErrorResponse, FormAction, Unlock, Unlocked, make_error, unlock}; use crate::i18n::Lang; use crate::{Cache, Database, Highlighter, Page}; -use wastebin_core::crypto::Password; -use wastebin_core::db; -use wastebin_core::db::read::{Data, Entry, Metadata}; +use wastebin_core::db::read::{Data, Metadata}; use wastebin_core::expiration::Expiration; use wastebin_highlight::markdown; @@ -30,6 +27,8 @@ pub(crate) struct Rendered { is_available: bool, /// Always `true` for this view; needed by the inherited paste template. is_markdown: bool, + /// Always `false` for this view; needed by the inherited paste template. + is_html: bool, expiration: Option, html: String, title: Option, @@ -48,46 +47,17 @@ pub async fn get( form: Result, E>, ) -> Result { async { - let form = form.ok().map(|Form(form)| form); - let password = form - .as_ref() - .and_then(|form| form.password.as_ref()) - .filter(|password| !password.is_empty()) - .map(|password| Password::from(password.as_bytes().to_vec())); - let confirmed = form.as_ref().and_then(|form| form.confirm_burn.as_deref()) == Some("1"); - let no_password = password.is_none(); let key: Key = id.parse()?; - let metadata = db.get_metadata(key.id).await?; - - if metadata.must_be_deleted && !confirmed { - return Ok(BurnConfirmation { - page: page.clone(), - theme: theme.clone(), - lang, - title: metadata.title.clone(), - action: FormAction::rendered(&key), - } - .into_response()); - } - - let (data, is_available, encrypted) = match db.get(key.id, password).await { - Ok(Entry::Regular(data)) => (data, true, false), - Ok(Entry::Burned(data)) => (data, false, false), - Ok(Entry::Encrypted(data)) => { - let is_available = !data.metadata.must_be_deleted; - (data, is_available, true) - } - Err(db::Error::NoPassword) => { - return Ok(PasswordInput { - page: page.clone(), - theme: theme.clone(), - lang, - action: FormAction::rendered(&key), - } - .into_response() - .no_store()); - } - Err(err) => return Err(err.into()), + let form = form.ok().map(|Form(form)| form); + let action = FormAction::rendered(&key); + let Unlocked { + data, + is_available, + encrypted, + no_password, + } = match unlock(&db, &page, theme.as_ref(), lang, &key, form, action).await? { + Unlock::Paste(unlocked) => unlocked, + Unlock::Prompt(response) => return Ok(response), }; let Data { text, metadata } = data; @@ -128,12 +98,13 @@ pub async fn get( can_delete, is_available, is_markdown: true, + is_html: false, expiration, html, title, }; - let response = rendered.into_response(); + let response = (Csp::Rendered, rendered).into_response(); Ok(if encrypted { response.no_store() } else { diff --git a/crates/wastebin_server/src/i18n.rs b/crates/wastebin_server/src/i18n.rs index e98f77e1..ad8a2814 100644 --- a/crates/wastebin_server/src/i18n.rs +++ b/crates/wastebin_server/src/i18n.rs @@ -207,7 +207,7 @@ static DE: phf::Map<&'static str, &'static str> = phf_map! { "paste.help.download" => "Herunterladen", "paste.help.show_qr" => "QR-Code anzeigen", "paste.help.toggle_wrap" => "Zeilenumbruch umschalten", - "paste.help.toggle_rendered" => "Markdown Ansicht umschalten", + "paste.help.toggle_rendered" => "Gerenderte Ansicht umschalten", "paste.help.toggle_help" => "Hilfe umschalten", "password.show" => "Passwort anzeigen", diff --git a/crates/wastebin_server/src/main.rs b/crates/wastebin_server/src/main.rs index 08613c31..ec825f40 100644 --- a/crates/wastebin_server/src/main.rs +++ b/crates/wastebin_server/src/main.rs @@ -1,5 +1,6 @@ mod assets; mod cache; +mod csp; mod env; mod errors; mod handlers; @@ -31,6 +32,7 @@ use tower_http::trace::TraceLayer; use crate::assets::Asset; use crate::cache::Cache; +use crate::csp::Csp; use crate::errors::Error; use crate::handlers::extract::Theme; use crate::handlers::{delete, download, html, insert, raw, robots, theme}; @@ -82,24 +84,17 @@ impl FromRef for Cache { } } -async fn security_headers_layer(req: Request, next: Next) -> impl IntoResponse { - // Rendered Markdown may embed remote images via `![](…)`; relax img-src for that route only. - const CSP_STRICT: HeaderValue = HeaderValue::from_static( - "default-src 'none'; script-src 'self'; img-src 'self' data: ; style-src 'self' data: ; font-src 'self' data: ; object-src 'none' ; base-uri 'none' ; frame-ancestors 'none' ; form-action 'self' ;", - ); - const CSP_RENDERED: HeaderValue = HeaderValue::from_static( - "default-src 'none'; script-src 'self'; img-src * data: ; style-src 'self' data: ; font-src 'self' data: ; object-src 'none' ; base-uri 'none' ; frame-ancestors 'none' ; form-action 'self' ;", - ); - - let csp = if req.uri().path().starts_with("/md/") { - CSP_RENDERED - } else { - CSP_STRICT - }; +async fn security_headers_layer(req: Request, next: Next) -> Response { + let mut response = next.run(req).await; + let csp = response + .extensions_mut() + .remove::() + .unwrap_or(Csp::Strict); + let headers = response.headers_mut(); + headers.insert(CONTENT_SECURITY_POLICY, csp.header()); - let headers: [(HeaderName, HeaderValue); 7] = [ + let defaults: [(HeaderName, HeaderValue); 6] = [ (SERVER, HeaderValue::from_static(env!("CARGO_PKG_NAME"))), - (CONTENT_SECURITY_POLICY, csp), (REFERRER_POLICY, HeaderValue::from_static("same-origin")), (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")), (X_FRAME_OPTIONS, HeaderValue::from_static("SAMEORIGIN")), @@ -110,7 +105,11 @@ async fn security_headers_layer(req: Request, next: Next) -> impl IntoResponse { (X_XSS_PROTECTION, HeaderValue::from_static("1; mode=block")), ]; - (headers, next.run(req).await) + for (name, value) in defaults { + headers.insert(name, value); + } + + response } async fn handle_service_errors( @@ -207,6 +206,10 @@ fn make_app(state: AppState, timeout: Duration, max_body_size: usize) -> Router "/md/{id}", get(html::rendered::get).post(html::rendered::get), ) + .route( + "/html/{id}", + get(html::document::get).post(html::document::get), + ) .route("/burn/{id}", get(html::burn::get)) .route( "/{id}", @@ -248,6 +251,7 @@ async fn start() -> Result<(), Box> { let expirations = env::expiration_set()?; let theme = env::theme()?; let title = env::title(); + let render_html = env::render_html()?; let cache = Cache::new(cache_size)?; let (db, db_handler) = Database::new(method)?; @@ -257,12 +261,17 @@ async fn start() -> Result<(), Box> { tracing::debug!("restricting maximum body size to {max_body_size} bytes"); tracing::debug!("enforcing a http timeout of {timeout:#?}"); + if render_html { + tracing::debug!("serving pastes as sandboxed pages at /html/{{id}}"); + } + let page = Arc::new(page::Page::new( title, base_url, theme, expirations, max_body_size, + render_html, )); let highlighter = Arc::new(wastebin_highlight::Highlighter::default()); let state = AppState { diff --git a/crates/wastebin_server/src/page.rs b/crates/wastebin_server/src/page.rs index 4722efc8..eb9f222a 100644 --- a/crates/wastebin_server/src/page.rs +++ b/crates/wastebin_server/src/page.rs @@ -21,6 +21,7 @@ pub(crate) struct Page { pub base_url: Url, pub expirations: Vec, pub max_body_size: usize, + pub render_html: bool, } impl Page { @@ -32,6 +33,7 @@ impl Page { theme: Theme, expirations: ExpirationSet, max_body_size: usize, + render_html: bool, ) -> Self { let assets = Assets::new(theme); let expirations = expirations.into_inner(); @@ -43,6 +45,7 @@ impl Page { base_url, expirations, max_body_size, + render_html, } } } diff --git a/crates/wastebin_server/src/test_helpers.rs b/crates/wastebin_server/src/test_helpers.rs index 5fd60ab2..a5529b32 100644 --- a/crates/wastebin_server/src/test_helpers.rs +++ b/crates/wastebin_server/src/test_helpers.rs @@ -22,8 +22,15 @@ pub(crate) struct Client { /// Determine if the client should store cookies. pub(crate) struct StoreCookies(pub bool); +/// Determine if the server renders HTML pastes as pages. +pub(crate) struct RenderHtml(pub bool); + impl Client { pub(crate) async fn new(store_cookies: StoreCookies) -> Self { + Self::with_html(store_cookies, RenderHtml(false)).await + } + + pub(crate) async fn with_html(store_cookies: StoreCookies, render_html: RenderHtml) -> Self { let (db, handler) = Database::new(db::Open::Memory).expect("open memory database"); let cache = Cache::new(NonZeroUsize::new(128).unwrap()).unwrap(); let key = Key::generate(); @@ -34,6 +41,7 @@ impl Client { Theme::Ayu, expirations, 1024 * 1024, + render_html.0, )); let state = crate::AppState { db, diff --git a/crates/wastebin_server/templates/formatted.html b/crates/wastebin_server/templates/formatted.html index 6c8a6f76..61b76da7 100644 --- a/crates/wastebin_server/templates/formatted.html +++ b/crates/wastebin_server/templates/formatted.html @@ -5,6 +5,10 @@ + {% else if is_html %} + + + {% endif %} {% endblock %} diff --git a/crates/wastebin_server/templates/paste.html b/crates/wastebin_server/templates/paste.html index c9420898..63c2a8dd 100644 --- a/crates/wastebin_server/templates/paste.html +++ b/crates/wastebin_server/templates/paste.html @@ -55,7 +55,7 @@ d{{ lang.t("paste.help.download") }} q{{ lang.t("paste.help.show_qr") }} w{{ lang.t("paste.help.toggle_wrap") }} - {% if is_markdown %} + {% if is_markdown || is_html %} m{{ lang.t("paste.help.toggle_rendered") }} {% endif %} ?{{ lang.t("paste.help.toggle_help") }} diff --git a/crates/wastebin_server/templates/qr.html b/crates/wastebin_server/templates/qr.html index 81e1d09d..667da04e 100644 --- a/crates/wastebin_server/templates/qr.html +++ b/crates/wastebin_server/templates/qr.html @@ -11,6 +11,10 @@ + {% else if is_html %} + + + {% endif %} {% endblock %} From f04d0604a6a6f779d18852982540e219b81ebcbf Mon Sep 17 00:00:00 2001 From: Anoop Sundaresh <16442416+theryecatcher@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:55:43 -0500 Subject: [PATCH 2/2] Document the m key for HTML pastes The m key clicks the view toggle, which HTML pastes now have too, so it opens their sandboxed page. No wastebin script runs on that page, so m cannot toggle back. --- CHANGELOG.md | 5 +++++ README.md | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d149d820..b50288d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,11 @@ wastebin cookies. It is off by default; set `WASTEBIN_RENDER_UNTRUSTED_HTML=true` to turn it on. +### Changed + +- m opens HTML pastes as a page, in addition to toggling the rendered + view on Markdown pastes. + ### Fixed - Reject off-origin and scheme-relative `Referer` values when redirecting back diff --git a/README.md b/README.md index 8afc374e..0fca3185 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,8 @@ When viewing a paste, you can use * q to display the current URL as a QR code, * p to view the formatted paste, * w to toggle line wrapping on and off (off by default), -* m to toggle the rendered view on Markdown pastes and +* m to toggle the rendered view on Markdown pastes or open HTML + pastes as a page and * ? to view the list of keybindings. To paste some text you can also use the ctrl+s key