25.6 KiB · text History 263b40b
//! Rich links on posts: staff attach up to [`MAX_LINKS`] URLs to any post,
//! each shown under it as a card built from what the page says about itself
//! (party-slut's links on a part of an event, ported).
//!
//! **Never at render time, never in the request.** A background task fetches
//! the page once ([`Previewer`]) and stores title, description, site name and
//! the picture here. A page view only reads our own rows: it never waits on
//! somebody else's server, and never tells that server who is reading. The
//! adding request doesn't fetch either, so a slow site can't hold it open.
//!
//! **The fence.** The fetch goes through [`crate::fetch`]: http(s) only,
//! public addresses only (after DNS, and on every redirect hop, connecting to
//! the addresses checked), size caps and timeouts.
//!
//! **Concurrency.** At most two fetches run at once (a process-wide
//! semaphore). recourse has no queue: a row is `pending` until its fetch
//! finishes, and [`Previewer::sweep`] at startup picks up any a restart
//! interrupted.
//!
//! **Pictures** are copied into Postgres like avatars (never hotlinked),
//! under the avatar rules: PNG, JPEG, GIF or WebP, decided from the bytes
//! (not the remote server's Content-Type), at most the avatar size cap. No
//! SVG: it is a document, not a picture.
//!
//! **Visibility.** Cards follow their post: none on a deleted, hidden or
//! held post, on the page or in the API, and the picture route answers 404
//! for them.
use std::collections::HashMap;
use std::sync::Arc;

use chrono::Utc;
use sea_orm::sea_query::Expr;
use sea_orm::*;
use serde::Serialize;
use tokio::sync::Semaphore;
use tracing::{info, warn};
use url::Url;
use uuid::Uuid;

use crate::actions::{ActionError, ActionResult};
use crate::entities::{post_links, posts};
use crate::fetch::{self, Limit};
use crate::moderation::{self, Actor};
use crate::AppState;

/// Most links one post may carry: a row of cards, not a bookmark list.
pub const MAX_LINKS: usize = 5;
/// Most of a page we read looking for its `<head>` (cut there, not refused).
const MAX_PAGE_BYTES: usize = 1024 * 1024;
/// Fetches at once, across the process.
const CONCURRENCY: usize = 2;

static PERMITS: Semaphore = Semaphore::const_new(CONCURRENCY);

pub const PENDING: &str = "pending";
pub const OK: &str = "ok";
pub const FAILED: &str = "failed";

/// Normalise what staff typed into something fetchable: a bare
/// `example.com/x` becomes `https://example.com/x`; anything but http(s)
/// (`javascript:`, `data:`, `file:`) is refused, as is a URL carrying a
/// user name or password.
pub fn normalize_url(input: &str) -> Option<String> {
    let trimmed = input.trim();
    if trimmed.is_empty() || trimmed.len() > 2000 || trimmed.chars().any(char::is_whitespace) {
        return None;
    }
    let candidate = if trimmed.contains("://") {
        trimmed.to_string()
    } else if trimmed.contains(':') && !looks_like_host_port(trimmed) {
        // `javascript:…`, `mailto:…`: a scheme, not a bare domain.
        return None;
    } else {
        format!("https://{trimmed}")
    };
    let url = Url::parse(&candidate).ok()?;
    if !matches!(url.scheme(), "http" | "https") {
        return None;
    }
    if url.host_str().is_none_or(str::is_empty) || !url.username().is_empty() || url.password().is_some() {
        return None;
    }
    let s = url.to_string();
    (s.len() <= 2048).then_some(s)
}

/// `example.com:8080/x`: a host and port, not a scheme.
fn looks_like_host_port(s: &str) -> bool {
    let (host, rest) = s.split_once(':').unwrap_or((s, ""));
    host.contains('.') && rest.chars().take_while(|c| *c != '/').all(|c| c.is_ascii_digit())
}

/// The host a card names when it has nothing better.
pub fn host_of(url: &str) -> String {
    Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(|h| h.trim_start_matches("www.").to_string()))
        .unwrap_or_else(|| url.to_string())
}

/// What a page said about itself.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct PageMetadata {
    pub title: Option<String>,
    pub description: Option<String>,
    pub site_name: Option<String>,
    pub image_url: Option<String>,
}

/// Pull the card fields out of a page: OpenGraph, then Twitter's tags, then
/// the ordinary ones (`<title>`, `meta description`). `base_url` is the URL
/// that answered, so a relative `og:image` resolves against the right place.
/// A real HTML parser, not patterns: a `>` in an attribute and tags inside
/// comments both defeat matching.
pub fn extract_metadata(html: &str, base_url: &str) -> PageMetadata {
    use scraper::{Html, Selector};

    let document = Html::parse_document(html);
    let meta = Selector::parse("meta").expect("static selector");

    let mut og: HashMap<String, String> = HashMap::new();
    let mut named: HashMap<String, String> = HashMap::new();
    for element in document.select(&meta) {
        let value = element.value();
        let content = match value.attr("content") {
            Some(c) if !c.trim().is_empty() => c.trim(),
            _ => continue,
        };
        // OpenGraph uses `property`, the older tags `name`; pages mix them.
        if let Some(property) = value.attr("property") {
            og.entry(property.trim().to_ascii_lowercase()).or_insert_with(|| content.to_string());
        }
        if let Some(name) = value.attr("name") {
            named.entry(name.trim().to_ascii_lowercase()).or_insert_with(|| content.to_string());
        }
    }

    let title_tag = Selector::parse("title").expect("static selector");
    let document_title = document
        .select(&title_tag)
        .next()
        .map(|e| e.text().collect::<String>().trim().to_string())
        .filter(|t| !t.is_empty());

    let pick = |keys: &[&str]| -> Option<String> {
        keys.iter().find_map(|k| og.get(*k).or_else(|| named.get(*k)).cloned())
    };

    let image_url = pick(&["og:image:secure_url", "og:image", "og:image:url", "twitter:image", "twitter:image:src"])
        .and_then(|raw| Url::parse(base_url).ok()?.join(&raw).ok())
        .filter(|u| matches!(u.scheme(), "http" | "https"))
        .map(|u| u.to_string());

    PageMetadata {
        title: pick(&["og:title", "twitter:title"]).or(document_title).map(|t| truncate(&t, 300)),
        description: pick(&["og:description", "twitter:description", "description"]).map(|d| truncate(&d, 600)),
        site_name: pick(&["og:site_name", "application-name"]).map(|s| truncate(&s, 200)),
        image_url,
    }
    .nonblank()
}

impl PageMetadata {
    fn nonblank(mut self) -> Self {
        for f in [&mut self.title, &mut self.description, &mut self.site_name] {
            if f.as_deref().is_some_and(str::is_empty) {
                *f = None;
            }
        }
        self
    }
}

/// Collapse whitespace and cut to `limit` characters (never mid-character).
fn truncate(value: &str, limit: usize) -> String {
    let value = value.split_whitespace().collect::<Vec<_>>().join(" ");
    if value.chars().count() <= limit {
        return value;
    }
    let mut cut: String = value.chars().take(limit - 1).collect();
    cut = cut.trim_end().to_string();
    cut.push('…');
    cut
}

/// The picture formats a card keeps (the avatar list), from the bytes.
pub fn sniff_image(bytes: &[u8]) -> Option<&'static str> {
    let t = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
        "image/png"
    } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
        "image/jpeg"
    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
        "image/gif"
    } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
        "image/webp"
    } else {
        return None;
    };
    crate::actions::AVATAR_TYPES.contains(&t).then_some(t)
}

// ---------------------------------------------------------------- staff

fn invalid_url() -> ActionError {
    ActionError::Invalid("That doesn't look like a web address (http or https).".into())
}

async fn live_post(state: &AppState, id: Uuid) -> ActionResult<posts::Model> {
    let post = posts::Entity::find_by_id(id).one(state.db.as_ref()).await?.ok_or(ActionError::NotFound)?;
    if post.deleted_at.is_some() {
        return Err(ActionError::NotFound);
    }
    Ok(post)
}

/// The links on a post, in order.
pub async fn list(db: &DatabaseConnection, post_id: Uuid) -> Result<Vec<post_links::Model>, DbErr> {
    post_links::Entity::find()
        .filter(post_links::Column::PostId.eq(post_id))
        .order_by_asc(post_links::Column::Position)
        .order_by_asc(post_links::Column::CreatedAt)
        .all(db)
        .await
}

/// Attach a link to a post (staff). Queued for a fetch; the card shows the
/// link as pending until it's done.
pub async fn attach(state: &AppState, actor: Actor<'_>, post_id: Uuid, raw: &str) -> ActionResult<post_links::Model> {
    actor.require_staff()?;
    let post = live_post(state, post_id).await?;
    let url = normalize_url(raw).ok_or_else(invalid_url)?;

    // Lock the post row so two staff adding at once can't pass the limit.
    let txn = state.db.begin().await?;
    posts::Entity::find_by_id(post.id).lock_exclusive().one(&txn).await?;
    let existing = post_links::Entity::find().filter(post_links::Column::PostId.eq(post.id)).all(&txn).await?;
    if existing.iter().any(|l| l.url == url) {
        return Err(ActionError::Conflict { code: "duplicate_link", message: "That link is already on this post.".into() });
    }
    if existing.len() >= MAX_LINKS {
        return Err(ActionError::Conflict {
            code: "too_many_links",
            message: format!("A post can carry at most {MAX_LINKS} links."),
        });
    }
    let now = Utc::now();
    let link = post_links::ActiveModel {
        id: Set(Uuid::now_v7()),
        post_id: Set(post.id),
        url: Set(url.clone()),
        position: Set(existing.iter().map(|l| l.position + 1).max().unwrap_or(0)),
        status: Set(PENDING.into()),
        title: Set(None),
        description: Set(None),
        site_name: Set(None),
        image_data: Set(None),
        image_content_type: Set(None),
        fetched_at: Set(None),
        created_by_id: Set(actor.id()),
        created_at: Set(now.into()),
        updated_at: Set(now.into()),
    }
    .insert(&txn)
    .await?;
    txn.commit().await?;

    let label = moderation::post_label(state.db.as_ref(), &post).await;
    moderation::log(state.db.as_ref(), actor, "attach_link", "post", Some(post.id), &label, Some(&url)).await;
    Previewer::of(state).spawn(link.id);
    Ok(link)
}

async fn load_link(state: &AppState, id: Uuid) -> ActionResult<post_links::Model> {
    post_links::Entity::find_by_id(id)
        .select_only()
        .columns(card_columns())
        .column_as(Expr::value(Option::<Vec<u8>>::None), "image_data")
        .into_model::<post_links::Model>()
        .one(state.db.as_ref())
        .await?
        .ok_or(ActionError::NotFound)
}

/// Take a link off its post (staff).
pub async fn remove(state: &AppState, actor: Actor<'_>, link_id: Uuid) -> ActionResult<post_links::Model> {
    actor.require_staff()?;
    let link = load_link(state, link_id).await?;
    let post = posts::Entity::find_by_id(link.post_id).one(state.db.as_ref()).await?.ok_or(ActionError::NotFound)?;
    post_links::Entity::delete_by_id(link.id).exec(state.db.as_ref()).await?;
    let label = moderation::post_label(state.db.as_ref(), &post).await;
    moderation::log(state.db.as_ref(), actor, "remove_link", "post", Some(post.id), &label, Some(&link.url)).await;
    Ok(link)
}

/// Fetch a link's page again (staff): back to pending, queued.
pub async fn refetch(state: &AppState, actor: Actor<'_>, link_id: Uuid) -> ActionResult<post_links::Model> {
    actor.require_staff()?;
    let link = load_link(state, link_id).await?;
    live_post(state, link.post_id).await?;
    post_links::Entity::update_many()
        .col_expr(post_links::Column::Status, Expr::value(PENDING))
        .col_expr(post_links::Column::UpdatedAt, Expr::value(chrono::DateTime::<chrono::FixedOffset>::from(Utc::now())))
        .filter(post_links::Column::Id.eq(link.id))
        .exec(state.db.as_ref())
        .await?;
    Previewer::of(state).spawn(link.id);
    Ok(post_links::Model { status: PENDING.into(), ..link })
}

// ---------------------------------------------------------------- fetching

/// Runs the fetches: at most [`CONCURRENCY`] at once, process-wide.
#[derive(Clone)]
pub struct Previewer {
    db: Arc<DatabaseConnection>,
    user_agent: Arc<str>,
}

impl Previewer {
    pub fn new(db: Arc<DatabaseConnection>, public_url: &str) -> Self {
        Self { db, user_agent: fetch::user_agent(public_url).into() }
    }

    pub fn of(state: &AppState) -> Self {
        Self::new(state.db.clone(), &state.config.public_url)
    }

    /// Fetch `link_id` in the background.
    pub fn spawn(&self, link_id: Uuid) -> tokio::task::JoinHandle<()> {
        let me = self.clone();
        tokio::spawn(async move {
            if let Err(e) = me.fetch(link_id).await {
                warn!(error = %e, %link_id, "link preview: could not record the result");
            }
        })
    }

    /// Every link still `pending` (a restart interrupted it, or it was never
    /// picked up), fetched now; waits for them all. Returns how many.
    pub async fn sweep(&self) -> Result<usize, DbErr> {
        let ids: Vec<Uuid> = post_links::Entity::find()
            .select_only()
            .column(post_links::Column::Id)
            .filter(post_links::Column::Status.eq(PENDING))
            .order_by_asc(post_links::Column::CreatedAt)
            .into_tuple()
            .all(self.db.as_ref())
            .await?;
        let n = ids.len();
        let handles: Vec<_> = ids.into_iter().map(|id| self.spawn(id)).collect();
        for h in handles {
            let _ = h.await;
        }
        Ok(n)
    }

    /// [`Self::sweep`] in the background, for startup.
    pub fn spawn_sweep(self) {
        tokio::spawn(async move {
            match self.sweep().await {
                Ok(0) => {}
                Ok(n) => info!("link previews: fetched {n} pending link(s) left from before the restart"),
                Err(e) => warn!(error = %e, "link previews: startup sweep failed"),
            }
        });
    }

    /// Fetch one link's page and picture and record what came back. A page
    /// that won't load, or has nothing to say, is an answer about the link
    /// (`failed`), not an error.
    pub async fn fetch(&self, link_id: Uuid) -> Result<(), DbErr> {
        let _permit = PERMITS.acquire().await.expect("never closed");
        let Some(url): Option<String> = post_links::Entity::find_by_id(link_id)
            .select_only()
            .column(post_links::Column::Url)
            .into_tuple()
            .one(self.db.as_ref())
            .await?
        else {
            return Ok(()); // removed meanwhile
        };

        let page = match fetch::fetch(&url, Limit { bytes: MAX_PAGE_BYTES, truncate: true }, &self.user_agent).await {
            Ok(p) => p,
            Err(e) => {
                info!(%url, error = %e, "link preview: page not fetched");
                return record(self.db.as_ref(), link_id, None, None).await;
            }
        };
        // Lossy: a page in an encoding we can't read usually still has ASCII
        // meta tags.
        let html = String::from_utf8_lossy(&page.body);
        let meta = extract_metadata(&html, page.final_url.as_str());
        let image = match meta.image_url.as_deref() {
            Some(u) => self.copy_image(u).await,
            None => None,
        };
        record(self.db.as_ref(), link_id, Some(meta), image).await
    }

    /// The card picture, as stored bytes, or none (a card is fine as text).
    async fn copy_image(&self, url: &str) -> Option<(Vec<u8>, &'static str)> {
        let limit = Limit { bytes: crate::actions::MAX_AVATAR_BYTES, truncate: false };
        let got = match fetch::fetch(url, limit, &self.user_agent).await {
            Ok(g) => g,
            Err(e) => {
                info!(%url, error = %e, "link preview: no picture");
                return None;
            }
        };
        match sniff_image(&got.body) {
            Some(t) => Some((got.body, t)),
            None => {
                info!(%url, "link preview: picture isn't PNG, JPEG, GIF or WebP");
                None
            }
        }
    }
}

/// Store a fetch's result: `ok` with what was found, or `failed`.
pub async fn record(
    db: &DatabaseConnection,
    link_id: Uuid,
    meta: Option<PageMetadata>,
    image: Option<(Vec<u8>, &'static str)>,
) -> Result<(), DbErr> {
    let now: chrono::DateTime<chrono::FixedOffset> = Utc::now().into();
    let mut am = post_links::ActiveModel {
        id: Unchanged(link_id),
        fetched_at: Set(Some(now)),
        updated_at: Set(now),
        ..Default::default()
    };
    match meta {
        Some(m) if m.title.is_some() || m.description.is_some() => {
            am.status = Set(OK.into());
            am.title = Set(m.title);
            am.description = Set(m.description);
            am.site_name = Set(m.site_name);
            let (data, ct) = image.map(|(d, t)| (Some(d), Some(t.to_string()))).unwrap_or((None, None));
            am.image_data = Set(data);
            am.image_content_type = Set(ct);
        }
        // Nothing usable: the card falls back to the link and its host.
        _ => am.status = Set(FAILED.into()),
    }
    match am.update(db).await {
        Ok(_) | Err(DbErr::RecordNotUpdated) => Ok(()),
        Err(e) => Err(e),
    }
}

// ---------------------------------------------------------------- showing

/// Every column but the picture bytes.
fn card_columns() -> [post_links::Column; 13] {
    use post_links::Column as C;
    [
        C::Id,
        C::PostId,
        C::Url,
        C::Position,
        C::Status,
        C::Title,
        C::Description,
        C::SiteName,
        C::ImageContentType,
        C::FetchedAt,
        C::CreatedById,
        C::CreatedAt,
        C::UpdatedAt,
    ]
}

/// One card, as the templates and the API show it.
#[derive(Clone, Debug, Serialize)]
pub struct LinkCard {
    pub id: Uuid,
    /// Where it goes.
    pub url: String,
    /// What the web's `href` is: the `/out` exit page for an off-site link.
    pub href: String,
    pub host: String,
    /// `pending`, `ok` or `failed`.
    pub status: String,
    pub title: Option<String>,
    pub description: Option<String>,
    pub site_name: Option<String>,
    /// Server-relative; changes when the picture does.
    pub image_url: Option<String>,
}

impl LinkCard {
    pub fn new(l: &post_links::Model, links: &crate::links::Links) -> Self {
        let ok = l.status == OK;
        Self {
            id: l.id,
            href: if links.is_external(&l.url) { links.out_link(&l.url, false) } else { l.url.clone() },
            host: host_of(&l.url),
            url: l.url.clone(),
            status: l.status.clone(),
            title: l.title.clone().filter(|_| ok),
            description: l.description.clone().filter(|_| ok),
            site_name: l.site_name.clone().filter(|_| ok),
            image_url: (ok && l.image_content_type.is_some())
                .then(|| format!("/links/{}/image?v={}", l.id, l.fetched_at.map(|t| t.timestamp()).unwrap_or(0))),
        }
    }
}

/// The cards on each of `post_ids`, in order (picture bytes not loaded).
/// The caller decides which posts may show theirs.
pub async fn cards_for(
    db: &DatabaseConnection,
    links: &crate::links::Links,
    post_ids: &[Uuid],
) -> Result<HashMap<Uuid, Vec<LinkCard>>, DbErr> {
    let mut out: HashMap<Uuid, Vec<LinkCard>> = HashMap::new();
    if post_ids.is_empty() {
        return Ok(out);
    }
    let rows = post_links::Entity::find()
        .select_only()
        .columns(card_columns())
        .column_as(Expr::value(Option::<Vec<u8>>::None), "image_data")
        .filter(post_links::Column::PostId.is_in(post_ids.iter().copied()))
        .order_by_asc(post_links::Column::Position)
        .order_by_asc(post_links::Column::CreatedAt)
        .into_model::<post_links::Model>()
        .all(db)
        .await?;
    for l in rows {
        out.entry(l.post_id).or_default().push(LinkCard::new(&l, links));
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn urls_are_normalised_or_refused() {
        assert_eq!(normalize_url("example.com/x").as_deref(), Some("https://example.com/x"));
        assert_eq!(normalize_url("  https://a.test/b  ").as_deref(), Some("https://a.test/b"));
        assert_eq!(normalize_url("http://A.Test").as_deref(), Some("http://a.test/"));
        assert_eq!(normalize_url("example.com:8080/x").as_deref(), Some("https://example.com:8080/x"));
        assert_eq!(normalize_url("HTTPS://example.com:443/").as_deref(), Some("https://example.com/"));
        // Not links to a page. `javascript:` matters most: this ends up in
        // an href.
        for bad in [
            "javascript:alert(1)",
            "JaVaScRiPt:alert(1)",
            "data:text/html,x",
            "file:///etc/passwd",
            "ftp://example.com/",
            "mailto:a@example.com",
            "https://user:pw@example.com/",
            "https://bank.example@evil.example/",
            "http://",
            "two words.com",
            "",
            "   ",
        ] {
            assert_eq!(normalize_url(bad), None, "should refuse {bad:?}");
        }
    }

    #[test]
    fn same_address_normalises_the_same() {
        assert_eq!(normalize_url("example.com"), normalize_url("https://EXAMPLE.com/"));
    }

    #[test]
    fn metadata_prefers_opengraph_and_falls_back() {
        let html = r#"
            <html><head>
              <title>Fallback title</title>
              <meta property="og:title" content="  The Real Title  ">
              <meta property="og:description" content="What it is about">
              <meta property="og:site_name" content="Example">
              <meta property="og:image" content="/card.png">
            </head><body>ignored</body></html>"#;
        let meta = extract_metadata(html, "https://example.test/page?a=b");
        assert_eq!(meta.title.as_deref(), Some("The Real Title"));
        assert_eq!(meta.description.as_deref(), Some("What it is about"));
        assert_eq!(meta.site_name.as_deref(), Some("Example"));
        assert_eq!(meta.image_url.as_deref(), Some("https://example.test/card.png"));
    }

    #[test]
    fn a_plain_page_still_yields_a_title() {
        let html = "<html><head><title>Just A Page</title>\
                    <meta name=\"description\" content=\"Plain old meta\"></head></html>";
        let meta = extract_metadata(html, "https://example.test/");
        assert_eq!(meta.title.as_deref(), Some("Just A Page"));
        assert_eq!(meta.description.as_deref(), Some("Plain old meta"));
        assert_eq!(meta.image_url, None);
    }

    #[test]
    fn twitter_tags_fill_in_for_opengraph() {
        let html = r#"<head><meta name="twitter:title" content="Tweeted">
            <meta name="twitter:description" content="Short">
            <meta name="twitter:image" content="https://cdn.example.test/i.jpg"></head>"#;
        let meta = extract_metadata(html, "https://example.test/");
        assert_eq!(meta.title.as_deref(), Some("Tweeted"));
        assert_eq!(meta.description.as_deref(), Some("Short"));
        assert_eq!(meta.image_url.as_deref(), Some("https://cdn.example.test/i.jpg"));
    }

    #[test]
    fn awkward_markup_is_parsed_not_pattern_matched() {
        let html = r#"<html><head>
            <!-- <meta property="og:title" content="Commented out"> -->
            <meta property="og:title" content="A > B, actually">
            <title>Not this one</title>
        </head></html>"#;
        let meta = extract_metadata(html, "https://example.test/");
        assert_eq!(meta.title.as_deref(), Some("A > B, actually"));
    }

    #[test]
    fn text_is_collapsed_and_bounded() {
        let long = "x".repeat(900);
        let html = format!(
            "<html><head><meta property=\"og:title\" content=\"a\n\n   b\">\
             <meta property=\"og:description\" content=\"{long}\"></head></html>"
        );
        let meta = extract_metadata(&html, "https://example.test/");
        assert_eq!(meta.title.as_deref(), Some("a b"));
        assert_eq!(meta.description.as_ref().unwrap().chars().count(), 600);
        assert!(meta.description.unwrap().ends_with('…'));
    }

    #[test]
    fn blank_tags_are_ignored() {
        let html = "<html><head><title>Real</title><meta property=\"og:title\" content=\"   \"></head></html>";
        assert_eq!(extract_metadata(html, "https://x.test/").title.as_deref(), Some("Real"));
    }

    /// A picture URL that isn't http(s) is no picture.
    #[test]
    fn odd_image_schemes_are_dropped() {
        let html = r#"<meta property="og:title" content="T"><meta property="og:image" content="data:image/png;base64,AAAA">"#;
        assert_eq!(extract_metadata(html, "https://x.test/").image_url, None);
        let html = r#"<meta property="og:title" content="T"><meta property="og:image" content="//cdn.x.test/a.png">"#;
        assert_eq!(extract_metadata(html, "https://x.test/").image_url.as_deref(), Some("https://cdn.x.test/a.png"));
    }

    #[test]
    fn pictures_are_recognised_by_their_bytes() {
        assert_eq!(sniff_image(b"\x89PNG\r\n\x1a\n...."), Some("image/png"));
        assert_eq!(sniff_image(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg"));
        assert_eq!(sniff_image(b"GIF89a..."), Some("image/gif"));
        assert_eq!(sniff_image(b"RIFF\0\0\0\0WEBPVP8 "), Some("image/webp"));
        for bad in [&b"<svg xmlns='http://www.w3.org/2000/svg'/>"[..], b"<html>", b"", b"RIFF\0\0\0\0WAVE"] {
            assert_eq!(sniff_image(bad), None);
        }
    }

    #[test]
    fn hosts_drop_www() {
        assert_eq!(host_of("https://www.example.com/x"), "example.com");
        assert_eq!(host_of("https://docs.example.com/x"), "docs.example.com");
    }
}