62.6 KiB · text History 1974764
//! 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,
}

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 state = AppState {
        env: recourse::web::environment(&config),
        db: db.clone(),
        config: config.clone(),
        view_throttle: recourse::new_view_throttle(),
        mailer: recourse::mailer::build(&config, false),
    };
    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 })
}

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}");
    }
}