//! Off-site links go through `/out`: a page that says where you're going
//! before you go ("You are leaving recourse @ host to go to: …").
//!
//! **When.** Links are rewritten when a post is *shown* ([`display`]), not
//! when it's written: the stored `cooked` HTML stays independent of the host
//! name and `LINK_SECRET`, so posts written before this existed, a move to
//! another host and a rotated secret all just work, with no recook pass. The
//! cost is one more sanitizer pass per post shown (html5ever over a few KB),
//! which a topic page of 50 posts doesn't notice.
//!
//! **What.** `http(s)` links whose host isn't this site's (`PUBLIC_URL`)
//! become `/out?u=<url>&s=<sig>`; relative and same-host links stay direct;
//! other schemes were already removed by the sanitizer. Every link gets
//! `rel="nofollow ugc noopener noreferrer"`.
//!
//! **Signature.** `s` is HMAC-SHA256 of the URL under `LINK_SECRET`, so
//! `/out` can't be used as an open redirect: an unsigned or altered link
//! shows its destination as plain text, with a warning and no Continue.
//!
//! Off-site *images* are left alone (they load directly). A caching image
//! proxy would hide readers' addresses from those hosts; not built.
use std::borrow::Cow;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use url::Url;
use crate::markdown::{footnote_ids_only, sanitizer};
/// Signs and checks `/out` destinations.
#[derive(Clone)]
pub struct Signer {
key: Vec<u8>,
}
impl Signer {
pub fn new(secret: &str) -> Self {
Self { key: secret.as_bytes().to_vec() }
}
fn mac(&self) -> Hmac<Sha256> {
Hmac::<Sha256>::new_from_slice(&self.key).expect("HMAC takes any key length")
}
/// 128 bits of the MAC, hex.
pub fn sign(&self, url: &str) -> String {
let mut m = self.mac();
m.update(b"out:");
m.update(url.as_bytes());
m.finalize().into_bytes()[..16].iter().map(|b| format!("{b:02x}")).collect()
}
/// Constant-time.
pub fn verify(&self, url: &str, sig: &str) -> bool {
let Some(bytes) = unhex(sig) else { return false };
if bytes.len() != 16 {
return false;
}
let mut m = self.mac();
m.update(b"out:");
m.update(url.as_bytes());
m.verify_truncated_left(&bytes).is_ok()
}
}
fn unhex(s: &str) -> Option<Vec<u8>> {
if !s.len().is_multiple_of(2) {
return None;
}
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
}
/// What `display` needs: this site's host, its origin (for absolute links)
/// and the signer.
#[derive(Clone)]
pub struct Links {
host: String,
origin: String,
signer: Signer,
}
impl Links {
pub fn new(public_url: &str, secret: &str) -> Self {
let parsed = Url::parse(public_url).ok();
let host = parsed.as_ref().and_then(|u| u.host_str()).unwrap_or("localhost").to_ascii_lowercase();
Self { host, origin: public_url.trim_end_matches('/').to_string(), signer: Signer::new(secret) }
}
pub fn from_config(c: &crate::Config) -> Self {
Self::new(&c.public_url, &c.link_secret)
}
pub fn host(&self) -> &str {
&self.host
}
pub fn signer(&self) -> &Signer {
&self.signer
}
/// Whether `href` leaves the site: absolute http(s) to another host.
pub fn is_external(&self, href: &str) -> bool {
match Url::parse(href) {
Ok(u) if matches!(u.scheme(), "http" | "https") => {
u.host_str().is_some_and(|h| !h.eq_ignore_ascii_case(&self.host))
}
_ => false,
}
}
/// The `/out` link for `href` (`absolute`: with this site's origin, for
/// the API).
pub fn out_link(&self, href: &str, absolute: bool) -> String {
let q = form_urlencoded(href);
let base = if absolute { self.origin.as_str() } else { "" };
format!("{base}/out?u={q}&s={}", self.signer.sign(href))
}
/// Post HTML as shown: external links through `/out`, every link `rel`'d.
pub fn display(&self, cooked: &str, absolute: bool) -> String {
if !cooked.contains("<a ") {
return cooked.to_string();
}
let me = self.clone();
sanitizer()
.link_rel(Some("nofollow ugc noopener noreferrer"))
.attribute_filter(move |element, attribute, value| {
if element == "a" && attribute == "href" && me.is_external(value) {
return Some(Cow::Owned(me.out_link(value, absolute)));
}
footnote_ids_only(element, attribute, value)
})
.clean(cooked)
.to_string()
}
}
impl Links {
/// The web's relative `/out` links made absolute (the API's posts are
/// shown outside this origin).
pub fn absolutize(&self, html: &str) -> String {
html.replace(r#"href="/out?"#, &format!(r#"href="{}/out?"#, self.origin))
}
}
fn form_urlencoded(s: &str) -> String {
url::form_urlencoded::byte_serialize(s.as_bytes()).collect()
}
/// A destination as `/out` shows it.
#[derive(Debug, serde::Serialize)]
pub struct Destination {
/// The URL, normalized (punycode host).
pub url: String,
/// Split around the host, to emphasise it: `before` `host` `after`.
pub before: String,
pub host: String,
pub after: String,
/// The host in Unicode when it's an IDN (`xn--` in `host`), else None.
pub host_unicode: Option<String>,
/// Userinfo (`https://bank.example@evil.example/`): worth a warning.
pub has_userinfo: bool,
}
/// Parse an `/out` target: http(s) only.
pub fn destination(raw: &str) -> Option<Destination> {
let u = Url::parse(raw.trim()).ok()?;
if !matches!(u.scheme(), "http" | "https") {
return None;
}
let host = u.host_str()?.to_string();
let url = u.to_string();
let at = url.find(&host)?;
let (unicode, _) = idna::domain_to_unicode(&host);
Some(Destination {
before: url[..at].to_string(),
after: url[at + host.len()..].to_string(),
host_unicode: (unicode != host).then_some(unicode),
has_userinfo: !u.username().is_empty() || u.password().is_some(),
host,
url,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn links() -> Links {
Links::new("https://forum.example.org", "test-secret")
}
#[test]
fn external_links_go_through_out_and_others_stay_direct() {
let l = links();
let cooked = crate::markdown::render(
"[ext](https://other.example/a?b=1&c=2) [same](https://forum.example.org/t/1) [rel](/t/2) [frag](#x) https://bare.example",
);
let shown = l.display(&cooked, false);
let sig = l.signer().sign("https://other.example/a?b=1&c=2");
assert!(shown.contains(&format!(r#"href="/out?u=https%3A%2F%2Fother.example%2Fa%3Fb%3D1%26c%3D2&s={sig}""#)), "{shown}");
assert!(shown.contains(r#"href="https://forum.example.org/t/1""#));
assert!(shown.contains(r#"href="/t/2""#));
assert!(shown.contains(r##"href="#x""##));
assert!(shown.contains("/out?u=https%3A%2F%2Fbare.example"), "bare URLs too");
assert_eq!(shown.matches(r#"rel="nofollow ugc noopener noreferrer""#).count(), 5);
// The API's are absolute.
let api = l.display(&cooked, true);
assert!(api.contains(r#"href="https://forum.example.org/out?u=https%3A%2F%2Fother.example"#), "{api}");
// Host match is case-insensitive; other schemes never make it here.
assert!(!l.is_external("HTTPS://FORUM.EXAMPLE.ORG/x"));
assert!(!l.is_external("mailto:a@b.example"));
assert!(!l.is_external("javascript:alert(1)"));
assert!(l.is_external("http://forum.example.org.evil.example/"));
}
#[test]
fn signatures_check_out_and_tampering_does_not() {
let s = Signer::new("k");
let sig = s.sign("https://a.example/");
assert_eq!(sig.len(), 32);
assert!(s.verify("https://a.example/", &sig));
assert!(!s.verify("https://a.example/x", &sig), "another URL");
assert!(!s.verify("https://a.example/", &sig[..30]), "truncated");
assert!(!s.verify("https://a.example/", "zz"));
assert!(!Signer::new("other").verify("https://a.example/", &sig), "another secret");
}
#[test]
fn destinations_show_their_host_in_both_forms() {
let d = destination("https://bücher.example/path?q=1").unwrap();
assert_eq!(d.host, "xn--bcher-kva.example");
assert_eq!(d.host_unicode.as_deref(), Some("bücher.example"));
assert_eq!((d.before.as_str(), d.after.as_str()), ("https://", "/path?q=1"));
let d = destination("http://plain.example").unwrap();
assert!(d.host_unicode.is_none());
assert!(destination("https://bank.example@evil.example/").unwrap().has_userinfo);
assert_eq!(destination("https://bank.example@evil.example/").unwrap().host, "evil.example");
assert!(destination("javascript:alert(1)").is_none());
assert!(destination("not a url").is_none());
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions success · Badges · Packages
⭐
Log in to mark this repository.
8.9 KiB · text
History
263b40b