118.0 KiB · text History 7ce364f
//! Live-database tests for moderation, through the real routers: the web
//! (`recourse::web::router`, session cookies, the real templates) and
//! `/api/v1` (device tokens). Every rule is checked from both sides where a
//! person can reach it from both.
//!
//! Skipped unless `TEST_DATABASE_URL` is set (`just test-db`). Names are
//! unique per run, so the database can be shared.
use std::sync::Arc;

use std::net::SocketAddr;

use axum::body::Body;
use axum::extract::ConnectInfo;
use axum::http::{Request, StatusCode};
use axum::Router;
use chrono::Utc;
use migration::MigratorTrait;
use sea_orm::*;
use serde_json::{json, Value};
use tower::ServiceExt;
use uuid::Uuid;

use recourse::auth;
use recourse::entities::{categories, moderation_log, posts, topic_reads, topics, users};
use recourse::moderation::{self, Actor, Sanction};
use recourse::policy::{FlagThreshold, STAFF_ONLY};
use recourse::{api, AppState, Config};

static MIGRATED: tokio::sync::OnceCell<()> = tokio::sync::OnceCell::const_new();

struct App {
    router: Router,
    state: AppState,
    /// Everything the app mailed.
    outbox: Arc<std::sync::Mutex<Vec<recourse::mailer::Message>>>,
}

/// A mailer that keeps what it sends.
struct Outbox(Arc<std::sync::Mutex<Vec<recourse::mailer::Message>>>);

impl recourse::mailer::Mailer for Outbox {
    fn send<'a>(&'a self, message: &'a recourse::mailer::Message) -> recourse::mailer::SendFuture<'a> {
        self.0.lock().unwrap().push(message.clone());
        Box::pin(async { Ok(()) })
    }
    fn delivers(&self) -> bool {
        true
    }
}

async fn app() -> Option<App> {
    app_with(|_| {}).await
}

/// [`app`] with the config adjusted.
async fn app_with(adjust: impl FnOnce(&mut Config)) -> Option<App> {
    let url = std::env::var("TEST_DATABASE_URL").ok()?;
    let db = Database::connect(&url).await.expect("connect to TEST_DATABASE_URL");
    MIGRATED
        .get_or_init(|| async {
            migration::Migrator::up(&db, None).await.expect("migrate");
        })
        .await;
    let mut config = Config::from_env();
    config.database_url = url;
    config.require_email_verification = true;
    config.mail_prism_url = None;
    config.mail_prism_api_key = None;
    config.min_trust_to_flag = 1;
    config.flag_threshold = FlagThreshold { ratio: 0.1, min_flags: 2, enough_flags: 10 };
    // As behind nginx on the host and a cluster ingress.
    config.trusted_proxies = recourse::client_ip::TrustedProxies::parse("127.0.0.1/32,10.0.0.0/8").unwrap();
    config.lameness = recourse::lameness::Config::default();
    adjust(&mut config);
    let config = Arc::new(config);
    let db = Arc::new(db);
    let outbox = Arc::new(std::sync::Mutex::new(Vec::new()));
    let state = AppState {
        env: recourse::web::environment(&config),
        db: db.clone(),
        config: config.clone(),
        view_throttle: recourse::new_view_throttle(),
        mailer: Arc::new(Outbox(outbox.clone())),
        live: recourse::live::Hub::new(),
    };
    let router = recourse::web::router(db.clone())
        .nest("/api/v1", api::router(db))
        .with_state(state.clone())
        .layer(axum::middleware::from_fn_with_state(
            Arc::new(config.trusted_proxies.clone()),
            recourse::client_ip::layer,
        ));
    Some(App { router, state, outbox })
}

fn tag() -> String {
    Uuid::now_v7().simple().to_string()[20..].to_string()
}

const PASSWORD: &str = "pw-for-tests-123";

/// A signed-in party: the account, a session cookie (web) and a device
/// token (API).
struct Who {
    user: users::Model,
    cookie: String,
    token: String,
}

impl App {
    fn db(&self) -> &DatabaseConnection {
        self.state.db.as_ref()
    }

    async fn send(&self, mut req: Request<Body>) -> (StatusCode, String, Option<String>) {
        // A direct (unproxied) client unless the test says otherwise.
        if req.extensions().get::<ConnectInfo<SocketAddr>>().is_none() {
            req.extensions_mut().insert(ConnectInfo(SocketAddr::from(([192, 0, 2, 1], 40000))));
        }
        let res = self.router.clone().oneshot(req).await.unwrap();
        let status = res.status();
        let location = res.headers().get("location").map(|v| v.to_str().unwrap().to_string());
        let bytes = axum::body::to_bytes(res.into_body(), 1 << 22).await.unwrap();
        (status, String::from_utf8_lossy(&bytes).into_owned(), location)
    }

    async fn api(&self, method: &str, path: &str, who: &Who, body: Option<Value>) -> (StatusCode, Value) {
        let req = Request::builder()
            .method(method)
            .uri(format!("/api/v1{path}"))
            .header("authorization", format!("Bearer {}", who.token));
        let req = match body {
            Some(b) => req.header("content-type", "application/json").body(Body::from(b.to_string())),
            None => req.body(Body::empty()),
        }
        .unwrap();
        let (status, text, _) = self.send(req).await;
        let v = if text.is_empty() { Value::Null } else { serde_json::from_str(&text).unwrap_or(Value::String(text)) };
        (status, v)
    }

    async fn page(&self, path: &str, who: Option<&Who>) -> (StatusCode, String) {
        let mut req = Request::builder().uri(path);
        if let Some(w) = who {
            req = req.header("cookie", format!("session_token={}", w.cookie));
        }
        let (s, body, _) = self.send(req.body(Body::empty()).unwrap()).await;
        (s, body)
    }

    async fn form(&self, path: &str, who: Option<&Who>, form: &[(&str, &str)]) -> (StatusCode, String, Option<String>) {
        let body = form
            .iter()
            .map(|(k, v)| format!("{k}={}", urlencode(v)))
            .collect::<Vec<_>>()
            .join("&");
        let mut req = Request::builder()
            .method("POST")
            .uri(path)
            .header("content-type", "application/x-www-form-urlencoded");
        if let Some(w) = who {
            req = req.header("cookie", format!("session_token={}", w.cookie));
        }
        self.send(req.body(Body::from(body)).unwrap()).await
    }

    async fn who(&self, name: &str, trust: i32, staff: bool) -> Who {
        let name = format!("{name}-{}", tag());
        let u = auth::create_user_direct(self.db(), &name, &format!("{name}@example.test"), PASSWORD, staff)
            .await
            .unwrap();
        let mut am: users::ActiveModel = u.into();
        am.trust_level = Set(trust);
        let user = am.update(self.db()).await.unwrap();
        let cookie = auth::create_session(self.db(), user.id, 1).await.unwrap().session_token;
        let token = auth::create_api_token(self.db(), user.id, Some("test".into()), None).await.unwrap().1;
        Who { user, cookie, token }
    }

    /// A reader with no password (cheap: no hashing), for readership counts.
    async fn reader(&self) -> users::Model {
        let name = format!("reader-{}", tag());
        let now = Utc::now();
        let mut am = users::ActiveModel {
            id: Set(Uuid::now_v7()),
            username: Set(name.clone()),
            email: Set(format!("{name}@example.test")),
            password_hash: Set("x".into()),
            is_active: Set(true),
            is_staff: Set(false),
            preferred_sort: Set("latest".into()),
            preferred_view: Set("classic".into()),
            reaction_notifications: Set(true),
            trust_level: Set(1),
            created_at: Set(now.into()),
            updated_at: Set(now.into()),
            last_login_at: Set(None),
            email_verified_at: Set(Some(now.into())),
            avatar_data: Set(None),
            avatar_content_type: Set(None),
            ..Default::default()
        };
        am.silenced_at = Set(None);
        am.insert(self.db()).await.unwrap()
    }

    async fn read(&self, user: Uuid, topic: &topics::Model, upto: i32) {
        topic_reads::ActiveModel {
            user_id: Set(user),
            topic_id: Set(topic.id),
            last_read_post_number: Set(upto),
            updated_at: Set(Utc::now().into()),
        }
        .insert(self.db())
        .await
        .unwrap();
    }

    async fn category(&self, view: Option<i32>, create: Option<i32>, reply: Option<i32>) -> categories::Model {
        let slug = format!("cat-{}", tag());
        let now = Utc::now();
        categories::ActiveModel {
            id: Set(Uuid::now_v7()),
            name: Set(slug.clone()),
            slug: Set(slug),
            description: Set(None),
            color: Set("#7c3aed".into()),
            position: Set(0),
            parent_id: Set(None),
            min_trust_level: Set(view),
            topic_min_trust: Set(create),
            reply_min_trust: Set(reply),
            reactions_enabled: Set(true),
            reaction_keys: Set(None),
            created_at: Set(now.into()),
            updated_at: Set(now.into()),
        }
        .insert(self.db())
        .await
        .unwrap()
    }

    async fn topic(&self, author: &Who, c: &categories::Model, body: &str) -> (topics::Model, posts::Model) {
        let t = recourse::actions::create_topic(&self.state, &author.user, &c.slug, &format!("Topic {}", tag()), body, "")
            .await
            .unwrap();
        let p = posts::Entity::find()
            .filter(posts::Column::TopicId.eq(t.id))
            .filter(posts::Column::PostNumber.eq(1))
            .one(self.db())
            .await
            .unwrap()
            .unwrap();
        (t, p)
    }

    async fn post(&self, id: Uuid) -> posts::Model {
        posts::Entity::find_by_id(id).one(self.db()).await.unwrap().unwrap()
    }

    async fn logged(&self, action: &str, target: Uuid) -> bool {
        moderation_log::Entity::find()
            .filter(moderation_log::Column::Action.eq(action))
            .filter(moderation_log::Column::TargetId.eq(target))
            .count(self.db())
            .await
            .unwrap()
            > 0
    }
}

fn urlencode(s: &str) -> String {
    s.bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
            _ => format!("%{b:02X}"),
        })
        .collect()
}

fn code(v: &Value) -> &str {
    v["error"]["code"].as_str().unwrap_or_else(|| panic!("no error envelope: {v}"))
}

#[tokio::test]
async fn a_silenced_user_reads_but_cannot_write_on_the_web_or_the_api() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let member = app.who("member", 2, false).await;
    let c = app.category(None, None, None).await;
    let (topic, post) = app.topic(&staff, &c, "Hello").await;

    // A cooldown: always timed, ≤ 90 days, with a reason.
    let week = Utc::now() + chrono::Duration::days(7);
    for (reason, until) in [
        (Some("cool down"), None),
        (Some("cool down"), Some(Utc::now() + chrono::Duration::days(91))),
        (None, Some(week)),
        (Some("  "), Some(week)),
    ] {
        let r = moderation::sanction(app.db(), Actor::web(&staff.user), member.user.id, Sanction::Silence, reason, until).await;
        assert!(matches!(r, Err(recourse::actions::ActionError::Invalid(_))), "{reason:?} {until:?}");
    }
    let (s, _, _) = app
        .form(&format!("/admin/users/{}/cooldown", member.user.id), Some(&staff), &[("reason", "x"), ("duration", "custom"), ("custom", "13w")])
        .await;
    assert_eq!(s, StatusCode::BAD_REQUEST, "13 weeks > 90 days");
    let (s, _, _) = app
        .form(&format!("/admin/users/{}/cooldown", member.user.id), Some(&staff), &[("reason", "cool down"), ("duration", "2160h"), ("mode", "classic")])
        .await;
    assert_eq!(s, StatusCode::OK, "the 90-day preset");
    assert!(app.logged("silence_user", member.user.id).await);

    // API: reads work; writes are 403 silenced; a private bookmark still works.
    let (s, page) = app.api("GET", &format!("/topics/{}", topic.id), &member, None).await;
    assert_eq!(s, StatusCode::OK);
    assert_eq!(page["can_reply"], json!(false));
    assert_eq!(page["reply_blocked"]["code"], json!("silenced"));
    let (_, me) = app.api("GET", "/me", &member, None).await;
    assert_eq!(me["user"]["may_write"], json!(false));
    let msg = me["user"]["silenced"]["message"].as_str().unwrap();
    assert!(msg.starts_with("Read-only until ") && msg.ends_with(": cool down"), "{msg}");
    assert!(me["user"]["read_only_until"].is_string());
    for (m, p, b) in [
        ("POST", format!("/topics/{}/posts", topic.id), json!({"body": "hi"})),
        ("PUT", format!("/posts/{}/reaction", post.id), json!({"key": "heart"})),
        ("POST", format!("/posts/{}/flags", post.id), json!({"reason": "spam"})),
        ("POST", format!("/categories/{}/topics", c.slug), json!({"title": "t", "body": "b"})),
    ] {
        let (s, body) = app.api(m, &p, &member, Some(b)).await;
        assert_eq!(s, StatusCode::FORBIDDEN, "{m} {p}");
        assert_eq!(code(&body), "silenced");
    }
    let (s, _) = app.api("PUT", &format!("/posts/{}/bookmark", post.id), &member, Some(json!({"bookmarked": true}))).await;
    assert_eq!(s, StatusCode::OK);

    // Web: the page says so and has no reply form; a forged post is refused.
    let (s, html) = app.page(&format!("/t/{}", topic.id), Some(&member)).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains(r#"id="silence-banner""#) && html.contains("cool down"));
    assert!(!html.contains(r#"id="reply""#));
    let (s, _, _) = app.form(&format!("/t/{}/posts", topic.id), Some(&member), &[("body", "sneaky")]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    let (s, _, _) = app.form(&format!("/c/{}/topics", c.slug), Some(&member), &[("title", "x"), ("body", "y")]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    assert_eq!(posts::Entity::find().filter(posts::Column::TopicId.eq(topic.id)).count(app.db()).await.unwrap(), 1);

    // Lifted: writing works again.
    moderation::lift(app.db(), Actor::web(&staff.user), member.user.id, Sanction::Silence).await.unwrap();
    let (s, _) = app.api("POST", &format!("/topics/{}/posts", topic.id), &member, Some(json!({"body": "back"}))).await;
    assert_eq!(s, StatusCode::CREATED);

    // A silence that has run out is no silence.
    moderation::sanction(app.db(), Actor::web(&staff.user), member.user.id, Sanction::Silence, Some("brief"), Some(Utc::now() + chrono::Duration::seconds(1)))
        .await
        .unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(1200)).await;
    let (s, _) = app.api("POST", &format!("/topics/{}/posts", topic.id), &member, Some(json!({"body": "expired"}))).await;
    assert_eq!(s, StatusCode::CREATED);
}

#[tokio::test]
async fn staff_only_topics_and_read_only_windows() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let member = app.who("member", 2, false).await;
    let basic = app.who("basic", 1, false).await;
    let regular = app.who("regular", 3, false).await;

    // Announcements: anyone reads, staff start topics, members reply.
    let ann = app.category(None, Some(STAFF_ONLY), None).await;
    let (s, body) = app.api("POST", &format!("/categories/{}/topics", ann.slug), &member, Some(json!({"title": "t", "body": "b"}))).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    assert_eq!(code(&body), "staff_only");
    let (s, _, _) = app.form(&format!("/c/{}/topics", ann.slug), Some(&member), &[("title", "t"), ("body", "b")]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    assert_eq!(app.page(&format!("/c/{}/new", ann.slug), Some(&member)).await.0, StatusCode::FORBIDDEN);
    let (_, html) = app.page(&format!("/c/{}", ann.slug), Some(&member)).await;
    assert!(!html.contains(&format!("/c/{}/new", ann.slug)), "no New Topic button");
    assert!(html.contains("Only staff can start topics here."));
    let (_, html) = app.page(&format!("/c/{}?view=focus", ann.slug), Some(&member)).await;
    assert!(!html.contains(&format!("/c/{}/new", ann.slug)) && html.contains("Only staff can start topics here."));
    let (_, page) = app.api("GET", &format!("/categories/{}", ann.slug), &member, None).await;
    assert_eq!(page["can_create_topic"], json!(false));
    assert_eq!(page["create_blocked"]["code"], json!("staff_only"));
    assert_eq!(page["category"]["posting"]["create_topic"]["kind"], json!("staff"));
    assert_eq!(page["category"]["can_reply"], json!(true));

    let (s, created) = app.api("POST", &format!("/categories/{}/topics", ann.slug), &staff, Some(json!({"title": "News", "body": "b"}))).await;
    assert_eq!(s, StatusCode::CREATED, "{created}");
    let tid = created["topic"]["id"].as_str().unwrap().to_string();
    let (s, _) = app.api("POST", &format!("/topics/{tid}/posts"), &member, Some(json!({"body": "thanks"}))).await;
    assert_eq!(s, StatusCode::CREATED);

    // A read-only window: Basic reads, Regulars post.
    let window = app.category(Some(1), Some(3), Some(3)).await;
    let (topic, post) = app.topic(&regular, &window, "Plans").await;
    let (s, page) = app.api("GET", &format!("/topics/{}", topic.id), &basic, None).await;
    assert_eq!(s, StatusCode::OK);
    assert_eq!(page["can_reply"], json!(false));
    assert_eq!(page["can_react"], json!(false));
    assert_eq!(page["reply_blocked"]["code"], json!("trust_level"));
    let (s, body) = app.api("POST", &format!("/topics/{}/posts", topic.id), &basic, Some(json!({"body": "me too"}))).await;
    assert_eq!((s, code(&body)), (StatusCode::FORBIDDEN, "trust_level"));
    let (s, body) = app.api("PUT", &format!("/posts/{}/reaction", post.id), &basic, Some(json!({"key": "heart"}))).await;
    assert_eq!((s, code(&body)), (StatusCode::FORBIDDEN, "trust_level"));
    let (s, _, _) = app.form(&format!("/t/{}/posts", topic.id), Some(&basic), &[("body", "me too")]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&basic)).await;
    assert!(!html.contains(r#"id="reply""#) && html.contains("Replying here needs trust level 3"));
    // …but can still flag (abuse reports aren't a posting right).
    let (s, _) = app.api("POST", &format!("/posts/{}/flags", post.id), &basic, Some(json!({"reason": "spam"}))).await;
    assert_eq!(s, StatusCode::CREATED);
    let (s, _) = app.api("POST", &format!("/topics/{}/posts", topic.id), &regular, Some(json!({"body": "ok"}))).await;
    assert_eq!(s, StatusCode::CREATED);
    // Below the read level it's simply not there.
    let new = app.who("new", 0, false).await;
    assert_eq!(app.api("GET", &format!("/topics/{}", topic.id), &new, None).await.0, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn a_locked_topic_takes_no_replies_except_from_staff() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let member = app.who("member", 2, false).await;
    let c = app.category(None, None, None).await;
    let (topic, _) = app.topic(&member, &c, "Hot take").await;
    let other = app.who("other", 2, false).await;
    let reply = recourse::actions::reply(&app.state, &other.user, topic.id, "Disagree").await.unwrap();

    // Non-staff can't lock.
    let (s, _, _) = app.form(&format!("/t/{}/lock", topic.id), Some(&member), &[("reason", "mine")]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    let (s, _, _) = app.form(&format!("/t/{}/lock", topic.id), Some(&staff), &[("reason", "Cooling off")]).await;
    assert_eq!(s, StatusCode::SEE_OTHER);
    assert!(app.logged("lock_topic", topic.id).await);

    let (s, body) = app.api("POST", &format!("/topics/{}/posts", topic.id), &member, Some(json!({"body": "but"}))).await;
    assert_eq!((s, code(&body)), (StatusCode::FORBIDDEN, "locked"));
    assert_eq!(body["error"]["message"], json!("Locked by staff: Cooling off"));
    let (s, _, _) = app.form(&format!("/t/{}/posts", topic.id), Some(&member), &[("body", "but")]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    let (s, body) = app.api("PUT", &format!("/posts/{}/reaction", reply.id), &member, Some(json!({"key": "heart"}))).await;
    assert_eq!((s, code(&body)), (StatusCode::FORBIDDEN, "locked"));
    // The author can't edit in a locked topic either.
    let (s, _, _) = app.form(&format!("/p/{}", reply.id), Some(&other), &[("body", "edited")]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    // Flags still work.
    let (s, _) = app.api("POST", &format!("/posts/{}/flags", reply.id), &member, Some(json!({"reason": "abusive"}))).await;
    assert_eq!(s, StatusCode::CREATED);

    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &member, None).await;
    assert_eq!(page["topic"]["is_locked"], json!(true));
    assert_eq!(page["topic"]["lock_reason"], json!("Cooling off"));
    assert_eq!(page["can_reply"], json!(false));
    assert_eq!(page["reply_blocked"]["code"], json!("locked"));
    let (_, list) = app.api("GET", &format!("/categories/{}", c.slug), &member, None).await;
    assert_eq!(list["topics"][0]["is_locked"], json!(true));
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&member)).await;
    assert!(html.contains("Locked by staff: Cooling off") && !html.contains(r#"id="reply""#));
    let (_, html) = app.page(&format!("/c/{}?view=focus", c.slug), Some(&member)).await;
    assert!(html.contains(r#"title="Locked""#), "lock on the Focus tile");

    // Staff still post; unlock reopens.
    let (s, _) = app.api("POST", &format!("/topics/{}/posts", topic.id), &staff, Some(json!({"body": "Locked for a day."}))).await;
    assert_eq!(s, StatusCode::CREATED);
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&staff)).await;
    assert!(html.contains(r#"id="reply""#) && html.contains("/unlock"));
    app.form(&format!("/t/{}/unlock", topic.id), Some(&staff), &[]).await;
    let (s, _) = app.api("POST", &format!("/topics/{}/posts", topic.id), &member, Some(json!({"body": "thanks"}))).await;
    assert_eq!(s, StatusCode::CREATED);

    // Pin / unpin (staff), logged.
    let (s, _, _) = app.form(&format!("/t/{}/pin", topic.id), Some(&member), &[]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    app.form(&format!("/t/{}/pin", topic.id), Some(&staff), &[]).await;
    assert!(topics::Entity::find_by_id(topic.id).one(app.db()).await.unwrap().unwrap().is_pinned);
    assert!(app.logged("pin_topic", topic.id).await);
}

#[tokio::test]
async fn a_moderated_posts_hidden_original_never_reaches_non_staff() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("author", 2, false).await;
    let reader = app.who("reader", 2, false).await;
    let c = app.category(None, None, None).await;
    let secret = format!("insult{}", tag());
    let (topic, post) = app.topic(&author, &c, &format!("You are an {secret}")).await;
    // A second version, also before moderation.
    recourse::actions::edit_post(&app.state, &author.user, post.id, &format!("Still an {secret}")).await.unwrap();

    let (s, _, _) = app
        .form(&format!("/p/{}/moderate", post.id), Some(&staff), &[("note", "Removed: personal attack."), ("hide_original", "1")])
        .await;
    assert_eq!(s, StatusCode::SEE_OTHER);
    assert!(app.logged("moderate_post", post.id).await && app.logged("hide_original", post.id).await);

    // History: non-staff (signed in or not) see "hidden by staff", never the text.
    for who in [None, Some(&reader), Some(&author)] {
        let (s, html) = app.page(&format!("/p/{}/history", post.id), who).await;
        assert_eq!(s, StatusCode::OK);
        assert!(!html.contains(&secret), "original leaked to non-staff");
        assert_eq!(html.matches("data-hidden-by-staff").count(), 2, "both earlier versions hidden");
        assert!(html.contains("Removed: personal attack."));
    }
    let (_, html) = app.page(&format!("/p/{}/history", post.id), Some(&staff)).await;
    assert!(html.contains(&secret) && html.contains("hidden from non-staff"));

    // The topic page and the API carry only the note, as the staff note.
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&reader)).await;
    assert!(!html.contains(&secret) && html.contains("data-moderated"));
    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &reader, None).await;
    assert!(!page.to_string().contains(&secret));
    assert_eq!(page["posts"][0]["moderated"]["by"], json!(staff.user.username));
    // Search can't find it either.
    let (_, found) = app.api("GET", &format!("/search?q={secret}"), &reader, None).await;
    assert_eq!(found["topics"].as_array().map(|a| a.len()).unwrap_or(0), 0, "{found}");

    // The author can't edit it back.
    let (s, _, _) = app.form(&format!("/p/{}", post.id), Some(&author), &[("body", "my words")]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    assert_eq!(app.page(&format!("/p/{}/edit", post.id), Some(&author)).await.0, StatusCode::FORBIDDEN);

    // Unhide, hide, restore: staff only, logged.
    let (s, _, _) = app.form(&format!("/p/{}/history/unhide", post.id), Some(&reader), &[]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    app.form(&format!("/p/{}/history/unhide", post.id), Some(&staff), &[]).await;
    assert!(app.page(&format!("/p/{}/history", post.id), Some(&reader)).await.1.contains(&secret));
    app.form(&format!("/p/{}/history/hide", post.id), Some(&staff), &[]).await;
    assert!(!app.page(&format!("/p/{}/history", post.id), Some(&reader)).await.1.contains(&secret));
    app.form(&format!("/p/{}/moderation/restore", post.id), Some(&staff), &[]).await;
    let restored = app.post(post.id).await;
    assert!(restored.moderated_at.is_none() && restored.raw == format!("Still an {secret}"));
    assert!(app.logged("restore_post_body", post.id).await);
}

#[tokio::test]
async fn flags_hide_a_post_by_share_of_readers() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("author", 2, false).await;
    let c = app.category(None, None, None).await;
    let f1 = app.who("f1", 1, false).await;
    let f2 = app.who("f2", 1, false).await;

    async fn readers(app: &App, topic: &topics::Model, n: usize, include: &[&Who]) {
        for w in include {
            app.read(w.user.id, topic, 1).await;
        }
        for _ in include.len()..n {
            let r = app.reader().await;
            app.read(r.id, topic, 1).await;
        }
    }

    // Below the ratio: 2 of 21 readers.
    let (ta, pa) = app.topic(&author, &c, "A").await;
    readers(&app, &ta, 21, &[&f1, &f2]).await;
    assert_eq!(flag(&app, &f1, pa.id).await.0, StatusCode::CREATED);
    assert_eq!(flag(&app, &f2, pa.id).await.0, StatusCode::CREATED);
    assert!(app.post(pa.id).await.hidden_at.is_none(), "2/21 < 10%");

    // At the ratio, and the min-flags guard: 1 of 20 doesn't hide; 2 of 20 does.
    let (tb, pb) = app.topic(&author, &c, "B").await;
    readers(&app, &tb, 20, &[&f1, &f2]).await;
    flag(&app, &f1, pb.id).await;
    assert!(app.post(pb.id).await.hidden_at.is_none(), "one flag never hides");
    flag(&app, &f2, pb.id).await;
    assert!(app.post(pb.id).await.hidden_at.is_some(), "2/20 = 10%");
    assert!(app.logged("auto_hide", pb.id).await);

    // Once only, and not your own.
    let (s, body) = flag(&app, &f1, pb.id).await;
    assert_eq!((s, code(&body)), (StatusCode::CONFLICT, "already_flagged"));
    let (s, body) = flag(&app, &author, pb.id).await;
    assert_eq!((s, code(&body)), (StatusCode::FORBIDDEN, "own_post"));
    let new = app.who("new", 0, false).await;
    let (s, body) = flag(&app, &new, pa.id).await;
    assert_eq!((s, code(&body)), (StatusCode::FORBIDDEN, "trust_level"));

    // Hidden: others get nothing of it; the author and staff do.
    let (_, page) = app.api("GET", &format!("/topics/{}", tb.id), &f1, None).await;
    assert_eq!(page["posts"][0]["hidden"], json!(true));
    assert_eq!(page["posts"][0]["cooked"], json!(""));
    let (_, page) = app.api("GET", &format!("/topics/{}", tb.id), &author, None).await;
    assert!(page["posts"][0]["cooked"].as_str().unwrap().contains("Opening") || !page["posts"][0]["cooked"].as_str().unwrap().is_empty());
    let (_, html) = app.page(&format!("/t/{}", tb.id), Some(&f1)).await;
    assert!(html.contains("Hidden pending staff review."));

    // Zero recorded readers: min flags decides.
    let (_, pc) = app.topic(&author, &c, "C").await;
    flag(&app, &f1, pc.id).await;
    assert!(app.post(pc.id).await.hidden_at.is_none());
    flag(&app, &f2, pc.id).await;
    assert!(app.post(pc.id).await.hidden_at.is_some(), "2 flags, 0 readers");

    // The queue shows the inputs; dismissing shows the post again.
    let (s, html) = app.page("/admin/flags", Some(&staff)).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains(&format!(r#"id="flags-{}""#, pb.id)) && html.contains("2 / 20 readers"));
    assert_eq!(app.page("/admin/flags", Some(&f1)).await.0, StatusCode::FORBIDDEN);
    let (s, html, _) = app.form(&format!("/admin/flags/{}/dismiss", pb.id), Some(&staff), &[("mode", "focus")]).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains("Flags dismissed"));
    assert!(app.post(pb.id).await.hidden_at.is_none());
    assert!(app.logged("dismiss_flags", pb.id).await);
    let (_, html) = app.page(&format!("/admin/users/{}", f1.user.id), Some(&staff)).await;
    assert!(html.contains("dismissed"), "the flagger's record");

    // Moderating from the queue upholds.
    let (s, _, _) = app.form(&format!("/admin/flags/{}/moderate", pc.id), Some(&staff), &[("note", "Removed."), ("mode", "classic")]).await;
    assert_eq!(s, StatusCode::OK);
    assert!(app.post(pc.id).await.moderated_at.is_some());
}

async fn flag(app: &App, who: &Who, post: Uuid) -> (StatusCode, Value) {
    app.api("POST", &format!("/posts/{post}/flags"), who, Some(json!({"reason": "abusive", "note": "rude"}))).await
}

#[tokio::test]
async fn a_flag_shadowbanned_users_flags_count_for_nothing_and_they_cant_tell() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("author", 2, false).await;
    let nuisance = app.who("nuisance", 2, false).await;
    let honest = app.who("honest", 2, false).await;
    let c = app.category(None, None, None).await;
    let (topic, post) = app.topic(&author, &c, "Fine post").await;

    let (s, html, _) = app
        .form(&format!("/admin/users/{}/flag-shadowban", nuisance.user.id), Some(&staff), &[("reason", "reports everything"), ("mode", "classic")])
        .await;
    assert_eq!(s, StatusCode::OK, "{html}");
    assert!(app.logged("flag_shadowban", nuisance.user.id).await);

    let (s, _) = app.api("POST", &format!("/posts/{}/flags", post.id), &nuisance, Some(json!({"reason": "spam"}))).await;
    assert_eq!(s, StatusCode::CREATED, "their flag appears to work");
    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &nuisance, None).await;
    assert_eq!(page["posts"][0]["flagged"], json!(true));
    // Zero readers and two flaggers would hide it; one is ignored, so it doesn't.
    app.api("POST", &format!("/posts/{}/flags", post.id), &honest, Some(json!({"reason": "spam"}))).await;
    assert!(app.post(post.id).await.hidden_at.is_none());

    // Nothing they can read says so.
    let (_, me) = app.api("GET", "/me", &nuisance, None).await;
    let me = me.to_string();
    assert!(!me.contains("ignored") && !me.contains("shadowban"), "{me}");
    let (_, html) = app.page("/profile", Some(&nuisance)).await;
    let lower = html.to_lowercase();
    assert!(!lower.contains("flags ignored") && !lower.contains("shadowban") && !lower.contains("flags_ignored"));
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&nuisance)).await;
    assert!(html.contains("Flagged"));

    // Staff see their flag apart, collapsed.
    let (_, html) = app.page("/admin/flags", Some(&staff)).await;
    assert!(html.contains("from shadowbanned flaggers"));
    let (_, html) = app.page(&format!("/admin/users/{}", nuisance.user.id), Some(&staff)).await;
    assert!(html.contains("flags ignored"));
}

#[tokio::test]
async fn a_suspended_account_is_signed_out_and_cannot_sign_in() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let user = app.who("suspect", 2, false).await;
    assert_eq!(app.api("GET", "/me", &user, None).await.0, StatusCode::OK);
    assert_eq!(app.page("/profile", Some(&user)).await.0, StatusCode::OK);

    // Staff can't be sanctioned; non-staff can't sanction.
    let (s, _, _) = app.form(&format!("/admin/users/{}/suspend", staff.user.id), Some(&staff), &[]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    let (s, _, _) = app.form(&format!("/admin/users/{}/suspend", staff.user.id), Some(&user), &[]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);

    let (s, html, _) = app
        .form(&format!("/admin/users/{}/suspend", user.user.id), Some(&staff), &[("reason", "spam wave"), ("duration", "168h"), ("mode", "classic")])
        .await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains("Suspended until"));
    assert!(app.logged("suspend_user", user.user.id).await);

    let (s, body) = app.api("GET", "/me", &user, None).await;
    assert_eq!((s, code(&body)), (StatusCode::UNAUTHORIZED, "unauthorized"));
    let (s, _) = app.page("/profile", Some(&user)).await;
    assert_eq!(s, StatusCode::TEMPORARY_REDIRECT, "the session is gone: to /login");
    let (s, html, _) = app.form("/auth/login", None, &[("username", &user.user.username), ("password", PASSWORD)]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    assert!(html.contains("This account is suspended until") && html.contains("spam wave"));

    // Lifted: they can sign in again.
    app.form(&format!("/admin/users/{}/unsuspend", user.user.id), Some(&staff), &[]).await;
    let (s, _, loc) = app.form("/auth/login", None, &[("username", &user.user.username), ("password", PASSWORD)]).await;
    assert_eq!((s, loc.as_deref()), (StatusCode::SEE_OTHER, Some("/")));
}

#[tokio::test]
async fn category_permission_changes_are_logged_and_subcategories_start_with_their_parents_rules() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let parent = app.category(None, Some(STAFF_ONLY), Some(2)).await;
    let name = format!("Sub {}", tag());
    let (s, html, _) = app
        .form("/admin/categories/inline", Some(&staff), &[("name", &name), ("parent_id", &parent.id.to_string())])
        .await;
    assert_eq!(s, StatusCode::OK, "{html}");
    let sub = categories::Entity::find().filter(categories::Column::Name.eq(&name)).one(app.db()).await.unwrap().unwrap();
    assert_eq!((sub.topic_min_trust, sub.reply_min_trust), (Some(STAFF_ONLY), Some(2)));
    assert!(html.contains("Staff start topics"));

    let form = [
        ("name", parent.name.as_str()),
        ("slug", parent.slug.as_str()),
        ("color", "#7c3aed"),
        ("min_trust_level", "1"),
        ("topic_rule", "3"),
        ("reply_rule", "viewers"),
    ];
    let (s, _, _) = app.form(&format!("/admin/categories/{}", parent.id), Some(&staff), &form).await;
    assert_eq!(s, StatusCode::SEE_OTHER);
    let p = categories::Entity::find_by_id(parent.id).one(app.db()).await.unwrap().unwrap();
    assert_eq!((p.min_trust_level, p.topic_min_trust, p.reply_min_trust), (Some(1), Some(3), None));
    assert!(app.logged("category_permissions", parent.id).await);
    let (s, html) = app.page(&format!("/admin/log?user={}", staff.user.id), Some(&staff)).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains("Changed category permissions"));
}

/// A request from `peer` with these extra headers.
fn from_peer(mut req: Request<Body>, peer: &str, headers: &[(&str, &str)]) -> Request<Body> {
    for (k, v) in headers {
        req.headers_mut().append(
            axum::http::HeaderName::from_bytes(k.as_bytes()).unwrap(),
            axum::http::HeaderValue::from_str(v).unwrap(),
        );
    }
    req.extensions_mut().insert(ConnectInfo(SocketAddr::new(peer.parse().unwrap(), 40000)));
    req
}

fn login_request(name: &str) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri("/auth/login")
        .header("content-type", "application/x-www-form-urlencoded")
        .body(Body::from(format!("username={}&password={}", urlencode(name), urlencode(PASSWORD))))
        .unwrap()
}

async fn sightings(app: &App, user: Uuid) -> Vec<(String, String, i32)> {
    recourse::ips::of_user(app.db(), user)
        .await
        .unwrap()
        .into_iter()
        .map(|s| (s.ip, s.last_action, s.count))
        .collect()
}

#[tokio::test]
async fn client_addresses_come_from_trusted_proxies_only_and_only_staff_see_them() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let alice = app.who("alice", 2, false).await;
    let sock = app.who("sock", 2, false).await;
    let c = app.category(None, None, None).await;
    // Unique per run, so runs sharing the database don't see each other.
    let n = (Uuid::now_v7().as_u128() % 200) as u8 + 20;
    let home = format!("198.51.{n}.7");
    let neighbour = format!("198.51.{n}.99");

    // Through nginx (127.0.0.1) and the ingress (10.x): the rightmost
    // untrusted hop, not the forged leftmost entry.
    let req = from_peer(login_request(&alice.user.username), "10.0.3.4", &[("x-forwarded-for", &format!("6.6.6.6, {home}, 10.0.0.2"))]);
    let (s, _, _) = app.send(req).await;
    assert_eq!(s, StatusCode::SEE_OTHER);
    assert_eq!(sightings(&app, alice.user.id).await, vec![(home.clone(), "sign_in".into(), 1)]);

    // A direct client can't claim an address: its header is ignored.
    let req = from_peer(login_request(&sock.user.username), &home, &[("x-forwarded-for", "6.6.6.6"), ("x-real-ip", "6.6.6.6")]);
    app.send(req).await;
    assert_eq!(sightings(&app, sock.user.id).await, vec![(home.clone(), "sign_in".into(), 1)]);
    let req = from_peer(login_request(&staff.user.username), "203.0.113.200", &[("x-forwarded-for", &home)]);
    app.send(req).await;
    assert!(sightings(&app, staff.user.id).await.iter().all(|(ip, _, _)| ip == "203.0.113.200"));

    // X-Real-IP from a trusted proxy that sends no X-Forwarded-For.
    let (topic, post) = app.topic(&alice, &c, "Hi").await;
    let req = Request::builder()
        .method("POST")
        .uri(format!("/api/v1/topics/{}/posts", topic.id))
        .header("authorization", format!("Bearer {}", sock.token))
        .header("content-type", "application/json")
        .body(Body::from(json!({"body": "me too"}).to_string()))
        .unwrap();
    let (s, _, _) = app.send(from_peer(req, "127.0.0.1", &[("x-real-ip", &neighbour)])).await;
    assert_eq!(s, StatusCode::CREATED);
    let seen = sightings(&app, sock.user.id).await;
    assert_eq!(seen[0].0, neighbour);
    assert_eq!(seen[0].1, "post", "the reply (app use is coalesced into the same row)");

    // A flag carries its address.
    let req = Request::builder()
        .method("POST")
        .uri(format!("/api/v1/posts/{}/flags", post.id))
        .header("authorization", format!("Bearer {}", sock.token))
        .header("content-type", "application/json")
        .body(Body::from(json!({"reason": "spam"}).to_string()))
        .unwrap();
    assert_eq!(app.send(from_peer(req, &home, &[])).await.0, StatusCode::CREATED);
    let flag = recourse::entities::post_flags::Entity::find()
        .filter(recourse::entities::post_flags::Column::PostId.eq(post.id))
        .one(app.db())
        .await
        .unwrap()
        .unwrap();
    assert_eq!(flag.ip.as_deref(), Some(home.as_str()));
    assert_eq!(recourse::ips::others_sharing(app.db(), alice.user.id).await.unwrap(), 1);

    // Staff: the queue says how many share; the user page's lookup lists
    // them (logged); the address page shows the /24 too (logged).
    moderation::flag_post(&app.state, &staff.user, post.id, "spam", None, None).await.unwrap();
    let (_, html) = app.page("/admin/flags", Some(&staff)).await;
    assert!(html.contains("1 other account shares an IP"));
    let (s, html) = app.page(&format!("/admin/users/{}/ips", alice.user.id), Some(&staff)).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains(&home) && html.contains(&sock.user.username));
    assert!(app.logged("view_ips", alice.user.id).await);
    let (s, html) = app.page(&format!("/admin/ips/{home}"), Some(&staff)).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains(&alice.user.username) && html.contains(&sock.user.username));
    assert!(html.contains(&format!("198.51.{n}.0&#x2f;24")) && html.contains(&neighbour), "the neighbour in the /24");
    let looked = moderation_log::Entity::find()
        .filter(moderation_log::Column::Action.eq("ip_lookup"))
        .filter(moderation_log::Column::TargetLabel.eq(home.clone()))
        .count(app.db())
        .await
        .unwrap();
    assert_eq!(looked, 1);

    // Nobody else sees any of it.
    for path in [format!("/admin/users/{}/ips", alice.user.id), format!("/admin/ips/{home}")] {
        assert_eq!(app.page(&path, Some(&alice)).await.0, StatusCode::FORBIDDEN, "{path}");
    }
    let (_, me) = app.api("GET", "/me", &alice, None).await;
    assert!(!me.to_string().contains(&home));
    let (_, html) = app.page("/profile", Some(&alice)).await;
    assert!(!html.contains(&home));
    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &alice, None).await;
    assert!(!page.to_string().contains(&home) && !page.to_string().contains(&neighbour));

    // Retention: rows not seen within the window go; flags keep no address.
    app.db()
        .execute_unprepared(&format!(
            "UPDATE user_ips SET last_seen = now() - interval '200 days' WHERE user_id = '{}'; \
             UPDATE post_flags SET created_at = now() - interval '200 days' WHERE id = '{}'",
            alice.user.id, flag.id
        ))
        .await
        .unwrap();
    assert!(recourse::ips::purge(app.db(), 180).await.unwrap() >= 1);
    assert!(sightings(&app, alice.user.id).await.is_empty());
    assert!(!sightings(&app, sock.user.id).await.is_empty());
    let flag = recourse::entities::post_flags::Entity::find_by_id(flag.id).one(app.db()).await.unwrap().unwrap();
    assert!(flag.ip.is_none());
}

#[tokio::test]
async fn off_site_links_go_through_the_signed_out_page() {
    let Some(app) = app().await else { return };
    let author = app.who("linker", 2, false).await;
    let c = app.category(None, None, None).await;
    let own = app.state.config.public_url.clone();
    let (topic, _) = app
        .topic(&author, &c, &format!("See [docs](https://docs.example/a?b=1&c=2), [ours]({own}/t/x), [rel](/c/), and https://xn--bcher-kva.example/kauf"))
        .await;
    let links = recourse::links::Links::from_config(&app.state.config);
    let sig = links.signer().sign("https://docs.example/a?b=1&c=2");

    // The topic page: off-site through /out, ours direct, all rel'd.
    let (_, html) = app.page(&format!("/t/{}", topic.id), None).await;
    assert!(html.contains(&format!("/out?u=https%3A%2F%2Fdocs.example%2Fa%3Fb%3D1%26c%3D2&amp;s={sig}")), "{html}");
    assert!(html.contains(&format!(r#"href="{own}/t/x""#)) && html.contains(r#"href="/c/""#));
    assert!(html.contains(r#"rel="nofollow ugc noopener noreferrer""#));
    assert!(!html.contains(r#"href="https://docs.example"#), "never direct");

    // The API: the same, absolute.
    let reader = app.who("reader", 1, false).await;
    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &reader, None).await;
    let cooked = page["posts"][0]["cooked"].as_str().unwrap();
    assert!(cooked.contains(&format!(r#"href="{own}/out?u=https%3A%2F%2Fdocs.example"#)), "{cooked}");

    // /out, signed out: where you're going, host emphasised, Continue.
    let out = format!("/out?u=https%3A%2F%2Fdocs.example%2Fa%3Fb%3D1%26c%3D2&s={sig}");
    let (s, html) = app.page(&out, None).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains(&format!("@ <span class=\"font-mono\">{}</span> to go to:", links.host())), "{html}");
    assert!(html.contains("<strong class=\"text-base-content text-base\">docs.example</strong>"));
    assert!(html.contains("data-continue") && !html.contains("data-unsigned"));
    assert!(!html.contains("http-equiv=\"refresh\""), "never by itself");

    // Altered destination, missing or wrong signature: text, warning, no Continue.
    for bad in [
        format!("/out?u=https%3A%2F%2Fevil.example%2F&s={sig}"),
        "/out?u=https%3A%2F%2Fdocs.example%2Fa%3Fb%3D1%26c%3D2".to_string(),
        "/out?u=https%3A%2F%2Fdocs.example%2Fa%3Fb%3D1%26c%3D2&s=00000000000000000000000000000000".to_string(),
        "/out?u=javascript%3Aalert(1)&s=00".to_string(),
        "/out".to_string(),
    ] {
        let (s, html) = app.page(&bad, None).await;
        assert_eq!(s, StatusCode::OK, "{bad}");
        assert!(html.contains("data-unsigned") && !html.contains("data-continue"), "{bad}");
    }

    // An IDN shows both forms.
    let idn = "https://xn--bcher-kva.example/kauf";
    let (_, html) = app.page(&format!("/out?u={}&s={}", "https%3A%2F%2Fxn--bcher-kva.example%2Fkauf", links.signer().sign(idn)), None).await;
    assert!(html.contains("data-idn") && html.contains("bücher.example") && html.contains("xn--bcher-kva.example"), "{html}");
}

#[tokio::test]
async fn anonymous_views_cannot_be_inflated_with_forged_forwarding_headers() {
    let Some(app) = app().await else { return };
    let alice = app.who("alice", 2, false).await;
    let c = app.category(None, None, None).await;
    let (topic, _) = app.topic(&alice, &c, "Count me once").await;
    let views = |app: &App| {
        let id = topic.id;
        let db = app.db().clone();
        async move { topics::Entity::find_by_id(id).one(&db).await.unwrap().unwrap().views }
    };
    let before = views(&app).await;
    let n = (Uuid::now_v7().as_u128() % 200) as u8 + 20;
    let visitor = format!("192.0.2.{n}");

    // A direct, untrusted visitor sends a different forged X-Forwarded-For
    // and X-Real-IP each time: still one viewer, one view this window.
    for i in 0..5 {
        let fake = format!("6.6.6.{i}");
        let req = Request::builder().uri(format!("/t/{}", topic.id)).body(Body::empty()).unwrap();
        let (s, _, _) = app
            .send(from_peer(req, &visitor, &[("x-forwarded-for", &fake), ("x-real-ip", &fake), ("x-recourse-client-ip", &fake)]))
            .await;
        assert_eq!(s, StatusCode::OK);
    }
    assert_eq!(views(&app).await, before + 1, "forged headers must not mint views");

    // A genuinely different client (through a trusted proxy) is a new viewer.
    let other = format!("198.51.{n}.33");
    let req = Request::builder().uri(format!("/t/{}", topic.id)).body(Body::empty()).unwrap();
    app.send(from_peer(req, "10.0.3.4", &[("x-forwarded-for", &other)])).await;
    assert_eq!(views(&app).await, before + 2);
}

/// The full category form, as staff would post it, with `extra` fields.
async fn save_category(app: &App, staff: &Who, c: &categories::Model, extra: &[(&str, &str)]) -> StatusCode {
    let mut form = vec![
        ("name", c.name.as_str()),
        ("slug", c.slug.as_str()),
        ("color", "#7c3aed"),
        ("min_trust_level", "public"),
        ("topic_rule", "viewers"),
        ("reply_rule", "viewers"),
    ];
    form.extend_from_slice(extra);
    app.form(&format!("/admin/categories/{}", c.id), Some(staff), &form).await.0
}

#[tokio::test]
async fn reactions_can_be_turned_off_or_narrowed_per_category() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("author", 2, false).await;
    let fan = app.who("fan", 2, false).await;
    let c = app.category(None, None, None).await;
    let (topic, post) = app.topic(&author, &c, "React to me").await;
    let react = |key: &'static str| {
        let path = format!("/posts/{}/reaction", post.id);
        let fan = &fan;
        let app = &app;
        async move { app.api("PUT", &path, fan, Some(json!({"key": key}))).await }
    };
    assert_eq!(react("heart").await.0, StatusCode::OK);
    let count = |page: &Value| page["posts"][0]["reactions"].as_array().unwrap().iter().map(|r| r["count"].as_i64().unwrap()).sum::<i64>();

    // Off: logged; refused on the API and the web; nothing shown anywhere.
    assert_eq!(save_category(&app, &staff, &c, &[("reactions", "none")]).await, StatusCode::SEE_OTHER);
    let log = moderation_log::Entity::find()
        .filter(moderation_log::Column::Action.eq("category_permissions"))
        .filter(moderation_log::Column::TargetId.eq(c.id))
        .one(app.db())
        .await
        .unwrap()
        .unwrap();
    let reason = log.reason.unwrap();
    assert!(reason.contains("reactions: all →") && reason.ends_with("reactions: off"), "{reason}");
    let (s, body) = react("star").await;
    assert_eq!((s, code(&body)), (StatusCode::FORBIDDEN, "reactions_off"));
    let (s, _, _) = app.form(&format!("/p/{}/react/star", post.id), Some(&fan), &[]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &fan, None).await;
    assert_eq!(page["can_react"], json!(false));
    assert!(page["posts"][0]["reactions"].as_array().unwrap().is_empty());
    let (_, cat) = app.api("GET", &format!("/categories/{}", c.slug), &fan, None).await;
    assert_eq!(cat["category"]["reactions"]["mode"], json!("none"));
    for path in [format!("/t/{}", topic.id), format!("/t/{}?view=focus", topic.id), format!("/c/{}?view=focus", c.slug), format!("/c/{}", c.slug)] {
        let (_, html) = app.page(&path, Some(&fan)).await;
        assert!(!html.contains("/react/") && !html.contains("❤️"), "{path}");
    }
    let (_, html) = app.page(&format!("/c/{}?view=focus", c.slug), Some(&fan)).await;
    assert!(html.contains("No reactions"), "the badge");
    let (_, html) = app.page("/reactions", Some(&fan)).await;
    assert!(!html.contains(&topic.title), "not on the Reacted page");
    let (_, notes) = app.api("GET", "/notifications", &author, None).await;
    assert!(notes["notifications"].as_array().unwrap().iter().all(|n| n["kind"] != json!("reaction")), "{notes}");

    // On again: the old reaction is back, and its notification.
    save_category(&app, &staff, &c, &[("reactions", "all")]).await;
    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &fan, None).await;
    assert_eq!(count(&page), 1);
    assert_eq!(page["can_react"], json!(true));
    let (_, notes) = app.api("GET", "/notifications", &author, None).await;
    assert!(notes["notifications"].as_array().unwrap().iter().any(|n| n["kind"] == json!("reaction")));
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&fan)).await;
    assert!(html.contains("/react/") && html.contains("emoji-tint"));

    // Only some: the others aren't offered (or shown).
    assert_eq!(save_category(&app, &staff, &c, &[("reactions", "some"), ("rk_star", "on"), ("rk_thumbsup", "on")]).await, StatusCode::SEE_OTHER);
    let (s, body) = react("heart").await;
    assert_eq!((s, code(&body)), (StatusCode::FORBIDDEN, "reaction_not_offered"));
    let (s, body) = react("star").await;
    assert_eq!(s, StatusCode::OK);
    let keys: Vec<&str> = body["reactions"].as_array().unwrap().iter().map(|r| r["key"].as_str().unwrap()).collect();
    assert_eq!(keys, ["star", "thumbsup"]);
    let (_, cat) = app.api("GET", &format!("/categories/{}", c.slug), &fan, None).await;
    assert_eq!(cat["category"]["reactions"], json!({"mode": "some", "keys": ["star", "thumbsup"]}));
    assert_eq!(save_category(&app, &staff, &c, &[("reactions", "some")]).await, StatusCode::OK, "none ticked: the form again");

    // A new subcategory starts with its parent's setting.
    save_category(&app, &staff, &c, &[("reactions", "none")]).await;
    let name = format!("Sub {}", tag());
    let (s, html, _) = app.form("/admin/categories/inline", Some(&staff), &[("name", &name), ("parent_id", &c.id.to_string())]).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains("No reactions"));
    let sub = categories::Entity::find().filter(categories::Column::Name.eq(&name)).one(app.db()).await.unwrap().unwrap();
    assert!(!sub.reactions_enabled);
    let (_, html, _) = app.form("/admin/categories/inline", Some(&staff), &[("name", &format!("{name}2")), ("parent_id", &c.id.to_string()), ("reactions", "all")]).await;
    assert!(!html.contains("No reactions"), "the inline add can change it");
}

#[tokio::test]
async fn the_inline_add_offers_the_parents_reactions() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let mut c: categories::ActiveModel = app.category(None, None, None).await.into();
    c.reaction_keys = Set(Some("star".into()));
    let c = c.update(app.db()).await.unwrap();
    let (s, html) = app.page(&format!("/admin/categories/slot?parent={}&form=1", c.id), Some(&staff)).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains(r#"<option value="some" selected>Only star (as the parent)</option>"#), "{html}");
    assert!(html.contains(r#"name="rk_star""#));
}

// --- the lameness filter -----------------------------------------------------

const WALL: &str = include_str!("fixtures/lameness_too_long.txt");

async fn reply_api(app: &App, who: &Who, topic: &topics::Model, body: &str) -> (StatusCode, Value) {
    app.api("POST", &format!("/topics/{}/posts", topic.id), who, Some(json!({"body": body}))).await
}

async fn holds_of(app: &App, post: Uuid) -> Vec<recourse::entities::post_holds::Model> {
    recourse::entities::post_holds::Entity::find()
        .filter(recourse::entities::post_holds::Column::PostId.eq(post))
        .all(app.db())
        .await
        .unwrap()
}

#[tokio::test]
async fn a_wall_of_repeats_is_held_for_review() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("waller", 1, false).await;
    let other = app.who("other", 2, false).await;
    let c = app.category(None, None, None).await;
    let (topic, _) = app.topic(&other, &c, "Talk about anything").await;

    // Through the API: saved, hidden, and the author is told why.
    let (s, post) = reply_api(&app, &author, &topic, WALL).await;
    assert_eq!(s, StatusCode::CREATED, "{post}");
    assert_eq!(post["hidden"], json!(true));
    let reasons = post["held"]["reasons"].as_array().unwrap();
    assert!(reasons.iter().any(|r| r.as_str().unwrap().contains("compresses to")), "{reasons:?}");
    let id: Uuid = post["id"].as_str().unwrap().parse().unwrap();
    assert!(app.logged("lameness_hold", id).await);

    // Others: hidden, no reasons, no text. The author and staff: the reasons.
    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &other, None).await;
    let theirs = page["posts"].as_array().unwrap().iter().find(|p| p["id"] == json!(id)).unwrap();
    assert_eq!((theirs["hidden"].clone(), theirs["cooked"].clone()), (json!(true), json!("")));
    assert!(theirs.get("held").is_none());
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&other)).await;
    assert!(html.contains("Hidden pending staff review.") && !html.contains("Held for review") && !html.contains("when the post is too long"));
    for (who, view) in [(&author, ""), (&author, "?view=focus"), (&staff, "")] {
        let (_, html) = app.page(&format!("/t/{}{view}", topic.id), Some(who)).await;
        assert!(html.contains("Held for review: it repeats itself"), "{view}");
    }

    // The queue shows it as the filter's, with the scores, in both layouts.
    for view in ["", "?view=focus"] {
        let (_, html) = app.page(&format!("/admin/flags{view}"), Some(&staff)).await;
        let at = html.find(&format!("flags-{id}")).unwrap_or_else(|| panic!("not queued {view}"));
        assert!(html[at..].contains("data-lameness-hold") && html[at..].contains("compression"), "{view}");
    }

    // Dismissed: a false positive. Shown again, no strike, logged.
    let (s, _, _) = app.form(&format!("/admin/flags/{id}/dismiss"), Some(&staff), &[]).await;
    assert!(s.is_success() || s.is_redirection(), "{s}");
    assert!(app.post(id).await.hidden_at.is_none());
    assert_eq!(holds_of(&app, id).await[0].resolution.as_deref(), Some("dismissed"));
    assert_eq!(moderation::strikes(app.db(), &app.state.config.lameness, author.user.id).await.unwrap(), 0);
    let log = moderation_log::Entity::find()
        .filter(moderation_log::Column::Action.eq("dismiss_flags"))
        .filter(moderation_log::Column::TargetId.eq(id))
        .one(app.db())
        .await
        .unwrap()
        .unwrap();
    assert!(log.reason.unwrap().contains("false positive"));

    // Edited back into a normal post: fine. Edited into junk again: held again.
    let (s, _, _) = app.form(&format!("/p/{id}"), Some(&author), &[("body", "Sorry, my cat sat on the paste key.")]).await;
    assert!(s.is_redirection(), "{s}");
    assert!(app.post(id).await.hidden_at.is_none());
    app.form(&format!("/p/{id}"), Some(&author), &[("body", &"Visit my channel for free stuff today\n".repeat(12))]).await;
    assert!(app.post(id).await.hidden_at.is_some(), "re-scored on edit");
    assert_eq!(holds_of(&app, id).await.len(), 2);
}

#[tokio::test]
async fn real_writing_and_staff_are_not_held_and_long_posts_are_refused() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("writer", 2, false).await;
    let c = app.category(None, None, None).await;
    let (topic, first) = app.topic(&author, &c, include_str!("../docs/android.md")).await;
    assert!(first.hidden_at.is_none());
    for body in recourse::seed::demo_post_bodies() {
        let (s, p) = reply_api(&app, &author, &topic, &body).await;
        assert_eq!((s, p["hidden"].clone()), (StatusCode::CREATED, json!(false)), "{body}");
    }
    let code_post = format!("Here's the module:\n\n```rust\n{}\n```", include_str!("../src/policy.rs"));
    let (s, _, _) = app.form(&format!("/t/{}/posts", topic.id), Some(&author), &[("body", &code_post)]).await;
    assert!(s.is_success() || s.is_redirection(), "{s}");
    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &author, None).await;
    assert!(page["posts"].as_array().unwrap().iter().all(|p| p["hidden"] == json!(false)));

    // Staff are scored but never held.
    let (_, p) = reply_api(&app, &staff, &topic, WALL).await;
    assert_eq!(p["hidden"], json!(false));

    // Over MAX_POST_CHARS: refused outright, web and API, with the sentence.
    let huge = "word ".repeat(7_000);
    let (s, body) = reply_api(&app, &author, &topic, &huge).await;
    assert_eq!((s, code(&body)), (StatusCode::PAYLOAD_TOO_LARGE, "too_long"));
    assert!(body["error"]["message"].as_str().unwrap().contains("at most 32000 characters"));
    let (s, text, _) = app.form(&format!("/t/{}/posts", topic.id), Some(&author), &[("body", &huge)]).await;
    assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);
    assert!(text.contains("at most 32000 characters"), "{text}");
    let (s, _, _) = app.form(&format!("/c/{}/topics", c.slug), Some(&author), &[("title", "Big"), ("body", &huge)]).await;
    assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&author)).await;
    assert!(html.contains(r#"maxlength="32000""#));
}

#[tokio::test]
async fn upheld_holds_climb_the_ladder_and_decay() {
    // No flood guard here: this is about the ladder.
    let Some(app) = app_with(|c| c.lameness.flood_holds = 1000).await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("spammer", 1, false).await;
    let c = app.category(None, None, None).await;
    let (topic, _) = app.topic(&staff, &c, "Open thread").await;
    let cfg = app.state.config.lameness.clone();
    let user = |app: &App| {
        let id = author.user.id;
        let db = app.db().clone();
        async move { users::Entity::find_by_id(id).one(&db).await.unwrap().unwrap() }
    };
    let mut until = Vec::new();
    for n in 1..=3 {
        moderation::lift(app.db(), Actor::cli(None), author.user.id, Sanction::Silence).await.unwrap();
        let (s, p) = reply_api(&app, &author, &topic, &format!("{n} {}", "BUY CHEAP PILLS NOW ".repeat(40))).await;
        assert_eq!((s, p["hidden"].clone()), (StatusCode::CREATED, json!(true)), "{p}");
        let id = p["id"].as_str().unwrap();
        // Upheld by deleting it (moderating does the same).
        let (s, _, _) = app.form(&format!("/admin/flags/{id}/delete"), Some(&staff), &[]).await;
        assert!(s.is_success() || s.is_redirection(), "{s}");
        assert_eq!(moderation::strikes(app.db(), &cfg, author.user.id).await.unwrap(), n);
        until.push(user(&app).await.silenced_until.map(|u| (u.with_timezone(&Utc) - Utc::now()).num_minutes()));
    }
    // 1: a warning; 2: an hour read-only; 3: a day. Told why, logged.
    assert_eq!(until[0], None);
    assert!(until[1].is_some_and(|m| (58..=60).contains(&m)), "{until:?}");
    assert!(until[2].is_some_and(|m| (60 * 24 - 2..=60 * 24).contains(&m)), "{until:?}");
    let u = user(&app).await;
    assert!(u.silence_reason.unwrap().starts_with("Automatic: 3 post(s) held"));
    assert!(app.logged("lameness_strike", author.user.id).await);
    let (_, html) = app.page(&format!("/admin/users/{}", author.user.id), Some(&staff)).await;
    assert!(html.contains("<strong>3</strong> strikes") && html.contains("7 days read-only"), "next step shown");

    // Strikes older than LAMENESS_STRIKE_DAYS don't count.
    let old: chrono::DateTime<chrono::FixedOffset> = (Utc::now() - chrono::Duration::days(cfg.strike_days + 1)).into();
    let first = recourse::entities::post_holds::Entity::find()
        .filter(recourse::entities::post_holds::Column::UserId.eq(author.user.id))
        .order_by_asc(recourse::entities::post_holds::Column::CreatedAt)
        .one(app.db())
        .await
        .unwrap()
        .unwrap();
    let mut am: recourse::entities::post_holds::ActiveModel = first.into();
    am.resolved_at = Set(Some(old));
    am.update(app.db()).await.unwrap();
    assert_eq!(moderation::strikes(app.db(), &cfg, author.user.id).await.unwrap(), 2);

    // Staff clear them from the user page; logged.
    let (s, html, _) = app.form(&format!("/admin/users/{}/clear-strikes", author.user.id), Some(&staff), &[("mode", "focus")]).await;
    assert_eq!(s, StatusCode::OK);
    assert!(!html.contains("data-status=\"strikes\""));
    assert_eq!(moderation::strikes(app.db(), &cfg, author.user.id).await.unwrap(), 0);
    assert!(app.logged("clear_strikes", author.user.id).await);

    // At the top of the ladder: suspended pending staff review.
    let step = cfg.step(cfg.ladder.len());
    assert_eq!(step, recourse::lameness::Step::Suspend);
}

#[tokio::test]
async fn a_flood_of_holds_gets_a_cooldown_before_review() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("flooder", 1, false).await;
    let c = app.category(None, None, None).await;
    let (topic, _) = app.topic(&staff, &c, "Open thread").await;
    for n in 0..3 {
        let (s, _) = reply_api(&app, &author, &topic, &format!("{n}{}", "!".repeat(80))).await;
        assert_eq!(s, StatusCode::CREATED);
    }
    let (s, body) = reply_api(&app, &author, &topic, "Now a normal post.").await;
    assert_eq!(s, StatusCode::FORBIDDEN, "read-only after three holds in an hour: {body}");
    let u = users::Entity::find_by_id(author.user.id).one(app.db()).await.unwrap().unwrap();
    assert!(u.silence_reason.unwrap().contains("3 posts held for review within 1 hour"));
    assert_eq!(moderation::strikes(app.db(), &app.state.config.lameness, author.user.id).await.unwrap(), 0, "no strike without review");
}

#[tokio::test]
async fn search_needs_three_characters() {
    let Some(app) = app().await else { return };
    let who = app.who("seeker", 1, false).await;
    for view in ["", "&view=focus"] {
        let (s, html) = app.page(&format!("/search?q=ab{view}"), Some(&who)).await;
        assert_eq!(s, StatusCode::OK);
        assert!(html.contains("Type at least 3 characters"), "{view}");
        assert!(html.contains(r#"minlength="3""#), "{view}");
    }
}

#[tokio::test]
async fn a_held_opening_post_hides_its_topic_from_everyone_but_author_and_staff() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("op", 1, false).await;
    let other = app.who("other", 2, false).await;
    let c = app.category(None, None, None).await;
    let word = format!("Zebrafish{}", tag().replace('-', ""));
    let tag_name = format!("t{}", &tag()[..6]);
    let title = format!("{word} care");

    // Visible at first: the other user watches the category (a notification
    // naming it), bookmarks and reacts to it.
    let (s, _) = app.api("PUT", &format!("/categories/{}/watch", c.slug), &other, Some(json!({"watching": true}))).await;
    assert!(s.is_success(), "{s}");
    let (s, created) = app
        .api("POST", &format!("/categories/{}/topics", c.slug), &author,
            Some(json!({"title": title, "body": "How often should I feed them?", "tags": [tag_name]})))
        .await;
    assert_eq!(s, StatusCode::CREATED, "{created}");
    let topic_id = created["id"].as_str().or(created["topic"]["id"].as_str()).unwrap().to_string();
    let topic = topics::Entity::find_by_id(topic_id.parse::<Uuid>().unwrap()).one(app.db()).await.unwrap().unwrap();
    let op = posts::Entity::find()
        .filter(posts::Column::TopicId.eq(topic.id))
        .filter(posts::Column::PostNumber.eq(1))
        .one(app.db())
        .await
        .unwrap()
        .unwrap();
    app.api("PUT", &format!("/posts/{}/bookmark", op.id), &other, Some(json!({"bookmarked": true}))).await;
    app.api("PUT", &format!("/posts/{}/reaction", op.id), &other, Some(json!({"key": "heart"}))).await;
    let count = |cats: &Value| {
        cats["categories"].as_array().unwrap().iter().find(|x| x["slug"] == json!(c.slug)).unwrap()["topic_count"].as_i64().unwrap()
    };
    let (_, cats) = app.api("GET", "/categories", &other, None).await;
    let before = count(&cats);
    for path in ["/bookmarks", "/notifications", "/reactions"] {
        assert!(app.page(path, Some(&other)).await.1.contains(&title), "{path} before the hold");
    }

    // The author edits the opening post into junk: held, and the topic with it.
    app.form(&format!("/p/{}", op.id), Some(&author), &[("body", WALL)]).await;
    let topic = topics::Entity::find_by_id(topic.id).one(app.db()).await.unwrap().unwrap();
    assert!(topic.held_at.is_some());

    let web = [
        "/".to_string(), "/?view=focus".into(), "/p/latest".into(), "/p/popular".into(), "/p/latest?view=focus".into(),
        format!("/c/{}", c.slug), format!("/c/{}?view=focus", c.slug), "/c/".into(), "/c/?view=focus".into(),
        format!("/tag/{tag_name}"), format!("/tag/{tag_name}?view=focus"), "/tags".into(), "/tags?view=focus".into(),
        format!("/search?q={word}"), format!("/search?q={word}&view=focus"),
        "/reactions".into(), "/reactions?view=focus".into(),
    ];
    for who in [None, Some(&other)] {
        for path in &web {
            let (s, html) = app.page(path, who).await;
            // A tag only the held topic uses isn't there for them at all.
            if path.starts_with("/tag/") && s == StatusCode::NOT_FOUND {
                continue;
            }
            assert!(s.is_success(), "{path} {s}");
            assert!(!html.contains(&title), "{path} shows the held topic to {:?}", who.map(|w| &w.user.username));
            if path.starts_with("/tags") && !path.contains(&tag_name) {
                assert!(!html.contains(&tag_name), "{path}: the tag is only on the held topic");
            }
        }
        for path in [format!("/t/{}", topic.id), format!("/t/{}?view=focus", topic.id), format!("/p/{}/history", op.id)] {
            assert_eq!(app.page(&path, who).await.0, StatusCode::NOT_FOUND, "{path}");
        }
    }
    for path in ["/bookmarks", "/bookmarks?view=focus", "/notifications", "/notifications?view=focus"] {
        let (_, html) = app.page(path, Some(&other)).await;
        assert!(!html.contains(&title), "{path}");
    }
    for path in [
        format!("/categories/{}", c.slug), format!("/tags/{tag_name}"), format!("/search?q={word}"),
        "/bookmarks".into(), "/notifications".into(),
    ] {
        let (_, body) = app.api("GET", &path, &other, None).await;
        assert!(!body.to_string().contains(&title), "api {path}: {body}");
    }
    let (s, body) = app.api("GET", &format!("/topics/{}", topic.id), &other, None).await;
    assert_eq!((s, code(&body)), (StatusCode::NOT_FOUND, "not_found"));
    let (s, _) = app.api("POST", &format!("/topics/{}/posts", topic.id), &other, Some(json!({"body": "hello?"}))).await;
    assert_eq!(s, StatusCode::NOT_FOUND);
    let (_, cats) = app.api("GET", "/categories", &other, None).await;
    assert_eq!(count(&cats), before - 1, "counts don't leak it");

    // The author: listed with a badge, and the topic says why.
    for path in [format!("/c/{}", c.slug), format!("/c/{}?view=focus", c.slug), "/p/latest".into()] {
        let (_, html) = app.page(&path, Some(&author)).await;
        assert!(html.contains(&title) && html.contains("data-held-badge") && html.contains("Held for review"), "{path}");
    }
    for path in [format!("/t/{}", topic.id), format!("/c/{}?view=focus&topic={}", c.slug, topic.id)] {
        let (s, html) = app.page(&path, Some(&author)).await;
        assert_eq!(s, StatusCode::OK, "{path}");
        assert!(html.contains("data-held-topic") && html.contains("Held for review: it repeats itself"), "{path}");
    }
    // Staff: a "Held" badge and the queue item.
    let (_, html) = app.page(&format!("/c/{}", c.slug), Some(&staff)).await;
    assert!(html.contains(&title) && html.contains("data-held-badge"));
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&staff)).await;
    assert!(html.contains(&format!("/admin/flags#flags-{}", op.id)));

    // Dismissed: visible everywhere again.
    app.form(&format!("/admin/flags/{}/dismiss", op.id), Some(&staff), &[]).await;
    assert!(topics::Entity::find_by_id(topic.id).one(app.db()).await.unwrap().unwrap().held_at.is_none());
    for path in [format!("/c/{}", c.slug), "/p/latest".into(), format!("/search?q={word}")] {
        assert!(app.page(&path, None).await.1.contains(&title), "{path}");
    }
    assert_eq!(app.page(&format!("/t/{}", topic.id), Some(&other)).await.0, StatusCode::OK);
    let (_, cats) = app.api("GET", "/categories", &other, None).await;
    assert_eq!(count(&cats), before);

    // A held reply hides only itself.
    let (s, p) = reply_api(&app, &other, &topic, WALL).await;
    assert_eq!((s, p["hidden"].clone()), (StatusCode::CREATED, json!(true)));
    assert!(topics::Entity::find_by_id(topic.id).one(app.db()).await.unwrap().unwrap().held_at.is_none());
    assert!(app.page(&format!("/c/{}", c.slug), None).await.1.contains(&title));
    assert_eq!(app.page(&format!("/t/{}", topic.id), None).await.0, StatusCode::OK);
}

#[tokio::test]
async fn upholding_a_held_opening_post() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("op", 1, false).await;
    let c = app.category(None, None, None).await;
    // Moderated: the staff note replaces it and the topic is visible again.
    let (t1, p1) = app.topic(&author, &c, WALL).await;
    assert!(topics::Entity::find_by_id(t1.id).one(app.db()).await.unwrap().unwrap().held_at.is_some());
    assert_eq!(app.page(&format!("/t/{}", t1.id), None).await.0, StatusCode::NOT_FOUND);
    let (s, _, _) = app.form(&format!("/admin/flags/{}/moderate", p1.id), Some(&staff), &[("note", "Removed: a wall of repeats.")]).await;
    assert!(s.is_success() || s.is_redirection(), "{s}");
    let (s, html) = app.page(&format!("/t/{}", t1.id), None).await;
    assert_eq!(s, StatusCode::OK);
    assert!(html.contains("Removed: a wall of repeats."));
    // Deleted: the topic goes with it.
    let (t2, p2) = app.topic(&author, &c, &"Visit my channel for free stuff today\n".repeat(12)).await;
    app.form(&format!("/admin/flags/{}/delete", p2.id), Some(&staff), &[]).await;
    let t2 = topics::Entity::find_by_id(t2.id).one(app.db()).await.unwrap().unwrap();
    assert!(t2.deleted_at.is_some() && t2.held_at.is_none());
    assert!(app.logged("delete_topic", t2.id).await);
}

// --- link previews (src/meta.rs) ------------------------------------------------

/// `<head>` only, without `<title>`: the preview tags an unfurler reads.
/// (`<title>` is the reader's browser tab; a scraper never has the session
/// that shows it the topic.)
fn head(page: &str) -> String {
    let h = &page[..page.find("</head>").expect("a <head>")];
    match (h.find("<title>"), h.find("</title>")) {
        (Some(a), Some(b)) => format!("{}{}", &h[..a], &h[b..]),
        _ => h.to_string(),
    }
}

/// The `content` of `<meta property|name="{key}">`.
fn meta_of<'a>(page: &'a str, key: &str) -> Option<&'a str> {
    let h = &page[..page.find("</head>")?];
    let at = h.find(&format!("property=\"{key}\"")).or_else(|| h.find(&format!("name=\"{key}\"")))?;
    let rest = &h[at..];
    let start = rest.find("content=\"")? + "content=\"".len();
    Some(&rest[start..start + rest[start..].find('"')?])
}

async fn retitle(app: &App, t: &topics::Model, title: &str) -> topics::Model {
    let mut am: topics::ActiveModel = t.clone().into();
    am.title = Set(title.to_string());
    am.update(app.db()).await.unwrap()
}

#[tokio::test]
async fn a_public_topic_unfurls_with_its_title_excerpt_and_absolute_urls() {
    let Some(app) = app_with(|c| c.public_url = "https://forum.example".into()).await else { return };
    let author = app.who("writer", 1, false).await;
    let c = app.category(None, None, None).await;
    let body = format!(
        "## Feeding\n\nGive them **{}** a day, [see here](https://x.test). ![tank](/assets/img/tank.png)\n\n```\nnot this\n```\n\n{}",
        "two meals",
        (0..60).map(|i| format!("w{i}x")).collect::<Vec<_>>().join(" ")
    );
    let (t, _) = app.topic(&author, &c, &body).await;
    let t = retitle(&app, &t, "Zebrafish care").await;

    // Classic and Focus alike.
    for path in [format!("/t/{}", t.id), format!("/t/{}?view=focus", t.id)] {
        let (s, page) = app.page(&path, None).await;
        assert_eq!(s, StatusCode::OK, "{path}");
        let url = format!("https://forum.example/t/{}", t.id);
        assert_eq!(meta_of(&page, "og:title"), Some("Zebrafish care"), "{path}");
        assert_eq!(meta_of(&page, "og:type"), Some("article"));
        assert_eq!(meta_of(&page, "og:url"), Some(url.as_str()));
        assert!(head(&page).contains(&format!("<link rel=\"canonical\" href=\"{url}\"/>")));
        // Our own image, made absolute.
        assert_eq!(meta_of(&page, "og:image"), Some("https://forum.example/assets/img/tank.png"));
        assert_eq!(meta_of(&page, "twitter:card"), Some("summary"));
        assert_eq!(meta_of(&page, "article:section"), Some(c.name.as_str()));
        assert_eq!(meta_of(&page, "author"), Some(author.user.username.as_str()));
        assert!(meta_of(&page, "article:published_time").is_some());
        let d = meta_of(&page, "og:description").unwrap();
        assert!(d.starts_with("Feeding Give them two meals a day, see here."), "{d}");
        assert!(!d.contains("**") && !d.contains("not this") && !d.contains("]("), "{d}");
        assert!(d.ends_with('…') && d.chars().count() <= 200, "{d}");
        assert!(d.trim_end_matches('…').rsplit(' ').next().unwrap().ends_with('x'), "cut mid-word: {d}");
        assert_eq!(meta_of(&page, "description"), Some(d));
        assert_eq!(meta_of(&page, "robots"), Some("index, follow"));
    }

    // No image of ours: the 512px site mark, with its size.
    let (t2, _) = app.topic(&author, &c, "Look ![x](https://elsewhere.example/x.png)").await;
    let (_, page) = app.page(&format!("/t/{}", t2.id), None).await;
    assert_eq!(meta_of(&page, "og:image"), Some("https://forum.example/assets/img/site-mark.png"));
    assert_eq!(meta_of(&page, "og:image:width"), Some("512"));

    // A permalink 303s to the topic, whose card is the topic's (og:url
    // without the #post anchor).
    let (_, p) = app.topic(&author, &c, "first").await;
    let r = recourse::actions::reply(&app.state, &author.user, p.topic_id, "a reply").await;
    if let Ok(reply) = r {
        let (s, _, loc) = app.send(Request::builder().uri(format!("/p/{}", reply.id)).body(Body::empty()).unwrap()).await;
        assert_eq!(s, StatusCode::SEE_OTHER);
        let loc = loc.unwrap();
        let (_, page) = app.page(&loc, None).await;
        assert_eq!(meta_of(&page, "og:url").unwrap(), format!("https://forum.example/t/{}", p.topic_id));
    }
}

#[tokio::test]
async fn closed_categories_held_and_moderated_topics_unfurl_generically() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let member = app.who("member", 3, false).await;
    let author = app.who("writer", 1, false).await;
    let secret = format!("Secretive{}", tag());

    // Members-only (trust 0 = any signed-in user), trust-gated, staff-only.
    for view in [Some(0), Some(2), Some(STAFF_ONLY)] {
        let c = app.category(view, None, None).await;
        let (t, _) = app.topic(&staff, &c, &format!("{secret} body")).await;
        let t = retitle(&app, &t, &format!("{secret} title")).await;
        // Anonymous, and a member who can read it: the card is built as
        // anonymous either way.
        for who in [None, Some(&member), Some(&staff)] {
            let (s, page) = app.page(&format!("/t/{}", t.id), who).await;
            if s != StatusCode::OK {
                continue;
            }
            let h = head(&page);
            assert!(!h.contains(&secret), "{view:?} leaks into <head> for {:?}", who.map(|w| &w.user.username));
            assert!(meta_of(&page, "og:title").unwrap().starts_with("A members-only discussion"));
            assert_eq!(meta_of(&page, "robots"), Some("noindex, nofollow"));
        }
        // The category's own page too.
        let (_, page) = app.page(&format!("/c/{}", c.slug), Some(&staff)).await;
        assert!(!head(&page).contains(&secret));
        assert!(meta_of(&page, "og:title").unwrap().starts_with("A members-only category"), "{view:?}");
    }

    // Held: 404 for anonymous; author and staff see the page, but a generic card.
    let open = app.category(None, None, None).await;
    let (t, _) = app.topic(&author, &open, &format!("{secret} held body")).await;
    let t = retitle(&app, &t, &format!("{secret} held")).await;
    let mut am: topics::ActiveModel = t.clone().into();
    am.held_at = Set(Some(Utc::now().into()));
    am.update(app.db()).await.unwrap();
    let (s, _) = app.page(&format!("/t/{}", t.id), None).await;
    assert_eq!(s, StatusCode::NOT_FOUND);
    for who in [&author, &staff] {
        let (s, page) = app.page(&format!("/t/{}", t.id), Some(who)).await;
        assert_eq!(s, StatusCode::OK);
        assert!(!head(&page).contains(&secret), "held topic leaks for {}", who.user.username);
    }

    // Moderated opening post: the staff note, never the original.
    let (t, op) = app.topic(&author, &open, &format!("{secret} original insult")).await;
    moderation::moderate_post(&app.state, Actor::web(&staff.user), op.id, "Removed: off topic.", false)
        .await
        .unwrap();
    let (_, page) = app.page(&format!("/t/{}", t.id), None).await;
    assert_eq!(meta_of(&page, "og:description"), Some("Removed: off topic."));
    assert!(!head(&page).contains("original insult"));

    // Deleted topic: the tombstone has a generic card.
    let (t, _) = app.topic(&author, &open, &format!("{secret} doomed")).await;
    let mut am: topics::ActiveModel = t.clone().into();
    am.deleted_at = Set(Some(Utc::now().into()));
    am.update(app.db()).await.unwrap();
    let (_, page) = app.page(&format!("/t/{}", t.id), None).await;
    assert!(!head(&page).contains(&secret));
}

#[tokio::test]
async fn titles_are_escaped_in_meta_attributes() {
    let Some(app) = app().await else { return };
    let author = app.who("writer", 1, false).await;
    let c = app.category(None, None, None).await;
    let (t, _) = app.topic(&author, &c, "Body with \"quotes\" & <b>tags</b>").await;
    retitle(&app, &t, r#"Say "hi" <script>alert(1)</script>"#).await;
    let (_, page) = app.page(&format!("/t/{}", t.id), None).await;
    let h = head(&page);
    assert!(!h.contains("<script>alert"), "raw script in <head>");
    assert!(h.contains(r#"<meta property="og:title" content="Say &quot;hi&quot; &lt;script&gt;alert(1)&lt;/script&gt;"/>"#), "{h}");
    assert!(h.contains("Body with &quot;quotes&quot; &amp; tags"), "{h}");
}

#[tokio::test]
async fn list_pages_summarise_and_private_pages_are_noindex() {
    let Some(app) = app().await else { return };
    let author = app.who("writer", 1, false).await;
    let staff = app.who("staff", 4, true).await;
    let c = app.category(None, None, None).await;
    let mut titles = vec![];
    for i in 0..5 {
        let (t, _) = app.topic(&author, &c, "body").await;
        let title = format!("Listed {i} {}", tag());
        retitle(&app, &t, &title).await;
        titles.push(title);
    }
    // Hidden from anonymous: never named in a list card.
    let closed = app.category(Some(0), None, None).await;
    let (t, _) = app.topic(&author, &closed, "body").await;
    let hidden = format!("Unlisted {}", tag());
    retitle(&app, &t, &hidden).await;

    // A category: "N topics: A, B, C and K more."
    let (_, page) = app.page(&format!("/c/{}", c.slug), Some(&author)).await;
    assert_eq!(meta_of(&page, "og:title"), Some(c.name.as_str()));
    let d = meta_of(&page, "og:description").unwrap();
    assert!(d.starts_with("5 topics: ") && d.ends_with(" and 2 more."), "{d}");
    // With a description, that instead.
    let mut am: categories::ActiveModel = c.clone().into();
    am.description = Set(Some("All about fish.".into()));
    am.update(app.db()).await.unwrap();
    let (_, page) = app.page(&format!("/c/{}", c.slug), None).await;
    assert_eq!(meta_of(&page, "og:description"), Some("All about fish."));

    for path in ["/", "/c/", "/p/latest", "/p/popular", "/tags", "/?view=focus", "/p/latest?view=focus"] {
        let (s, page) = app.page(path, Some(&staff)).await;
        assert_eq!(s, StatusCode::OK, "{path}");
        assert_eq!(meta_of(&page, "robots"), Some("index, follow"), "{path}");
        assert!(meta_of(&page, "og:url").is_some(), "{path}");
        assert!(!head(&page).contains(&hidden), "{path} names a members-only topic");
    }
    let (_, page) = app.page("/p/latest", None).await;
    assert!(meta_of(&page, "og:description").unwrap().starts_with("The newest activity: "));

    // The Focus reader's URL carries the opened topic's card.
    let (_, page) = app.page(&format!("/p/latest?view=focus&topic={}", t.id), Some(&staff)).await;
    assert!(!head(&page).contains(&hidden));
    let open = topics::Entity::find().filter(topics::Column::Title.eq(titles[0].clone())).one(app.db()).await.unwrap().unwrap();
    let (_, page) = app.page(&format!("/?view=focus&topic={}", open.id), None).await;
    assert_eq!(meta_of(&page, "og:title"), Some(titles[0].as_str()));

    // No card: noindex with the site defaults.
    for (path, who) in [
        ("/login", None),
        ("/profile", Some(&author)),
        ("/devices", Some(&author)),
        ("/bookmarks", Some(&author)),
        ("/notifications", Some(&author)),
        ("/admin/flags", Some(&staff)),
        ("/search?q=Listed", None),
    ] {
        let (s, page) = app.page(path, who).await;
        if s != StatusCode::OK {
            panic!("{path}: {s}");
        }
        assert_eq!(meta_of(&page, "robots"), Some("noindex, nofollow"), "{path}");
        assert!(meta_of(&page, "og:url").is_none(), "{path}");
    }
}

// --- open registration (src/registration.rs) ------------------------------------

/// The registration form's stamp, as served.
async fn register_stamp(app: &App) -> String {
    let (s, page) = app.page("/register", None).await;
    assert_eq!(s, StatusCode::OK, "/register");
    let at = page.find(r#"name="stamp" value=""#).expect("a stamp") + r#"name="stamp" value=""#.len();
    page[at..at + page[at..].find('"').unwrap()].to_string()
}

/// POST /auth/register from `ip`: (status, body, session cookie).
async fn register(app: &App, ip: [u8; 4], fields: &[(&str, &str)]) -> (StatusCode, String, Option<String>) {
    let body = fields.iter().map(|(k, v)| format!("{k}={}", urlencode(v))).collect::<Vec<_>>().join("&");
    let mut req = Request::builder()
        .method("POST")
        .uri("/auth/register")
        .header("content-type", "application/x-www-form-urlencoded")
        .body(Body::from(body))
        .unwrap();
    req.extensions_mut().insert(ConnectInfo(SocketAddr::from((ip, 40000))));
    let res = app.router.clone().oneshot(req).await.unwrap();
    let status = res.status();
    let cookie = res
        .headers()
        .get("set-cookie")
        .and_then(|v| v.to_str().ok())
        .and_then(|c| c.strip_prefix("session_token="))
        .map(|c| c.split(';').next().unwrap().to_string());
    let bytes = axum::body::to_bytes(res.into_body(), 1 << 22).await.unwrap();
    (status, String::from_utf8_lossy(&bytes).into_owned(), cookie)
}

/// A fresh client address in the benchmarking range (198.18.0.0/15, 2^17
/// of them), so the per-address limit of one test never meets another's.
fn test_ip() -> [u8; 4] {
    let b = Uuid::now_v7().as_bytes()[13..16].to_vec();
    [198, 18 + (b[0] & 1), b[1], b[2]]
}

async fn signup(app: &App, ip: [u8; 4], name: &str, stamp: &str, extra: &[(&str, &str)]) -> (StatusCode, String, Option<String>) {
    let email = format!("{name}@example.test");
    let mut f: Vec<(&str, &str)> = vec![
        ("username", name),
        ("email", &email),
        ("password", PASSWORD),
        ("confirm_password", PASSWORD),
        ("stamp", stamp),
        ("website", ""),
    ];
    f.extend_from_slice(extra);
    register(app, ip, &f).await
}

#[tokio::test]
async fn open_registration_needs_no_invite_and_starts_unverified() {
    let Some(app) = app_with(|c| {
        c.registration_enabled = true;
        c.registration.min_fill_secs = 0;
    })
    .await
    else {
        return;
    };
    // The open form has no invite field.
    let (_, page) = app.page("/register", None).await;
    assert!(!page.contains(r#"name="registration_token""#));
    assert!(!page.contains("still need a valid invite"));

    let name = format!("open{}", tag());
    let stamp = register_stamp(&app).await;
    let (s, body, cookie) = signup(&app, test_ip(), &name, &stamp, &[]).await;
    assert_eq!(s, StatusCode::SEE_OTHER, "{body}");
    let cookie = cookie.expect("signed in");
    let user = users::Entity::find().filter(users::Column::Username.eq(&name)).one(app.db()).await.unwrap().unwrap();
    assert!(user.email_verified_at.is_none());
    assert!(!user.is_staff);
    assert_eq!(user.trust_level, 0);

    // Mailed a verification link, logged for staff.
    let mail = app.outbox.lock().unwrap().iter().find(|m| m.to == user.email).cloned().expect("verification mail");
    assert!(mail.body.contains("/verify-email?token="), "{}", mail.body);
    assert!(app.logged("register", user.id).await);

    // Reads, with the banner; can't write.
    let who = Who { user: user.clone(), cookie, token: String::new() };
    let (s, home) = app.page("/", Some(&who)).await;
    assert_eq!(s, StatusCode::OK);
    assert!(home.contains(r#"id="verify-banner""#));
    let c = app.category(None, None, None).await;
    let (s, _, _) = app.form(&format!("/c/{}/topics", c.slug), Some(&who), &[("title", "hello there"), ("body", "first!")]).await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    // The banner's resend is throttled right after the first mail, and works.
    let (s, _, _) = app.form("/verify-email/resend", Some(&who), &[]).await;
    assert!(s.is_redirection(), "{s}");

    // Following the link verifies; then writing works.
    let link = &mail.body[mail.body.find("/verify-email?token=").unwrap()..];
    let link = link.split_whitespace().next().unwrap();
    let (s, _) = app.page(link, None).await;
    assert!(s.is_success() || s.is_redirection(), "{s}");
    let user = users::Entity::find_by_id(user.id).one(app.db()).await.unwrap().unwrap();
    assert!(user.email_verified_at.is_some());

    // A taken name re-renders the form with what was typed.
    let (s, body, _) = signup(&app, test_ip(), &name, &stamp, &[]).await;
    assert_eq!(s, StatusCode::CONFLICT);
    assert!(body.contains("already registered") && body.contains(&format!(r#"value="{name}""#)));
}

#[tokio::test]
async fn invites_still_work_open_or_closed_and_closed_needs_one() {
    for open in [true, false] {
        let Some(app) = app_with(|c| {
            c.registration_enabled = open;
            c.registration.min_fill_secs = 0;
            c.registration.per_ip_per_day = 1;
        })
        .await
        else {
            return;
        };
        let ip = test_ip();
        // Pinned to an email: only that address redeems it.
        let name = format!("inv{}", tag());
        let email = format!("{name}@example.test");
        let invite = auth::create_registration_token(app.db(), None, Some(email.clone()), 7).await.unwrap();
        let (s, _) = app.page(&format!("/register?token={}", invite.token), None).await;
        assert_eq!(s, StatusCode::OK);
        let (s, body, _) = signup(&app, ip, &format!("x{name}"), "", &[("registration_token", &invite.token)]).await;
        assert_eq!(s, StatusCode::BAD_REQUEST, "wrong email, open={open}");
        assert!(body.contains("invalid, expired"));
        // No stamp or honeypot needed with an invite, and no per-address limit.
        for _ in 0..2 {
            let n = format!("inv{}", tag());
            let inv = auth::create_registration_token(app.db(), None, None, 7).await.unwrap();
            let (s, body, _) = signup(&app, ip, &n, "", &[("registration_token", &inv.token)]).await;
            assert_eq!(s, StatusCode::SEE_OTHER, "open={open}: {body}");
            let inv = recourse::entities::registration_tokens::Entity::find_by_id(inv.id).one(app.db()).await.unwrap().unwrap();
            assert!(inv.is_used && inv.used_by_user_id.is_some());
        }
        let (s, _, _) = signup(&app, ip, &name, "", &[("registration_token", &invite.token)]).await;
        assert_eq!(s, StatusCode::SEE_OTHER, "pinned invite, open={open}");

        if !open {
            // Closed: no form without an invite, and no account without one.
            assert_eq!(app.page("/register", None).await.0, StatusCode::NOT_FOUND);
            let n = format!("noinv{}", tag());
            let (s, _, _) = signup(&app, test_ip(), &n, &recourse::registration::stamp(&app.state.config), &[]).await;
            assert_eq!(s, StatusCode::NOT_FOUND);
            assert!(users::Entity::find().filter(users::Column::Username.eq(&n)).one(app.db()).await.unwrap().is_none());
        }
    }
}

#[tokio::test]
async fn open_signups_are_limited_per_address_and_screen_out_bots() {
    let Some(app) = app_with(|c| {
        c.registration_enabled = true;
        c.registration.min_fill_secs = 0;
        c.registration.per_ip_per_day = 2;
    })
    .await
    else {
        return;
    };
    let ip = test_ip();
    let stamp = register_stamp(&app).await;
    for _ in 0..2 {
        let (s, body, _) = signup(&app, ip, &format!("lim{}", tag()), &stamp, &[]).await;
        assert_eq!(s, StatusCode::SEE_OTHER, "{body}");
    }
    let third = format!("lim{}", tag());
    let (s, body, _) = signup(&app, ip, &third, &stamp, &[]).await;
    assert_eq!(s, StatusCode::TOO_MANY_REQUESTS);
    assert!(body.contains("Too many accounts"));
    assert!(users::Entity::find().filter(users::Column::Username.eq(&third)).one(app.db()).await.unwrap().is_none());
    // Another address is fine.
    let (s, _, _) = signup(&app, test_ip(), &third, &stamp, &[]).await;
    assert_eq!(s, StatusCode::SEE_OTHER);

    // The honeypot, a forged stamp, no stamp.
    for (extra, what) in [
        (vec![("website", "http://spam.example")], "honeypot"),
        (vec![("stamp", "1800000000.00112233445566778899aabbccddeeff")], "forged stamp"),
    ] {
        let n = format!("bot{}", tag());
        let email = format!("{n}@example.test");
        let mut fields: Vec<(&str, &str)> =
            vec![("username", &n), ("email", &email), ("password", PASSWORD), ("confirm_password", PASSWORD)];
        if what == "honeypot" {
            fields.push(("stamp", &stamp));
        }
        fields.extend(extra);
        let (s, _, _) = register(&app, test_ip(), &fields).await;
        assert_eq!(s, StatusCode::BAD_REQUEST, "{what}");
        assert!(users::Entity::find().filter(users::Column::Username.eq(&n)).one(app.db()).await.unwrap().is_none(), "{what}");
    }
}

#[tokio::test]
async fn a_form_sent_back_too_fast_is_refused() {
    let Some(app) = app_with(|c| {
        c.registration_enabled = true;
        c.registration.min_fill_secs = 30;
    })
    .await
    else {
        return;
    };
    let stamp = register_stamp(&app).await;
    let n = format!("fast{}", tag());
    let (s, body, _) = signup(&app, test_ip(), &n, &stamp, &[]).await;
    assert_eq!(s, StatusCode::BAD_REQUEST);
    assert!(body.contains("That was quick"));
    // The re-rendered form keeps what was typed and carries a fresh stamp.
    assert!(body.contains(&format!(r#"value="{n}""#)) && body.contains(r#"name="stamp""#));
    assert!(users::Entity::find().filter(users::Column::Username.eq(&n)).one(app.db()).await.unwrap().is_none());
}

#[tokio::test]
async fn never_verified_silent_accounts_expire() {
    let Some(app) = app_with(|c| {
        c.registration_enabled = true;
        c.registration.min_fill_secs = 0;
    })
    .await
    else {
        return;
    };
    let stamp = register_stamp(&app).await;
    let mut made = vec![];
    for _ in 0..3 {
        let n = format!("ttl{}", tag());
        let (s, _, _) = signup(&app, test_ip(), &n, &stamp, &[]).await;
        assert_eq!(s, StatusCode::SEE_OTHER);
        made.push(users::Entity::find().filter(users::Column::Username.eq(&n)).one(app.db()).await.unwrap().unwrap());
    }
    let staff = app.who("staff", 4, true).await;
    let c = app.category(None, None, None).await;
    // [0]: silent and unverified; [1]: verified; [2]: unverified but wrote
    // something (a staff-made topic attributed to them stands in for it).
    let mut am: users::ActiveModel = made[1].clone().into();
    am.email_verified_at = Set(Some(Utc::now().into()));
    am.update(app.db()).await.unwrap();
    let (t, _) = app.topic(&staff, &c, "kept").await;
    let mut am: topics::ActiveModel = t.into();
    am.user_id = Set(made[2].id);
    am.update(app.db()).await.unwrap();
    for u in &made {
        let mut am: users::ActiveModel = u.clone().into();
        am.created_at = Set((Utc::now() - chrono::Duration::days(8)).into());
        am.update(app.db()).await.unwrap();
    }
    // A fresh one stays too.
    let n = format!("ttl{}", tag());
    signup(&app, test_ip(), &n, &stamp, &[]).await;

    let gone = recourse::registration::sweep_unverified(app.db(), 7).await.unwrap();
    assert!(gone >= 1);
    let db = app.db();
    let exists = |id: Uuid| async move { users::Entity::find_by_id(id).one(db).await.unwrap().is_some() };
    assert!(!exists(made[0].id).await, "silent unverified account kept");
    assert!(exists(made[1].id).await && exists(made[2].id).await);
    assert!(users::Entity::find().filter(users::Column::Username.eq(&n)).one(app.db()).await.unwrap().is_some());
    assert!(app.logged("expire_unverified", made[0].id).await);
}

// --- shader backgrounds (/shaders, assets/f/js/shader_background.js) ------------

#[tokio::test]
async fn the_shaders_page_lists_every_pattern_and_the_default_is_oil_at_seven() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    for who in [None, Some(&staff)] {
        let (s, page) = app.page("/shaders", who).await;
        assert_eq!(s, StatusCode::OK);
        for p in recourse::handlers::shaders::Shader::ALL {
            assert!(page.contains(&format!(r#"data-shader-preview="{}""#, p.value())), "{p:?} has no preview");
            assert!(page.contains(&format!(r#"data-use="{}""#, p.value())), "{p:?} can't be picked");
            assert!(page.contains(p.label()));
        }
        assert!(page.contains(r#"data-use="off""#), "an Off choice");
        // Coverage moves in 1s, so 7 is reachable.
        assert!(page.contains(r#"step="1" class="range range-xs" data-setting="oilCoverage""#));
        assert!(page.contains(r#"href="/shaders""#), "the theme menu links here");
        assert_eq!(meta_of(&page, "robots"), Some("index, follow"));
    }

    // Every page carries the default the script starts from.
    let (_, page) = app.page("/", None).await;
    let at = page.find(r#"data-shader-default=""#).expect("data-shader-default on <body>") + r#"data-shader-default=""#.len();
    let raw = &page[at..at + page[at..].find('"').unwrap()];
    let json: Value = serde_json::from_str(&raw.replace("&quot;", "\"")).unwrap();
    assert_eq!(json, json!({"pattern": "oil", "oilCoverage": 17}));

    // The profile links to it.
    let (_, page) = app.page("/profile", Some(&staff)).await;
    assert!(page.contains(r#"id="shader-setting""#) && page.contains(r#"href="/shaders""#));
}

// --- live updates (src/live.rs, f/js/live.js) -------------------------------------

#[tokio::test]
async fn live_signals_only_name_topics_the_viewer_may_see() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let regular = app.who("regular", 3, false).await;
    let basic = app.who("basic", 1, false).await;
    let author = app.who("author", 1, false).await;
    let gated = app.category(Some(3), None, None).await;
    let open = app.category(None, None, None).await;

    let (t, _) = app.topic(&staff, &gated, "for regulars").await;
    let sig = |u: users::Model, ids: Vec<Uuid>| {
        let state = app.state.clone();
        async move { recourse::live::signal_for(&state, &u, &ids).await.unwrap() }
    };
    assert_eq!(sig(regular.user.clone(), vec![t.id]).await, Some([gated.id].into()));
    assert_eq!(sig(basic.user.clone(), vec![t.id]).await, None, "trust 1 can't read a trust-3 category");

    // Held: nobody but its author and staff, until it's cleared.
    let (h, op) = app.topic(&author, &open, "held").await;
    let mut am: topics::ActiveModel = h.clone().into();
    am.held_at = Set(Some(Utc::now().into()));
    am.update(app.db()).await.unwrap();
    assert_eq!(sig(regular.user.clone(), vec![h.id]).await, None);
    assert_eq!(sig(author.user.clone(), vec![h.id]).await, Some([open.id].into()));
    let mut am: topics::ActiveModel = topics::Entity::find_by_id(h.id).one(app.db()).await.unwrap().unwrap().into();
    am.held_at = Set(None);
    am.update(app.db()).await.unwrap();
    assert_eq!(sig(regular.user.clone(), vec![h.id]).await, Some([open.id].into()));
    // Deleted: gone again.
    let mut am: topics::ActiveModel = topics::Entity::find_by_id(h.id).one(app.db()).await.unwrap().unwrap().into();
    am.deleted_at = Set(Some(Utc::now().into()));
    am.update(app.db()).await.unwrap();
    assert_eq!(sig(regular.user.clone(), vec![h.id, op.topic_id]).await, None);

    // A subcategory's topic names its parent too (the parent's page lists it).
    let mut child = app.category(None, None, None).await;
    let mut am: categories::ActiveModel = child.clone().into();
    am.parent_id = Set(Some(open.id));
    child = am.update(app.db()).await.unwrap();
    let (c, _) = app.topic(&staff, &child, "nested").await;
    assert_eq!(sig(basic.user.clone(), vec![c.id]).await, Some([child.id, open.id].into()));
}

#[tokio::test]
async fn new_visible_posts_publish_and_held_ones_wait() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let member = app.who("member", 2, false).await;
    let c = app.category(None, None, None).await;
    let mut rx = app.state.live.subscribe();
    let (t, _) = app.topic(&member, &c, "a perfectly ordinary opening post").await;
    assert_eq!(rx.try_recv().ok(), Some(t.id), "a new topic");
    recourse::actions::reply(&app.state, &member.user, t.id, "and a reply").await.unwrap();
    assert_eq!(rx.try_recv().ok(), Some(t.id), "a reply");
    // A wall of junk is held: no event until staff dismiss the hold.
    let held = recourse::actions::reply(&app.state, &member.user, t.id, WALL).await.unwrap();
    assert!(held.hidden_at.is_some());
    assert!(rx.try_recv().is_err(), "a held reply announced");
    moderation::dismiss_flags(&app.state, Actor::web(&staff.user), held.id).await.unwrap();
    assert_eq!(rx.try_recv().ok(), Some(t.id), "released");
}

#[tokio::test]
async fn the_socket_is_for_signed_in_pages_of_ours() {
    let Some(app) = app_with(|c| c.public_url = "https://forum.example".into()).await else { return };
    let member = app.who("member", 2, false).await;
    let upgrade = |cookie: Option<&str>, origin: Option<&str>| {
        let mut b = Request::builder()
            .uri("/ws")
            .header("connection", "upgrade")
            .header("upgrade", "websocket")
            .header("sec-websocket-version", "13")
            .header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");
        if let Some(c) = cookie {
            b = b.header("cookie", format!("session_token={c}"));
        }
        if let Some(o) = origin {
            b = b.header("origin", o);
        }
        b.body(Body::empty()).unwrap()
    };
    let (s, _, _) = app.send(upgrade(None, Some("https://forum.example"))).await;
    assert_eq!(s, StatusCode::UNAUTHORIZED, "anonymous");
    let (s, _, _) = app.send(upgrade(Some("not-a-session"), Some("https://forum.example"))).await;
    assert_eq!(s, StatusCode::UNAUTHORIZED, "a bad session");
    let (s, _, _) = app.send(upgrade(Some(&member.cookie), Some("https://evil.example"))).await;
    assert_eq!(s, StatusCode::FORBIDDEN, "someone else's page");
    let (s, _, _) = app.send(upgrade(Some(&member.cookie), None)).await;
    assert_eq!(s, StatusCode::FORBIDDEN, "no Origin");

    // Signed-in pages carry the socket; anonymous ones don't.
    let (_, page) = app.page("/", Some(&member)).await;
    assert!(page.contains(r#"ws-connect="/ws""#) && page.contains(r#"id="live-signal""#));
    let (_, page) = app.page("/", None).await;
    assert!(!page.contains("ws-connect"));
}

#[tokio::test]
async fn popular_refreshes_itself_and_latest_lists_are_live() {
    let Some(app) = app().await else { return };
    let member = app.who("member", 2, false).await;
    let c = app.category(None, None, None).await;
    let poll = r#"hx-trigger="every 300s [window.livePollOk()]""#;
    for (path, popular_id) in [
        ("/?view=classic", "landing-popular"),
        ("/?view=focus", "landing-popular"),
        ("/p/popular?view=classic", "feed-list"),
        ("/p/popular?view=focus", "focus-list"),
    ] {
        for who in [None, Some(&member)] {
            let (s, page) = app.page(path, who).await;
            assert_eq!(s, StatusCode::OK, "{path}");
            let at = page.find(&format!(r#"id="{popular_id}""#)).unwrap_or_else(|| panic!("{path}: #{popular_id}"));
            let tag = &page[at..at + page[at..].find('>').unwrap()];
            assert!(tag.contains(poll) && tag.contains(&format!(r##"hx-select="#{popular_id}""##)), "{path}: {tag}");
            assert!(tag.contains(r#"hx-disinherit="*""#), "{path}: its links must not inherit the poll's target");
        }
    }
    for path in ["/?view=classic", "/?view=focus", "/p/latest?view=classic", "/p/latest?view=focus"] {
        let (_, page) = app.page(path, Some(&member)).await;
        assert!(page.contains(r#"data-live="latest""#), "{path}");
    }
    for path in [format!("/c/{}", c.slug), format!("/c/{}?view=focus", c.slug)] {
        let (_, page) = app.page(&path, Some(&member)).await;
        assert!(page.contains(&format!(r#"data-live="category" data-live-category="{}""#, c.id)), "{path}");
    }
}

/// The whole path over a real socket: a member of a trust-gated category
/// hears about a new topic in it, a member below the bar hears nothing.
#[tokio::test]
async fn a_live_socket_pushes_to_those_who_may_see() {
    use futures_util::StreamExt;
    use tokio_tungstenite::tungstenite::client::IntoClientRequest;
    let Ok(_) = std::env::var("TEST_DATABASE_URL") else { return };
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let origin = format!("http://{addr}");
    let o = origin.clone();
    let app = app_with(move |c| c.public_url = o).await.unwrap();
    let router = app.router.clone();
    tokio::spawn(async move {
        axum::serve(listener, router.into_make_service_with_connect_info::<SocketAddr>()).await.unwrap();
    });
    let staff = app.who("staff", 4, true).await;
    let regular = app.who("regular", 3, false).await;
    let basic = app.who("basic", 1, false).await;
    let gated = app.category(Some(3), None, None).await;

    let connect = |who: &Who| {
        let mut req = format!("ws://{addr}/ws").into_client_request().unwrap();
        req.headers_mut().insert("cookie", format!("session_token={}", who.cookie).parse().unwrap());
        req.headers_mut().insert("origin", origin.parse().unwrap());
        async move { tokio_tungstenite::connect_async(req).await.expect("upgrade").0 }
    };
    let mut yes = connect(&regular).await;
    let mut no = connect(&basic).await;
    // Text frames only (pings are answered by the client library).
    async fn next_text(ws: &mut (impl futures_util::Stream<Item = Result<tokio_tungstenite::tungstenite::Message, tokio_tungstenite::tungstenite::Error>> + Unpin), secs: u64) -> Option<String> {
        tokio::time::timeout(std::time::Duration::from_secs(secs), async {
            while let Some(Ok(m)) = ws.next().await {
                if let tokio_tungstenite::tungstenite::Message::Text(t) = m {
                    return Some(t.to_string());
                }
            }
            None
        })
        .await
        .ok()
        .flatten()
    }
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    let (_t, _) = app.topic(&staff, &gated, "regulars only").await;
    let got = next_text(&mut yes, 5).await.expect("the regular is told");
    assert!(got.contains(r#"id="live-signal""#) && got.contains(&gated.id.to_string()), "{got}");
    assert!(!got.contains("regulars only"), "a signal, not content");
    assert_eq!(next_text(&mut no, 3).await, None, "the basic member is told nothing");
}

// ------------------------------------------------------------ rich links
//
// The URLs below are documentation (192.0.2.0/24) and private addresses on
// purpose: attaching queues a real background fetch, and the fence refuses
// those before anything connects, so no test reaches the network.

async fn attach(app: &App, who: Option<&Who>, post: Uuid, url: &str) -> (StatusCode, String) {
    let (s, body, _) = app.form(&format!("/p/{post}/links"), who, &[("url", url)]).await;
    (s, body)
}

async fn links_of(app: &App, post: Uuid) -> Vec<recourse::entities::post_links::Model> {
    use recourse::entities::post_links;
    post_links::Entity::find()
        .filter(post_links::Column::PostId.eq(post))
        .order_by_asc(post_links::Column::Position)
        .all(app.db())
        .await
        .unwrap()
}

/// A fetched card, as the background task would have stored it (once the
/// real one, which the fence refuses, has finished).
async fn fetched(app: &App, link: Uuid, title: &str, png: bool) {
    settled(app, link).await;
    let meta = recourse::link_cards::PageMetadata {
        title: Some(title.into()),
        description: Some("What the page says it is about".into()),
        site_name: Some("Example Site".into()),
        image_url: None,
    };
    let image = png.then(|| (b"\x89PNG\r\n\x1a\nnot really a png".to_vec(), "image/png"));
    recourse::link_cards::record(app.db(), link, Some(meta), image).await.unwrap();
}

/// Wait for a link's background fetch.
async fn settled(app: &App, link: Uuid) {
    use recourse::entities::post_links;
    for _ in 0..100 {
        let l = post_links::Entity::find_by_id(link).one(app.db()).await.unwrap().unwrap();
        if l.status != "pending" {
            return;
        }
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }
    panic!("link {link} still pending");
}

async fn htmx_form(app: &App, path: &str, who: &Who, form: &[(&str, &str)]) -> (StatusCode, String) {
    let body = form.iter().map(|(k, v)| format!("{k}={}", urlencode(v))).collect::<Vec<_>>().join("&");
    let req = Request::builder()
        .method("POST")
        .uri(path)
        .header("content-type", "application/x-www-form-urlencoded")
        .header("hx-request", "true")
        .header("cookie", format!("session_token={}", who.cookie))
        .body(Body::from(body))
        .unwrap();
    let (s, b, _) = app.send(req).await;
    (s, b)
}

#[tokio::test]
async fn only_staff_attach_remove_and_refetch_links() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let author = app.who("author", 4, false).await;
    let c = app.category(None, None, None).await;
    let (topic, op) = app.topic(&author, &c, "A post to decorate").await;

    // Not staff, even the post's author at the top trust level: refused.
    let (s, _) = attach(&app, Some(&author), op.id, "https://192.0.2.10/a").await;
    assert_eq!(s, StatusCode::FORBIDDEN);
    let (s, _) = attach(&app, None, op.id, "https://192.0.2.10/a").await;
    assert!(!s.is_success(), "anonymous: {s}");
    assert!(links_of(&app, op.id).await.is_empty());

    // Staff: attached (a bare domain becomes https), logged, queued.
    let (s, _) = attach(&app, Some(&staff), op.id, "192.0.2.10/a").await;
    assert_eq!(s, StatusCode::SEE_OTHER);
    let links = links_of(&app, op.id).await;
    assert_eq!(links.len(), 1);
    assert_eq!(links[0].url, "https://192.0.2.10/a");
    assert_eq!(links[0].created_by_id, Some(staff.user.id));
    assert!(app.logged("attach_link", op.id).await);
    let link = links[0].id;

    // The background fetch refuses a documentation address and records the
    // link as failed; the card still shows the link and its host.
    settled(&app, link).await;
    assert_eq!(links_of(&app, op.id).await[0].status, "failed");
    let (_, html) = app.page(&format!("/t/{}", topic.id), None).await;
    assert!(html.contains(r#"data-link-card="failed""#) && html.contains("192.0.2.10"), "failed card shown");

    // Remove and refetch: staff only.
    for action in ["delete", "refetch"] {
        let (s, _, _) = app.form(&format!("/links/{link}/{action}"), Some(&author), &[]).await;
        assert_eq!(s, StatusCode::FORBIDDEN, "{action}");
    }
    let (s, _, _) = app.form(&format!("/links/{link}/refetch"), Some(&staff), &[]).await;
    assert_eq!(s, StatusCode::SEE_OTHER);
    let (s, _, _) = app.form(&format!("/links/{link}/delete"), Some(&staff), &[]).await;
    assert_eq!(s, StatusCode::SEE_OTHER);
    assert!(links_of(&app, op.id).await.is_empty());
    assert!(app.logged("remove_link", op.id).await);

    // The log names them.
    let (_, log) = app.page("/admin/log", Some(&staff)).await;
    assert!(log.contains("Attached link") && log.contains("Removed link"));

    // The staff control is on the post for staff only.
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&staff)).await;
    assert!(html.contains(&format!(r#"hx-get="/p/{}/links?open=1""#, op.id)));
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&author)).await;
    assert!(!html.contains(&format!("/p/{}/links?open=1", op.id)));
    let (s, panel) = app.page(&format!("/p/{}/links?open=1", op.id), Some(&author)).await;
    assert_eq!(s, StatusCode::OK);
    assert!(!panel.contains("data-links-panel"), "no manage panel for non-staff");
}

#[tokio::test]
async fn links_are_limited_and_deduplicated() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let c = app.category(None, None, None).await;
    let (_, op) = app.topic(&staff, &c, "Five links at most").await;

    for i in 1..=5 {
        let (s, _) = attach(&app, Some(&staff), op.id, &format!("https://192.0.2.{i}/x")).await;
        assert_eq!(s, StatusCode::SEE_OTHER, "link {i}");
    }
    // The same address however it's written.
    for dup in ["HTTPS://192.0.2.1/x", "192.0.2.1/x", " https://192.0.2.1:443/x "] {
        let (s, body) = attach(&app, Some(&staff), op.id, dup).await;
        assert_eq!(s, StatusCode::CONFLICT, "{dup}: {body}");
        assert!(body.contains("already on this post"), "{body}");
    }
    let (s, body) = attach(&app, Some(&staff), op.id, "https://192.0.2.6/x").await;
    assert_eq!(s, StatusCode::CONFLICT);
    assert!(body.contains("at most 5"), "{body}");
    for bad in ["javascript:alert(1)", "data:text/html,hi", "ftp://192.0.2.7/", "https://u:p@192.0.2.7/"] {
        let (s, _) = attach(&app, Some(&staff), op.id, bad).await;
        assert_eq!(s, StatusCode::BAD_REQUEST, "{bad}");
    }
    assert_eq!(links_of(&app, op.id).await.len(), 5);
    assert_eq!(links_of(&app, op.id).await.iter().map(|l| l.position).collect::<Vec<_>>(), vec![0, 1, 2, 3, 4]);

    // Inline (htmx): the refusal comes back in the panel, to be swapped in.
    let (s, body) = htmx_form(&app, &format!("/p/{}/links", op.id), &staff, &[("url", "https://192.0.2.9/")]).await;
    assert_eq!(s, StatusCode::OK);
    assert!(body.contains("data-links-error") && body.contains("at most 5") && body.contains("data-links-panel"), "{body}");
    assert!(!body.contains("<html"), "a fragment");
}

#[tokio::test]
async fn link_cards_follow_their_post() {
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let other = app.who("other", 2, false).await;
    let author = app.who("waller", 1, false).await;
    let c = app.category(None, None, None).await;
    let (topic, op) = app.topic(&other, &c, "Cards under this one").await;

    // A visible post: its card, on every layout and in the API.
    attach(&app, Some(&staff), op.id, "https://192.0.2.20/page").await;
    let link = links_of(&app, op.id).await[0].id;
    fetched(&app, link, "Card On A Visible Post", true).await;
    for view in ["", "?view=focus"] {
        let (_, html) = app.page(&format!("/t/{}{view}", topic.id), Some(&other)).await;
        assert!(html.contains("Card On A Visible Post"), "{view}");
        assert!(html.contains(r#"rel="noopener noreferrer nofollow ugc""#));
        assert!(html.contains(r#"href="/out?u=https%3A%2F%2F192.0.2.20%2Fpage&amp;s="#), "through /out: {view}");
        assert!(html.contains(&format!("/links/{link}/image?v=")), "our own copy of the picture");
    }
    let (_, reader) = app.page(&format!("/c/{}?view=focus&topic={}", c.slug, topic.id), Some(&other)).await;
    assert!(reader.contains("Card On A Visible Post"), "the Focus reader");
    let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), &other, None).await;
    let card = &page["posts"][0]["links"][0];
    assert_eq!(card["title"], json!("Card On A Visible Post"));
    assert_eq!(card["status"], json!("ok"));
    assert_eq!(card["url"], json!("https://192.0.2.20/page"));
    assert!(card["href"].as_str().unwrap().starts_with("http") && card["href"].as_str().unwrap().contains("/out?u="));
    let req = Request::builder().uri(format!("/links/{link}/image")).body(Body::empty()).unwrap();
    let res = app.router.clone().oneshot(with_peer(req)).await.unwrap();
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(res.headers()["content-type"], "image/png");
    assert_eq!(res.headers()["x-content-type-options"], "nosniff");

    // A held reply: no card for anyone, in the page or the API, and no
    // picture.
    let (s, held) = reply_api(&app, &author, &topic, WALL).await;
    assert_eq!(s, StatusCode::CREATED);
    assert_eq!(held["hidden"], json!(true));
    let held_id: Uuid = held["id"].as_str().unwrap().parse().unwrap();
    let (s, _) = attach(&app, Some(&staff), held_id, "https://192.0.2.21/held").await;
    assert_eq!(s, StatusCode::SEE_OTHER, "staff may still attach");
    let held_link = links_of(&app, held_id).await[0].id;
    fetched(&app, held_link, "Card On A Held Post", true).await;
    for who in [Some(&other), Some(&author), Some(&staff), None] {
        for view in ["", "?view=focus"] {
            let (_, html) = app.page(&format!("/t/{}{view}", topic.id), who).await;
            assert!(!html.contains("Card On A Held Post"), "held card leaked ({view})");
        }
    }
    for who in [&other, &author] {
        let (_, page) = app.api("GET", &format!("/topics/{}", topic.id), who, None).await;
        let p = page["posts"].as_array().unwrap().iter().find(|p| p["id"] == json!(held_id)).unwrap();
        assert_eq!(p["links"], json!([]));
    }
    let (s, _) = app.page(&format!("/links/{held_link}/image"), Some(&other)).await;
    assert_eq!(s, StatusCode::NOT_FOUND);
    let (s, _) = app.page(&format!("/links/{held_link}/image"), None).await;
    assert_eq!(s, StatusCode::NOT_FOUND);
    // Staff manage it in the panel, which says why there's no card.
    let (_, panel) = app.page(&format!("/p/{held_id}/links?open=1"), Some(&staff)).await;
    assert!(panel.contains("data-links-panel") && panel.contains("Card On A Held Post") && panel.contains("This post is hidden"));
    let (_, panel) = app.page(&format!("/p/{held_id}/links"), Some(&other)).await;
    assert!(!panel.contains("Card On A Held Post"));

    // A deleted post: gone too.
    app.form(&format!("/p/{}/delete", op.id), Some(&staff), &[]).await;
    let (_, html) = app.page(&format!("/t/{}", topic.id), Some(&staff)).await;
    assert!(!html.contains("Card On A Visible Post"));
    let (s, _) = app.page(&format!("/links/{link}/image"), Some(&other)).await;
    assert_eq!(s, StatusCode::NOT_FOUND);
}

fn with_peer(mut req: Request<Body>) -> Request<Body> {
    req.extensions_mut().insert(ConnectInfo(SocketAddr::from(([192, 0, 2, 1], 40000))));
    req
}

/// Links a restart left `pending` are fetched by the startup sweep (here,
/// refused by the fence and recorded as failed).
#[tokio::test]
async fn the_startup_sweep_picks_up_pending_links() {
    use recourse::entities::post_links;
    let Some(app) = app().await else { return };
    let staff = app.who("staff", 4, true).await;
    let c = app.category(None, None, None).await;
    let (_, op) = app.topic(&staff, &c, "Interrupted").await;
    let mut ids = vec![];
    for (i, url) in ["http://10.1.2.3/", "http://169.254.169.254/latest/meta-data/", "http://[fd00::1]/", "http://localhost/"]
        .into_iter()
        .enumerate()
    {
        let now = Utc::now();
        let row = post_links::ActiveModel {
            id: Set(Uuid::now_v7()),
            post_id: Set(op.id),
            url: Set(url.into()),
            position: Set(i as i32),
            status: Set("pending".into()),
            created_by_id: Set(Some(staff.user.id)),
            created_at: Set(now.into()),
            updated_at: Set(now.into()),
            ..Default::default()
        }
        .insert(app.db())
        .await
        .unwrap();
        ids.push(row.id);
    }
    let n = recourse::link_cards::Previewer::new(app.state.db.clone(), "https://forum.test").sweep().await.unwrap();
    assert!(n >= ids.len(), "swept {n}");
    for l in links_of(&app, op.id).await {
        assert_eq!(l.status, "failed", "{}", l.url);
        assert!(l.fetched_at.is_some());
        assert!(l.title.is_none() && l.image_data.is_none());
    }
}