Repository navigation
Allow rendering HTML pastes as sandboxed pages #236
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -168,7 +169,7 @@ When viewing a paste, you can use | |
| * <kbd>q</kbd> to display the current URL as a QR code, | ||
| * <kbd>p</kbd> to view the formatted paste, | ||
| * <kbd>w</kbd> to toggle line wrapping on and off (off by default), | ||
| * <kbd>m</kbd> to toggle the rendered view on Markdown pastes and | ||
| * <kbd>m</kbd> to toggle the rendered view on Markdown and HTML pastes and | ||
| * <kbd>?</kbd> to view the list of keybindings. | ||
|
|
||
| To paste some text you can also use the <kbd>ctrl</kbd>+<kbd>s</kbd> key | ||
|
|
@@ -191,6 +192,29 @@ embedded via ``, 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`, pastes | ||
| created with an `html` or `htm` extension can be viewed as a page of their own | ||
| at `/html/{id}`, reached through the same toggle as rendered Markdown. It is | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think the premise that it's based on file extension is a bit flawed because |
||
| 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 and it cannot read wastebin cookies or act on behalf of the viewer. | ||
| Scripts, form submissions and top-level navigation are blocked. 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 if you control the proxy sitting in front of this for selectively admitting | ||
| visits to this subdomain. | ||
|
|
||
| ### Configuration | ||
|
|
||
| The following environment variables can be set to configure the server and | ||
|
|
@@ -201,6 +225,7 @@ run-time behavior: | |
| | `WASTEBIN_ADDRESS_PORT` | Address and port to bind the server to. | `0.0.0.0:8088` | | ||
| | `WASTEBIN_BASE_URL` | Base URL for the QR code display. | | | ||
| | `WASTEBIN_CACHE_SIZE` | Number of rendered items to cache. | `128` | | ||
| | `WASTEBIN_RENDER_UNTRUSTED_HTML` | Set to `true` to show `html` and `htm` pastes as sandboxed pages at `/html/{id}`. See [HTML pages](#html-pages) before enabling. | `false` | | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This breaks order, please move it down. |
||
| | `WASTEBIN_DATABASE_PATH` | Path to the sqlite3 database file. | `:memory:` | | ||
| | `WASTEBIN_HTTP_TIMEOUT` | Maximum number of seconds a request is processed until wastebin responds with 408. | `5` | | ||
| | `WASTEBIN_MAX_BODY_SIZE` | Number of bytes to accept for POST requests. | `1048576`, i.e. 1 MB | | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<NonZeroUsize, Error> { | |
| .map_err(Error::CacheSize) | ||
| } | ||
|
|
||
| pub fn render_html() -> Result<bool, Error> { | ||
| 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" | "1" => Ok(true), | ||
| "false" | "0" => Ok(false), | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You only document |
||
| _ => Err(Error::RenderHtml), | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| pub fn database_method() -> Result<db::Open, Error> { | ||
| match std::env::var(vars::DATABASE_PATH) { | ||
| Ok(path) => Ok(db::Open::Path(PathBuf::from(path))), | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,253 @@ | ||
| use axum::extract::{Form, Path, State}; | ||
| use axum::http::{HeaderValue, header}; | ||
| use axum::response::{IntoResponse, Response}; | ||
|
|
||
| use crate::cache::Key; | ||
| 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; | ||
|
|
||
| const CSP_SANDBOX: HeaderValue = 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' ;", | ||
| ); | ||
|
|
||
| pub async fn get<E>( | ||
| State(page): State<Page>, | ||
| State(db): State<Database>, | ||
| Path(id): Path<String>, | ||
| theme: Option<Theme>, | ||
| lang: Lang, | ||
| form: Result<Form<PasteForm>, E>, | ||
| ) -> Result<Response, ErrorResponse> { | ||
| 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 = ( | ||
| [ | ||
| ( | ||
| header::CONTENT_TYPE, | ||
| HeaderValue::from_static("text/html; charset=utf-8"), | ||
| ), | ||
| (header::CONTENT_SECURITY_POLICY, CSP_SANDBOX), | ||
| ], | ||
| 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 = "<!doctype html><title>Spec</title><style>h1{color:teal}</style><h1>Hello</h1><svg viewBox=\"0 0 1 1\"><rect width=\"1\" height=\"1\"/></svg>"; | ||
|
|
||
| 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<String, Box<dyn std::error::Error>> { | ||
| 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<dyn std::error::Error>> { | ||
| 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<dyn std::error::Error>> { | ||
| 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("<h1>Hello</h1>"), "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<dyn std::error::Error>> { | ||
| 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<dyn std::error::Error>> { | ||
| 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<dyn std::error::Error>> { | ||
| 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<dyn std::error::Error>> { | ||
| 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("<h1>Hello</h1>")); | ||
|
|
||
| let body = client.get(&location).send().await?.text().await?; | ||
| assert!(!body.contains("href=\"/html/"), "body: {body}"); | ||
|
|
||
| Ok(()) | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please make that its own commit and CHANGELOG entry.