//! 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> {
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();
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),
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(®ular, &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), ®ular, 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/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&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}");
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
43.6 KiB · text
History
7250478