A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(admin): remove router suites run against a mock API
Hampusa3d1875db033
diff --git a/fluxer_admin/tests/csrf_legacy_cookie.rs b/fluxer_admin/tests/csrf_legacy_cookie.rsdeleted file mode 100644index 4e601d317..000000000--- a/fluxer_admin/tests/csrf_legacy_cookie.rs+++ /dev/null@@ -1,281 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--#![recursion_limit = "256"]--use axum::{- Json, Router,- body::{Body, to_bytes},- http::{HeaderMap, Method, Request, StatusCode, Uri, header},- response::{IntoResponse, Response},-};-use fluxer_admin::{- build_router,- config::{AdminConfig, ProxyConfig},- session,-};-use serde_json::{Value, json};-use tokio::net::TcpListener;-use tower::ServiceExt;--const SECRET_KEY: &str = "legacy-csrf-cookie-test-secret";-const ADMIN_ORIGIN: &str = "https://admin.example.test";-const LEGACY_HEX_TOKEN: &str = "8f14e45fceea167a5a36dedd4bea25438f14e45fceea167a5a36dedd4bea2543";-const CREATED_KEY_SECRET: &str = "fa_1900000000000000001_OneTimeSecretForTests";--struct TestApp {- router: Router,- session_cookie: String,-}--#[tokio::test]-async fn clean_browser_can_submit_an_action() {- let app = setup().await;- let cookie = app.session_cookie.clone();-- let (cookie_token, page_token) = load_page(&app, &cookie).await;- assert_eq!(cookie_token, page_token);-- let with_csrf = format!("{cookie}; __Host-csrf_token={cookie_token}");- let status = submit_action(&app, &with_csrf, &page_token).await;- assert_eq!(status, StatusCode::OK);-}--#[tokio::test]-async fn legacy_csrf_cookie_does_not_wedge_actions() {- let app = setup().await;- let stale = format!("{}; csrf_token={LEGACY_HEX_TOKEN}", app.session_cookie);-- let (cookie_token, page_token) = load_page(&app, &stale).await;- assert_eq!(cookie_token, page_token);-- let both = format!("{stale}; __Host-csrf_token={cookie_token}");- let status = submit_action(&app, &both, &page_token).await;- assert_eq!(- status,- StatusCode::OK,- "a leftover unsigned csrf_token cookie must not block actions"- );-}--#[tokio::test]-async fn production_responses_expire_the_legacy_csrf_cookie() {- let app = setup().await;- let stale = format!("{}; csrf_token={LEGACY_HEX_TOKEN}", app.session_cookie);- let headers = page_headers(&app, &stale).await;-- let expiry = headers- .get_all(header::SET_COOKIE)- .iter()- .filter_map(|value| value.to_str().ok())- .find(|value| value.starts_with("csrf_token=;"))- .unwrap_or_else(|| panic!("legacy cookie was not expired: {headers:?}"));- assert!(expiry.contains("Max-Age=0"), "{expiry}");- assert!(expiry.contains("Path=/"), "{expiry}");-}--async fn setup() -> TestApp {- let api_endpoint = spawn_mock_api().await;- let router = build_router(production_config(api_endpoint));- let session_value = session::create_session("1500000000000000000", "test-token", SECRET_KEY);- TestApp {- router,- session_cookie: format!("{}={session_value}", session::SESSION_COOKIE_NAME),- }-}--fn production_config(api_endpoint: String) -> AdminConfig {- AdminConfig {- host: "127.0.0.1".to_owned(),- port: 0,- secret_key_base: SECRET_KEY.to_owned(),- base_path: String::new(),- api_endpoint,- media_endpoint: "https://media.example.test".to_owned(),- static_cdn_endpoint: "https://static.example.test".to_owned(),- reports_bucket_origin: "https://reports.example.test".to_owned(),- admin_endpoint: ADMIN_ORIGIN.to_owned(),- web_app_endpoint: "https://app.example.test".to_owned(),- oauth_client_id: "admin-client".to_owned(),- oauth_client_secret: "admin-secret".to_owned(),- oauth_redirect_uri: "https://admin.example.test/callback".to_owned(),- build_version: "test".to_owned(),- self_hosted: false,- proxy: ProxyConfig {- trust_client_ip_header: false,- client_ip_header_name: "x-forwarded-for".to_owned(),- },- }-}--async fn page_headers(app: &TestApp, cookie: &str) -> HeaderMap {- app.router- .clone()- .oneshot(page_request(cookie))- .await- .unwrap()- .headers()- .clone()-}--async fn load_page(app: &TestApp, cookie: &str) -> (String, String) {- let response = app- .router- .clone()- .oneshot(page_request(cookie))- .await- .unwrap();- let status = response.status();- let headers = response.headers().clone();- let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();- let text = String::from_utf8(body.to_vec()).unwrap();- assert_eq!(status, StatusCode::OK, "{text}");- assert!(- text.contains("AdminUser"),- "the page did not render the admin the mock API returns"- );- let cookie_token = host_csrf_cookie(&headers)- .unwrap_or_else(|| panic!("no __Host-csrf_token in Set-Cookie: {headers:?}"));- let page_token = form_csrf_value(&text).expect("no _csrf hidden input rendered");- (cookie_token, page_token)-}--fn page_request(cookie: &str) -> Request<Body> {- Request::builder()- .method(Method::GET)- .uri("/admin-api-keys")- .header(header::COOKIE, cookie)- .header("sec-fetch-site", "same-origin")- .body(Body::empty())- .unwrap()-}--async fn submit_action(app: &TestApp, cookie: &str, form_token: &str) -> StatusCode {- let response = app- .router- .clone()- .oneshot(- Request::builder()- .method(Method::POST)- .uri("/admin-api-keys?action=create")- .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")- .header(header::COOKIE, cookie)- .header(header::ORIGIN, ADMIN_ORIGIN)- .header("sec-fetch-site", "same-origin")- .header("HX-Request", "true")- .header("HX-Boosted", "true")- .header("HX-Target", "body")- .body(Body::from(format!(- "_csrf={form_token}&name=Legacy+Cookie+Key&acls=*"- )))- .unwrap(),- )- .await- .unwrap();- let status = response.status();- let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();- let text = String::from_utf8(body.to_vec()).unwrap();- if status == StatusCode::OK {- assert!(- text.contains(CREATED_KEY_SECRET),- "the action did not render the key the mock API creates"- );- }- status-}--fn host_csrf_cookie(headers: &HeaderMap) -> Option<String> {- headers- .get_all(header::SET_COOKIE)- .iter()- .filter_map(|value| value.to_str().ok())- .find_map(|value| {- value- .split(';')- .next()- .and_then(|pair| pair.trim().strip_prefix("__Host-csrf_token="))- .map(str::to_owned)- })-}--fn form_csrf_value(body: &str) -> Option<String> {- let marker = r#"name="_csrf" value=""#;- body.match_indices(marker)- .filter_map(|(index, _)| {- let rest = &body[index + marker.len()..];- let end = rest.find('"')?;- Some(rest[..end].to_owned())- })- .find(|value| !value.is_empty())-}--async fn spawn_mock_api() -> String {- let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- axum::serve(listener, Router::new().fallback(mock_api))- .await- .unwrap();- });- format!("http://{addr}")-}--async fn mock_api(method: Method, uri: Uri) -> Response {- match (method, uri.path()) {- (Method::GET, "/admin/users/@me") => Json(json!({ "user": admin_user() })).into_response(),- (Method::GET, "/admin/api-keys") => Json(json!([])).into_response(),- (Method::POST, "/admin/api-keys") => Json(json!({- "key_id": "1900000000000000001",- "key": CREATED_KEY_SECRET,- "name": "Legacy Cookie Key",- "created_at": "2026-07-10T15:00:00.000Z",- "expires_at": null,- "acls": ["*"]- }))- .into_response(),- _ => (StatusCode::NOT_FOUND, Json(json!({ "error": "not found" }))).into_response(),- }-}--fn admin_user() -> Value {- json!({- "id": "1500000000000000000",- "username": "AdminUser",- "discriminator": 1,- "avatar": null,- "banner": null,- "email": "[email protected]",- "email_verified": true,- "email_bounced": false,- "global_name": "AdminUser",- "bio": null,- "pronouns": null,- "accent_color": null,- "date_of_birth": null,- "locale": "en-US",- "acls": ["*"],- "traits": [],- "flags": "0",- "premium_flags": 0,- "bot": false,- "system": false,- "premium_type": null,- "premium_since": null,- "premium_until": null,- "premium_grace_ends_at": null,- "premium_lifetime_sequence": null,- "has_totp": false,- "authenticator_types": [],- "temp_banned_until": null,- "pending_deletion_at": null,- "pending_bulk_message_deletion_at": null,- "deletion_reason_code": null,- "deletion_public_reason": null,- "deletion_audit_log_reason": null,- "deletion_scheduled_by": null,- "deletion_scheduled_at": null,- "last_active_at": null,- "last_active_ip": null,- "last_active_ip_reverse": null,- "last_active_location": null- })-}diff --git a/fluxer_admin/tests/enforcement_panel.rs b/fluxer_admin/tests/enforcement_panel.rsdeleted file mode 100644index 2181a31ff..000000000--- a/fluxer_admin/tests/enforcement_panel.rs+++ /dev/null@@ -1,1058 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--#![recursion_limit = "256"]--use axum::{- Json, Router,- body::{Body, to_bytes},- extract::State,- http::{HeaderMap, Method, Request, StatusCode, Uri, header},- response::{IntoResponse, Response},-};-use fluxer_admin::{- build_router,- config::{AdminConfig, ProxyConfig},- session,-};-use serde_json::{Value, json};-use std::sync::{Arc, Mutex};-use tokio::net::TcpListener;-use tower::ServiceExt;--const SECRET_KEY: &str = "enforcement-panel-test-secret";-const ADMIN_ID: &str = "1500000000000000000";-const USER_ID: &str = "1500000000000000001";-const DECISION_ID: &str = "1900000000000000001";-const REPORT_ID: &str = "1600000000000000001";-const CHANNEL_ID: &str = "1700000000000000001";-const MESSAGE_ID: &str = "1700000000000000002";-const SUSPENDED_UNTIL: &str = "2099-01-01T00:00:00.000Z";-const DISABLED: u64 = 1 << 38;-const NETWORK_IP: &str = "45.33.10.1";-const SHARED_IP: &str = "45.33.10.2";--#[derive(Clone)]-struct Captured {- route: String,- audit_log_reason: Option<String>,- body: Value,-}--struct Mock {- admin_acls: Vec<&'static str>,- user: Value,- decisions: Vec<Value>,- decision: Value,- audit_logs: Vec<Value>,- captured: Mutex<Vec<Captured>>,-}--impl Mock {- fn new(user: Value) -> Self {- Self {- admin_acls: vec!["*"],- user,- decisions: Vec::new(),- decision: Value::Null,- audit_logs: Vec::new(),- captured: Mutex::new(Vec::new()),- }- }-}--struct TestApp {- router: Router,- session_cookie: String,- mock: Arc<Mock>,-}--async fn setup(mock: Mock) -> TestApp {- let mock = Arc::new(mock);- let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();- let addr = listener.local_addr().unwrap();- let state = Arc::clone(&mock);- tokio::spawn(async move {- axum::serve(listener, Router::new().fallback(mock_api).with_state(state))- .await- .unwrap();- });- let router = build_router(test_config(format!("http://{addr}")));- let session_value = session::create_session(ADMIN_ID, "test-token", SECRET_KEY);- TestApp {- router,- session_cookie: format!("{}={session_value}", session::SESSION_COOKIE_NAME),- mock,- }-}--async fn get(app: &TestApp, uri: &str) -> (StatusCode, HeaderMap, String) {- let response = app- .router- .clone()- .oneshot(- Request::builder()- .method(Method::GET)- .uri(uri)- .header(header::COOKIE, &app.session_cookie)- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- let status = response.status();- let headers = response.headers().clone();- let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();- (status, headers, String::from_utf8(body.to_vec()).unwrap())-}--async fn page(app: &TestApp, uri: &str) -> String {- let (status, _, body) = get(app, uri).await;- assert_eq!(status, StatusCode::OK, "{body}");- body-}--async fn post(app: &TestApp, uri: &str, fields: &str) -> Vec<Captured> {- let (_, headers, _) = get(app, "/decisions").await;- let csrf = headers- .get_all(header::SET_COOKIE)- .iter()- .filter_map(|value| value.to_str().ok())- .find_map(|value| {- let pair = value.split(';').next()?;- pair.strip_prefix("__Host-csrf_token=")- .or_else(|| pair.strip_prefix("csrf_token="))- .map(ToOwned::to_owned)- })- .expect("csrf cookie");- let response = app- .router- .clone()- .oneshot(- Request::builder()- .method(Method::POST)- .uri(uri)- .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")- .header(- header::COOKIE,- format!("{}; __Host-csrf_token={csrf}", app.session_cookie),- )- .body(Body::from(format!("_csrf={csrf}&{fields}")))- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::SEE_OTHER);- app.mock.captured.lock().unwrap().clone()-}--async fn mock_api(- State(mock): State<Arc<Mock>>,- method: Method,- uri: Uri,- headers: HeaderMap,- request: Request<Body>,-) -> Response {- let path = uri.path().to_owned();- if method != Method::GET {- let bytes = to_bytes(request.into_body(), usize::MAX).await.unwrap();- mock.captured.lock().unwrap().push(Captured {- route: format!("{method} {path}"),- audit_log_reason: headers- .get("x-audit-log-reason")- .and_then(|value| value.to_str().ok())- .map(ToOwned::to_owned),- body: serde_json::from_slice(&bytes).unwrap_or(Value::Null),- });- }- let user_path = format!("/admin/users/{USER_ID}");- let decision_path = format!("/admin/enforcement-decisions/{DECISION_ID}");- match (method, path.as_str()) {- (Method::GET, "/admin/users/@me") => {- let mut admin = user(ADMIN_ID, "AdminUser");- admin["acls"] = json!(mock.admin_acls);- Json(json!({ "user": admin })).into_response()- }- (Method::GET, "/admin/users") => Json(json!({- "users": [user(ADMIN_ID, "AdminUser"), mock.user.clone()]- }))- .into_response(),- (Method::GET, p) if p == user_path => {- Json(json!({ "users": [mock.user.clone()] })).into_response()- }- (Method::GET, p) if p == format!("{user_path}/network-block-candidates") => Json(json!({- "networks": [- {"ip": NETWORK_IP, "last_seen_at": "2026-10-13T09:00:00.000Z", "skip_reason": null, "other_unrestricted_accounts": 0},- {"ip": SHARED_IP, "last_seen_at": "2026-10-12T09:00:00.000Z", "skip_reason": null, "other_unrestricted_accounts": 2},- {"ip": "10.0.0.5", "last_seen_at": "2026-10-11T09:00:00.000Z", "skip_reason": "special_purpose", "other_unrestricted_accounts": 0}- ]- }))- .into_response(),- (Method::GET, "/admin/enforcement-decisions") => {- Json(json!({ "decisions": mock.decisions })).into_response()- }- (Method::GET, p) if p == decision_path => Json(mock.decision.clone()).into_response(),- (Method::GET, "/admin/audit-logs") => Json(json!({- "logs": mock.audit_logs,- "total": mock.audit_logs.len()- }))- .into_response(),- (Method::PUT | Method::DELETE | Method::PATCH, p) if p.starts_with(&user_path) => {- Json(json!({ "user": mock.user.clone(), "skipped_ips": [] })).into_response()- }- (Method::POST, p) if p == format!("{user_path}/warnings") => {- Json(json!({ "decision_id": DECISION_ID })).into_response()- }- (Method::POST, p) if p == format!("{decision_path}/end") => {- Json(mock.decision.clone()).into_response()- }- (Method::POST, p) if p == format!("{decision_path}/notes") => Json(json!({- "note_id": "1",- "author_id": ADMIN_ID,- "body": "x",- "created_at": "2026-10-14T12:00:00.000Z"- }))- .into_response(),- _ => (- StatusCode::NOT_FOUND,- Json(json!({ "code": "UNKNOWN", "message": "not found" })),- )- .into_response(),- }-}--fn user(id: &str, username: &str) -> Value {- json!({- "id": id,- "username": username,- "discriminator": 1,- "avatar": null,- "banner": null,- "email": "[email protected]",- "email_verified": true,- "email_bounced": false,- "global_name": username,- "bio": null,- "pronouns": null,- "accent_color": null,- "date_of_birth": null,- "locale": "en-US",- "acls": [],- "traits": [],- "flags": "0",- "premium_flags": 0,- "bot": false,- "system": false,- "premium_type": null,- "premium_since": null,- "premium_until": null,- "premium_grace_ends_at": null,- "premium_lifetime_sequence": null,- "has_totp": false,- "authenticator_types": [],- "temp_banned_until": null,- "pending_deletion_at": null,- "pending_bulk_message_deletion_at": null,- "deletion_reason_code": null,- "deletion_public_reason": null,- "deletion_audit_log_reason": null,- "deletion_scheduled_by": null,- "deletion_scheduled_at": null,- "enforcement_decision_id": null,- "last_active_at": null,- "last_active_ip": null,- "last_active_ip_reverse": null,- "last_active_location": null- })-}--fn subject() -> Value {- user(USER_ID, "Subject")-}--fn suspended_subject() -> Value {- let mut subject = subject();- subject["temp_banned_until"] = json!(SUSPENDED_UNTIL);- subject["flags"] = json!(DISABLED.to_string());- subject["enforcement_decision_id"] = json!(DECISION_ID);- subject-}--fn list_item(reason_code: i32) -> Value {- json!({- "decision_id": DECISION_ID,- "subject_type": "user",- "subject_id": USER_ID,- "subject_name": null,- "recipient_user_id": USER_ID,- "kind": "suspension",- "reason_code": reason_code,- "source": "report",- "automation": "none",- "statement": null,- "rights_holder": null,- "ends_at": SUSPENDED_UNTIL,- "deletion_at": null,- "limit": null,- "profile_fields": [],- "removed_message_count": null,- "removed_all_messages": false,- "payment_at": null,- "report_ids": [REPORT_ID],- "decided_by": ADMIN_ID,- "created_at": "2026-10-14T12:00:00.000Z",- "status": "active",- "end_outcome": null,- "ended_at": null,- "ended_by": null,- "end_statement": null,- "notice_status": "sent",- "notice_channels": ["email"],- "notice_locale": "en-US",- "notice_text": "We suspended your account.",- "notice_sent_at": "2026-10-14T12:00:01.000Z",- "expired": false,- "replaced": false- })-}--fn full_decision() -> Value {- let mut decision = list_item(11);- decision["statement"] = json!("Stop sending these messages.");- decision["notes"] = json!([{- "note_id": "1950000000000000001",- "author_id": ADMIN_ID,- "body": "Ticket 42, three reports",- "created_at": "2026-10-14T12:00:00.000Z"- }]);- decision["evidence"] = json!([{- "message_id": MESSAGE_ID,- "channel_id": CHANNEL_ID,- "timestamp": "2026-10-13T09:00:00.000Z",- "content": "the offending message",- "attachments": [{"filename": "proof.png", "size": "1024", "content_type": "image/png"}],- "attachment_count": 1- }]);- decision["profile_values"] = Value::Null;- decision["network_blocks"] =- json!([{"ip": NETWORK_IP, "expires_at": "2027-01-12T12:00:00.000Z"}]);- decision["notice"] = json!({- "decision_id": DECISION_ID,- "kind": "suspension",- "permanent": false,- "issued_at": "Oct 14, 2026",- "ends_at": "Jan 1, 2099",- "deletion_at": null,- "summary": "We suspended your account until Jan 1, 2099.",- "effects": ["You can't sign in until then."],- "rule": {"title": "Harassment", "url": "https://fluxer.com/guidelines#1-harassment-threats-and-privacy"},- "facts": ["You sent messages that harass people."],- "statement": "Stop sending these messages.",- "how_we_decided": ["We reviewed this after a report."],- "appeal": {"email": "[email protected]", "deadline": "Dec 13, 2026", "account_has_email": true},- "redress": []- });- decision-}--fn redacted_decision() -> Value {- let mut decision = full_decision();- decision["report_ids"] = json!([]);- decision["evidence"][0]["content"] = Value::Null;- decision["evidence"][0]["attachments"] = Value::Null;- decision-}--fn decision_mock(reason_code: i32) -> Mock {- let mut mock = Mock::new(suspended_subject());- mock.decisions = vec![list_item(reason_code)];- mock.decision = full_decision();- mock-}--fn moderation_uri() -> String {- format!("/users/{USER_ID}?tab=moderation")-}--fn current_restriction(html: &str) -> &str {- let current = section(html, "data-current-restriction");- current- .find("Suspend account")- .or_else(|| current.find("Account deletion"))- .map_or(current, |end| ¤t[..end])-}--fn section<'a>(html: &'a str, marker: &str) -> &'a str {- let start = html- .find(marker)- .unwrap_or_else(|| panic!("missing {marker}\n{html}"));- &html[start..]-}--#[tokio::test]-async fn moderation_tab_with_a_decision_shows_it_and_ends_it() {- let app = setup(decision_mock(11)).await;- let html = page(&app, &moderation_uri()).await;- let current = current_restriction(&html);- assert!(- current.contains("Suspension for Harassment or bullying. Until Jan 1, 2099, 12:00 AM UTC")- );- assert!(current.contains(&format!(r#"href="/decisions/{DECISION_ID}""#)));- assert!(current.contains(&format!(r#"action="/decisions/{DECISION_ID}?action=end""#)));- assert!(current.contains(r#"value="lifted""#));- assert!(!current.contains("data-correction-line"));- assert!(!html.contains("action=unban"));- let table = section(&html, "data-decisions-table");- assert!(table.contains(">Suspension</td>"));- assert!(table.contains(">Active</td>"));- assert!(html.contains("?action=suspend&tab=moderation"));- assert!(html.contains("?action=warn&tab=moderation"));-}--#[tokio::test]-async fn ending_a_restricted_decision_shows_the_correction_line() {- let app = setup(decision_mock(13)).await;- let html = page(&app, &moderation_uri()).await;- let current = current_restriction(&html);- assert!(current.contains("data-correction-line"));- assert!(current.contains("If this decision was reported to an authority, file a correction."));-}--#[tokio::test]-async fn moderation_tab_for_a_legacy_suspension_offers_the_lift_form() {- let mut subject = suspended_subject();- subject["enforcement_decision_id"] = Value::Null;- let mut mock = Mock::new(subject);- mock.audit_logs = vec![json!({- "log_id": "1",- "admin_user_id": ADMIN_ID,- "admin_user": {"id": ADMIN_ID, "username": "AdminUser", "discriminator": "0001", "global_name": null},- "action": "temp_ban",- "target_id": USER_ID,- "target_type": "user",- "audit_log_reason": "Old internal note",- "metadata": {"banned_until": SUSPENDED_UNTIL},- "created_at": "2026-09-01T12:00:00.000Z"- })];- let app = setup(mock).await;- let html = page(&app, &moderation_uri()).await;- let current = current_restriction(&html);- assert!(- current.contains("Banned permanently. Recorded before decisions, so it has no decision.")- );- assert!(current.contains("Old internal note"));- assert!(current.contains("?action=unban&tab=moderation"));- assert!(!current.contains("?action=end"));- assert!(!current.contains("notify_user"));-}--#[tokio::test]-async fn moderation_tab_without_a_restriction_offers_suspend_and_warn_with_prefills() {- let app = setup(Mock::new(subject())).await;- let html = page(- &app,- &format!(- "{}&report_id={REPORT_ID}&message={CHANNEL_ID}%2F{MESSAGE_ID}",- moderation_uri()- ),- )- .await;- let current = current_restriction(&html);- assert!(current.contains("No current restriction."));- assert!(!current.contains("<form"));- assert!(html.contains("No decisions."));- let suspend = section(&html, "?action=suspend");- assert!(suspend.contains(r#"name="duration_hours""#));- assert!(suspend.contains(r#"name="remove_evidence""#));- assert!(suspend.contains(&format!(">{REPORT_ID}</textarea>")));- assert!(suspend.contains(&format!(">{CHANNEL_ID}/{MESSAGE_ID}</textarea>")));- assert!(section(&html, "?action=warn").contains("Send warning"));- let limit = between(&html, "?action=limit_features", "?action=warn");- for expected in [- format!(">{REPORT_ID}</textarea>"),- format!(">{CHANNEL_ID}/{MESSAGE_ID}</textarea>"),- r#"name="source" value="report" required checked"#.to_owned(),- r#"Limit<span class="text-red-500 ml-0.5">*</span></legend>"#.to_owned(),- r#"Internal note<span class="text-red-500 ml-0.5">*</span></label>"#.to_owned(),- ] {- assert!(limit.contains(&expected), "missing {expected}\n{limit}");- }-}--fn between<'a>(html: &'a str, start: &str, end: &str) -> &'a str {- let rest = section(html, start);- rest.find(end).map_or(rest, |index| &rest[..index])-}--#[tokio::test]-async fn moderation_tab_offers_close_and_limit_features() {- let app = setup(Mock::new(subject())).await;- let html = page(&app, &moderation_uri()).await;- let close = between(&html, "?action=close", "?action=limit_features");- for expected in [- r#"value="enforcement""#,- r#"value="holder_request""#,- r#"value="housekeeping""#,- "A rule was broken",- "The account holder asked",- "Inactivity",- r#"name="days_until_deletion" value="74""#,- r#"data-show-for-basis="enforcement" hidden disabled"#,- r#"data-show-for-basis="holder_request housekeeping" hidden disabled"#,- r#"name="remove_evidence""#,- "Close account",- ] {- assert!(close.contains(expected), "missing {expected}\n{close}");- }- assert!(!close.contains(r#"<option value="13""#));- assert!(!close.contains("replace_pending_deletion_at"));- assert!(!close.contains("notify_user"));- let limit = between(&html, "?action=limit_features", "?action=warn");- for expected in [- r#"data-show-for-codes="3 6 8 18 21" hidden"#,- r#"data-show-for-codes="29" hidden"#,- r#"data-show-for-codes="12 14" hidden"#,- r#"data-show-for-limit="reports" hidden disabled"#,- r#"name="ends_on""#,- r#"<option value="29""#,- "Limit features",- ] {- assert!(limit.contains(expected), "missing {expected}\n{limit}");- }- assert!(!limit.contains(r#"<option value="11""#));- assert!(!limit.contains("checked"));-}--#[tokio::test]-async fn moderation_tab_for_a_legacy_deletion_offers_the_cancel_form() {- let mut subject = subject();- subject["pending_deletion_at"] = json!("2026-12-01T00:00:00.000Z");- subject["deletion_reason_code"] = json!(1);- subject["deletion_scheduled_by"] = json!(ADMIN_ID);- let app = setup(Mock::new(subject)).await;- let html = page(&app, &moderation_uri()).await;- let current = current_restriction(&html);- assert!(- current.contains("Scheduled for deletion. No decision owns it, so it is cancelled here.")- );- assert!(current.contains("?action=cancel_deletion&tab=moderation"));- assert!(current.contains("Cancel deletion"));- assert!(!current.contains("notify_user"));- let close = section(&html, "?action=close");- assert!(- close.contains(r#"name="replace_pending_deletion_at" value="2026-12-01T00:00:00.000Z""#)- );-}--#[tokio::test]-async fn decisions_page_lists_the_review_queue() {- let mut queued = list_item(12);- queued["kind"] = json!("feature_limit");- queued["limit"] = json!("purchases");- queued["automation"] = json!("automated");- queued["source"] = json!("own_review");- queued["ends_at"] = Value::Null;- queued["decided_by"] = json!("0");- queued["payment_at"] = json!("2026-10-01T09:00:00.000Z");- let mut mock = Mock::new(subject());- mock.decisions = vec![queued];- let app = setup(mock).await;- let html = page(&app, "/decisions").await;- let queue = section(&html, "data-review-queue");- assert!(queue.contains(&format!(r#"href="/decisions/{DECISION_ID}""#)));- assert!(queue.contains(&format!(r#"href="/users/{USER_ID}?tab=moderation""#)));- assert!(queue.contains("Payment fraud"));-}--#[tokio::test]-async fn decisions_page_hides_the_review_queue_without_permission() {- let mut mock = Mock::new(subject());- mock.admin_acls = vec!["user:lookup"];- let app = setup(mock).await;- let html = page(&app, "/decisions").await;- assert!(!html.contains("Review queue"));-}--#[tokio::test]-async fn moderation_tab_hides_decisions_and_actions_without_their_permissions() {- let mut mock = decision_mock(11);- mock.admin_acls = vec!["user:lookup", "user:update:flags"];- let app = setup(mock).await;- let html = page(&app, &moderation_uri()).await;- let current = current_restriction(&html);- assert!(current.contains("Banned permanently") || current.contains("Suspended until"));- assert!(current.contains("Open the decision to see or end it."));- assert!(!html.contains("data-decisions-table"));- assert!(!html.contains("?action=suspend"));- assert!(html.contains("?action=warn"));-}--#[tokio::test]-async fn overview_banner_links_the_decision_and_restriction_flags_are_read_only() {- let app = setup(decision_mock(11)).await;- let html = page(&app, &format!("/users/{USER_ID}")).await;- let banner = section(&html, "data-restriction-banner");- assert!(banner.contains(&format!(r#"href="/decisions/{DECISION_ID}""#)));- let disabled = format!(r#"name="flags[]" value="{DISABLED}" checked disabled"#);- assert!(html.contains(&disabled), "{html}");- assert!(html.contains("Restriction flags are read-only. Use the moderation tab."));-}--#[tokio::test]-async fn decision_page_renders_the_full_response() {- let app = setup(decision_mock(11)).await;- let html = page(&app, &format!("/decisions/{DECISION_ID}")).await;- for expected in [- "Decision 1900000000000000001",- "Harassment or bullying",- "https://fluxer.com/guidelines#1-harassment-threats-and-privacy",- "Stop sending these messages.",- "We suspended your account.",- "We suspended your account until Jan 1, 2099.",- "the offending message",- "Attachment: proof.png",- "/messages?channel_id=1700000000000000001&message_id=1700000000000000002&context_limit=50",- "/reports/1600000000000000001",- "Ticket 42, three reports",- "?action=add_note",- "?action=end",- "Network blocks",- NETWORK_IP,- ] {- assert!(html.contains(expected), "missing {expected}\n{html}");- }-}--#[tokio::test]-async fn an_expired_suspension_can_only_be_reversed() {- let mut mock = decision_mock(11);- for decision in [&mut mock.decision, &mut mock.decisions[0]] {- decision["status"] = json!("ended");- decision["end_outcome"] = json!("expired");- decision["ended_at"] = json!(SUSPENDED_UNTIL);- decision["ended_by"] = json!("0");- }- mock.decision["network_blocks"] = json!([]);- let app = setup(mock).await;- let html = page(&app, &format!("/decisions/{DECISION_ID}")).await;- assert!(html.contains(">Expired<"), "{html}");- assert!(html.contains("?action=end"));- assert!(html.contains(r#"value="reversed""#));- assert!(!html.contains(r#"value="lifted""#));- let html = page(&app, &moderation_uri()).await;- assert!(section(&html, "data-decisions-table").contains(">Expired</td>"));-}--#[tokio::test]-async fn decision_page_hides_the_end_form_without_the_ip_removal_permission() {- let mut mock = decision_mock(11);- mock.admin_acls = vec!["enforcement:view", "user:temp_ban"];- let app = setup(mock).await;- let html = page(&app, &format!("/decisions/{DECISION_ID}")).await;- assert!(html.contains("Network blocks"));- assert!(!html.contains("?action=end"));-}--#[tokio::test]-async fn suspend_card_offers_recent_networks_with_their_collateral() {- let app = setup(Mock::new(subject())).await;- let html = page(&app, &moderation_uri()).await;- let suspend = between(&html, "?action=suspend", "?action=close");- let networks = section(suspend, r#"data-show-for-duration_hours="0""#);- assert!(networks.contains("hidden disabled"));- assert!(networks.contains("Block networks this account used"));- assert!(networks.contains("0 other unrestricted accounts last active here"));- assert!(networks.contains("2 other unrestricted accounts last active here"));- assert!(networks.contains("Private or special-purpose range, never blocked"));- assert!(networks.contains(&format!(r#"value="{NETWORK_IP}" class="hidden""#)));- assert!(networks.contains(&format!(r#"value="{SHARED_IP}" disabled"#)));- assert!(networks.contains(r#"name="network_block_days" value="90""#));- let close = between(&html, "?action=close", "?action=limit_features");- assert!(close.contains("Block networks this account used"));-}--#[tokio::test]-async fn suspend_and_close_send_the_chosen_networks() {- let app = setup(Mock::new(subject())).await;- let captured = post(- &app,- &format!("/users/{USER_ID}?action=suspend&tab=moderation"),- &format!(- "duration_hours=0&reason_code=3&source=own_review&automation=none\- &statement=Spam&internal_note=Ticket+7&block_networks={NETWORK_IP}&network_block_days=30"- ),- )- .await;- assert_eq!(- captured[0].body["block_networks"],- json!({"ips": [NETWORK_IP], "days": 30})- );- let captured = post(- &app,- &format!("/users/{USER_ID}?action=close&tab=moderation"),- &format!(- "basis=enforcement&days_until_deletion=74&reason_code=3&source=own_review\- &automation=none&statement=Spam&internal_note=Ticket+7&block_networks={NETWORK_IP}"- ),- )- .await;- assert_eq!(- captured.last().unwrap().body["block_networks"],- json!({"ips": [NETWORK_IP], "days": 90})- );-}--#[tokio::test]-async fn moderation_tab_skips_networks_without_the_ip_permissions() {- let mut mock = Mock::new(subject());- mock.admin_acls = vec!["user:temp_ban", "user:delete"];- let app = setup(mock).await;- let html = page(&app, &moderation_uri()).await;- assert!(!html.contains("Block networks this account used"));-}--#[tokio::test]-async fn decision_page_renders_a_redacted_response_without_staff_forms() {- let mut mock = decision_mock(11);- mock.admin_acls = vec!["enforcement:view"];- mock.decision = redacted_decision();- let app = setup(mock).await;- let html = page(&app, &format!("/decisions/{DECISION_ID}")).await;- assert!(html.contains("Content is hidden. Needs the message:lookup permission."));- assert!(html.contains("Attachments: 1"));- assert!(!html.contains("the offending message"));- assert!(!html.contains("/reports/1600000000000000001"));- assert!(!html.contains("?action=add_note"));- assert!(!html.contains("?action=end"));-}--#[tokio::test]-async fn decisions_lookup_redirects_to_the_decision() {- let app = setup(Mock::new(subject())).await;- let (status, headers, _) = get(&app, &format!("/decisions?id=+{DECISION_ID}+")).await;- assert!(status.is_redirection());- assert_eq!(- headers- .get(header::LOCATION)- .and_then(|value| value.to_str().ok()),- Some(format!("/decisions/{DECISION_ID}").as_str())- );- let html = page(&app, "/decisions?id=abc").await;- assert!(html.contains("A decision ID is a number."));-}--#[tokio::test]-async fn suspend_sends_the_decision_and_the_internal_note() {- let app = setup(Mock::new(subject())).await;- let captured = post(- &app,- &format!("/users/{USER_ID}?action=suspend&tab=moderation"),- &format!(- "duration_hours=0&reason_code=11&source=report&automation=flagged\- &report_ids={REPORT_ID}&evidence={CHANNEL_ID}%2F{MESSAGE_ID}\- &statement=Stop&internal_note=Ticket+42&remove_evidence=true"- ),- )- .await;- assert_eq!(captured.len(), 1);- assert_eq!(captured[0].route, format!("PUT /admin/users/{USER_ID}/ban"));- assert_eq!(captured[0].audit_log_reason.as_deref(), Some("Ticket 42"));- assert_eq!(- captured[0].body,- json!({- "duration_hours": 0,- "remove_evidence": true,- "decision": {- "reason_code": 11,- "source": "report",- "automation": "flagged",- "report_ids": [REPORT_ID],- "evidence": [{"channel_id": CHANNEL_ID, "message_id": MESSAGE_ID}],- "statement": "Stop"- }- })- );-}--#[tokio::test]-async fn suspend_without_a_reason_sends_nothing() {- let app = setup(Mock::new(subject())).await;- let captured = post(- &app,- &format!("/users/{USER_ID}?action=suspend&tab=moderation"),- "duration_hours=24&source=report&automation=none&internal_note=x",- )- .await;- assert!(captured.is_empty());-}--#[tokio::test]-async fn warn_sends_the_decision_with_the_rights_holder() {- let app = setup(Mock::new(subject())).await;- let captured = post(- &app,- &format!("/users/{USER_ID}?action=warn&tab=moderation"),- "reason_code=31&source=own_review&automation=none&statement=Remove+it\- &rights_holder=Example+Records&internal_note=DMCA+notice",- )- .await;- assert_eq!(captured.len(), 1);- assert_eq!(- captured[0].route,- format!("POST /admin/users/{USER_ID}/warnings")- );- assert_eq!(captured[0].audit_log_reason.as_deref(), Some("DMCA notice"));- assert_eq!(- captured[0].body,- json!({- "decision": {- "reason_code": 31,- "source": "own_review",- "automation": "none",- "statement": "Remove it",- "rights_holder": "Example Records"- }- })- );-}--#[tokio::test]-async fn ending_and_annotating_a_decision_send_their_requests() {- let app = setup(decision_mock(11)).await;- let end_uri = format!("/decisions/{DECISION_ID}?action=end");- let captured = post(- &app,- &end_uri,- "outcome=reversed&statement=We+made+a+mistake&internal_note=Appeal+upheld",- )- .await;- assert_eq!(- captured[0].route,- format!("POST /admin/enforcement-decisions/{DECISION_ID}/end")- );- assert_eq!(- captured[0].audit_log_reason.as_deref(),- Some("Appeal upheld")- );- assert_eq!(- captured[0].body,- json!({"outcome": "reversed", "statement": "We made a mistake"})- );- let captured = post(- &app,- &format!("/decisions/{DECISION_ID}?action=add_note"),- "body=Appeal+received",- )- .await;- assert_eq!(- captured[1].route,- format!("POST /admin/enforcement-decisions/{DECISION_ID}/notes")- );- assert_eq!(captured[1].body, json!({"body": "Appeal received"}));- let captured = post(&app, &end_uri, "statement=x&internal_note=y").await;- assert_eq!(captured.len(), 2, "an end without an outcome sends nothing");-}--#[tokio::test]-async fn saving_flags_never_touches_restriction_flags() {- let app = setup(Mock::new(suspended_subject())).await;- let captured = post(- &app,- &format!("/users/{USER_ID}?action=update_flags&tab=overview"),- &format!("flags[]={}&flags[]={}", 1u64 << 50, 1u64 << 6),- )- .await;- assert_eq!(captured.len(), 1);- assert_eq!(- captured[0].route,- format!("PATCH /admin/users/{USER_ID}/flags")- );- assert_eq!(- captured[0].body,- json!({"add_flags": [(1u64 << 50).to_string()]})- );-}--#[tokio::test]-async fn shredder_and_delete_all_offer_a_basis_and_delete_all_refuses_restricted_reasons() {- let app = setup(Mock::new(subject())).await;- let html = page(- &app,- &format!(- "{}&delete_all_messages_dry_run=true&delete_all_messages_channel_count=1\- &delete_all_messages_message_count=2",- moderation_uri()- ),- )- .await;- let delete_all = between(&html, "Delete all messages", "Message shredder");- for expected in [- "2 messages in 1 channel.",- r#"name="dry_run" value="false""#,- r#"name="basis" value="enforcement""#,- r#"name="basis" value="holder_request""#,- r#"name="basis" value="housekeeping""#,- r#"name="evidence""#,- ] {- assert!(- delete_all.contains(expected),- "missing {expected}\n{delete_all}"- );- }- assert!(!delete_all.contains("Restricted: no details"));- let shredder = section(&html, "Message shredder");- assert!(shredder.contains(r#"name="basis" value="enforcement""#));- assert!(shredder.contains("Restricted: no details"));- assert!(- !shredder.contains(r#"name="evidence""#),- "the entries are the evidence"- );-}--#[tokio::test]-async fn content_removal_forms_send_their_basis() {- let app = setup(Mock::new(subject())).await;- let captured = post(- &app,- &format!("/users/{USER_ID}?action=message_shred&tab=moderation"),- &format!(- "csv_data={CHANNEL_ID}%2C{MESSAGE_ID}&basis=enforcement&reason_code=3\- &source=own_review&automation=none&statement=Stop&internal_note=Ticket+7"- ),- )- .await;- assert_eq!(- captured[0].route,- format!("POST /admin/users/{USER_ID}/message-shreds")- );- assert_eq!(captured[0].audit_log_reason.as_deref(), Some("Ticket 7"));- assert_eq!(- captured[0].body,- json!({- "entries": [{"channel_id": CHANNEL_ID, "message_id": MESSAGE_ID}],- "basis": {- "type": "enforcement",- "decision": {- "reason_code": 3,- "source": "own_review",- "automation": "none",- "statement": "Stop"- }- }- })- );- let captured = post(- &app,- &format!("/users/{USER_ID}?action=delete_all_messages&tab=moderation"),- "dry_run=false&basis=housekeeping&internal_note=Cleanup",- )- .await;- assert_eq!(- captured[1].route,- format!("DELETE /admin/users/{USER_ID}/messages")- );- assert_eq!(captured[1].body, json!({"basis": {"type": "housekeeping"}}));- assert_eq!(captured[1].audit_log_reason.as_deref(), Some("Cleanup"));- let captured = post(- &app,- &format!("/users/{USER_ID}?action=clear_fields&tab=account"),- "fields[]=bio&basis=holder_request",- )- .await;- assert_eq!(- captured[2].route,- format!("DELETE /admin/users/{USER_ID}/profile-fields")- );- assert_eq!(- captured[2].body,- json!({"fields": ["bio"], "basis": {"type": "holder_request"}})- );- let captured = post(- &app,- &format!("/users/{USER_ID}?action=delete_all_messages&tab=moderation"),- "dry_run=false",- )- .await;- assert_eq!(- captured.len(),- 3,- "a deletion without a basis sends nothing"- );-}--#[tokio::test]-async fn community_message_and_report_forms_send_their_basis_or_outcome() {- let app = setup(Mock::new(subject())).await;- let guild_id = "1800000000000000001";- let captured = post(- &app,- &format!("/guilds/{guild_id}?action=delete_guild&tab=moderation"),- "basis=enforcement&reason_code=26&source=report&automation=none\- &report_ids=1600000000000000001&internal_note=Reviewed",- )- .await;- assert_eq!(- captured[0].route,- format!("DELETE /admin/guilds/{guild_id}")- );- assert_eq!(captured[0].audit_log_reason.as_deref(), Some("Reviewed"));- assert_eq!(- captured[0].body,- json!({- "basis": {- "type": "enforcement",- "decision": {- "reason_code": 26,- "source": "report",- "automation": "none",- "report_ids": [REPORT_ID]- }- }- })- );- let captured = post(- &app,- "/messages?action=delete",- &format!("channel_id={CHANNEL_ID}&message_id={MESSAGE_ID}&basis=housekeeping"),- )- .await;- assert_eq!(- captured[1].route,- format!("DELETE /admin/channels/{CHANNEL_ID}/messages/{MESSAGE_ID}")- );- assert_eq!(captured[1].body, json!({"basis": {"type": "housekeeping"}}));- let captured = post(- &app,- &format!("/reports/{REPORT_ID}/resolve"),- "resolution=actioned&public_comment=Handled",- )- .await;- assert_eq!(- captured.len(),- 2,- "an actioned resolution without an outcome sends nothing"- );-}--fn test_config(api_endpoint: String) -> AdminConfig {- AdminConfig {- host: "127.0.0.1".to_owned(),- port: 0,- secret_key_base: SECRET_KEY.to_owned(),- base_path: String::new(),- api_endpoint,- media_endpoint: "https://media.example.test".to_owned(),- static_cdn_endpoint: "https://static.example.test".to_owned(),- reports_bucket_origin: "https://reports.example.test".to_owned(),- admin_endpoint: "https://admin.example.test".to_owned(),- web_app_endpoint: "https://app.example.test".to_owned(),- oauth_client_id: "admin-client".to_owned(),- oauth_client_secret: "admin-secret".to_owned(),- oauth_redirect_uri: "https://admin.example.test/callback".to_owned(),- build_version: "test".to_owned(),- self_hosted: false,- proxy: ProxyConfig {- trust_client_ip_header: false,- client_ip_header_name: "x-forwarded-for".to_owned(),- },- }-}diff --git a/fluxer_admin/tests/htmx_acceptance.rs b/fluxer_admin/tests/htmx_acceptance.rsdeleted file mode 100644index 4f80a37ad..000000000--- a/fluxer_admin/tests/htmx_acceptance.rs+++ /dev/null@@ -1,927 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--#![recursion_limit = "256"]--use axum::{- Json, Router,- body::{Body, to_bytes},- extract::{DefaultBodyLimit, Path},- http::{HeaderMap, Method, Request, StatusCode, Uri, header},- response::{IntoResponse, Response},- routing,-};-use fluxer_admin::{- build_router,- config::{AdminConfig, ProxyConfig},- session,-};-use serde_json::{Value, json};-use std::sync::{Arc, Mutex};-use tokio::net::TcpListener;-use tower::ServiceExt;--const SECRET_KEY: &str = "htmx-acceptance-test-secret";--struct TestApp {- router: Router,- session_cookie: String,-}--#[tokio::test]-async fn report_legal_hold_form_places_and_clears_the_hold() {- let received = Arc::new(Mutex::new(Vec::<Value>::new()));- let sink = received.clone();- let api = Router::new()- .route(- "/admin/reports/1800000000000000001/legal-hold",- routing::post(move |Json(body): Json<Value>| {- let sink = sink.clone();- async move {- sink.lock().unwrap().push(body.clone());- if body["legal_hold_reason"] == "rejected" {- return (- StatusCode::BAD_REQUEST,- Json(json!({"code": "INVALID_FORM_BODY", "message": "Invalid"})),- )- .into_response();- }- json_response(json!({- "report_id": "1800000000000000001",- "legal_hold_until": body["legal_hold_until"],- "legal_hold_reason": body["legal_hold_reason"]- }))- }- }),- )- .fallback(mock_api);- let app = setup_with_api(api).await;- let (headers, page) = get_with_headers(&app, "/reports/1800000000000000001", &[]).await;- let csrf_token = csrf_cookie(&headers)- .unwrap_or_else(|| panic!("report page did not set csrf_token cookie\n{page}"));- assert_form_has_csrf(- &page,- "/reports/1800000000000000001/legal-hold",- &csrf_token,- );- let cookie = format!("{}; csrf_token={}", app.session_cookie, csrf_token);- let post = |body: String| {- let app = &app;- let cookie = cookie.clone();- async move {- let (status, headers, text) = post_form_with_headers(- app,- "/reports/1800000000000000001/legal-hold",- &[- ("HX-Request", "true"),- ("HX-Target", "flash-container"),- ("Cookie", &cookie),- ],- &body,- )- .await;- assert_eq!(status, StatusCode::NO_CONTENT, "{text}");- headers- .get("X-Fluxer-Admin-Toast")- .and_then(|value| value.to_str().ok())- .unwrap_or_else(|| panic!("missing toast header\n{text}"))- .to_owned()- }- };-- let toast = post(format!(- "_csrf={csrf_token}&legal_hold_until=2027-01-31&legal_hold_reason=Court+order+42"- ))- .await;- assert!(toast.contains("success"), "{toast}");- assert!(- toast.contains("Legal hold placed until Jan 31, 2027, 11:59 PM UTC"),- "{toast}"- );- let toast = post(format!(- "_csrf={csrf_token}&clear=1&legal_hold_reason=ignored"- ))- .await;- assert!(toast.contains("Legal hold cleared"), "{toast}");- let toast = post(format!(- "_csrf={csrf_token}&legal_hold_until=2027-01-31&legal_hold_reason=rejected"- ))- .await;- assert!(toast.contains("error"), "{toast}");- assert!(toast.contains("The hold must end in the future"), "{toast}");- assert!(!toast.contains("needs a reason"), "{toast}");- let toast = post(format!(- "_csrf={csrf_token}&legal_hold_until=2020-01-01&legal_hold_reason=Past+date"- ))- .await;- assert!(toast.contains("error"), "{toast}");- assert!(toast.contains("The hold must end in the future"), "{toast}");- {- let received = received.lock().unwrap();- assert_eq!(- *received,- vec![- json!({"legal_hold_until": "2027-01-31T23:59:59.999Z", "legal_hold_reason": "Court order 42"}),- json!({"legal_hold_until": null, "legal_hold_reason": null}),- json!({"legal_hold_until": "2027-01-31T23:59:59.999Z", "legal_hold_reason": "rejected"}),- ]- );- }-- let toast = post(format!(- "_csrf={csrf_token}&legal_hold_until=2027-01-31&legal_hold_reason=+"- ))- .await;- assert!(toast.contains("Give a reason for the hold"), "{toast}");- let toast = post(format!(- "_csrf={csrf_token}&legal_hold_until=soon&legal_hold_reason=x"- ))- .await;- assert!(toast.contains("Choose the date the hold ends"), "{toast}");- assert_eq!(received.lock().unwrap().len(), 3);-}--#[tokio::test]-async fn report_notes_show_the_author_and_time_and_the_form_adds_one() {- let received = Arc::new(Mutex::new(Vec::<Value>::new()));- let sink = received.clone();- let api = Router::new()- .route(- "/admin/reports/1800000000000000001",- routing::get(|| async { json_response(report_with_note()) }),- )- .route(- "/admin/reports/1800000000000000001/notes",- routing::post(move |Json(body): Json<Value>| {- let sink = sink.clone();- async move {- sink.lock().unwrap().push(body.clone());- json_response(json!({- "note_id": "1950000000000000002",- "author_id": "1500000000000000000",- "body": body["body"],- "created_at": "2026-05-27T08:00:00.000Z"- }))- }- }),- )- .route(- "/admin/users",- routing::get(|| async {- json_response(json!({ "users": [user("1500000000000000000", "AdminUser")] }))- }),- )- .fallback(mock_api);- let app = setup_with_api(api).await;- let (headers, page) = get_with_headers(&app, "/reports/1800000000000000001", &[]).await;- let note_start = page- .find(r#"data-note="1950000000000000001""#)- .unwrap_or_else(|| panic!("missing note\n{page}"));- let note = &page[note_start..page[note_start..].find("</li>").unwrap() + note_start];- assert!(- note.contains(r#"href="/users/1500000000000000000""#),- "{note}"- );- assert!(note.contains("AdminUser"), "{note}");- assert!(note.contains("May 26, 2026, 1:30 PM UTC"), "{note}");- assert!(- note.contains("Reporter sent more context by email"),- "{note}"- );- let csrf_token = csrf_cookie(&headers)- .unwrap_or_else(|| panic!("report page did not set csrf_token cookie\n{page}"));- assert_form_has_csrf(&page, "/reports/1800000000000000001/notes", &csrf_token);- let cookie = format!("{}; csrf_token={}", app.session_cookie, csrf_token);- let post = |body: String| {- let app = &app;- let cookie = cookie.clone();- async move {- let (status, headers, text) = post_form_with_headers(- app,- "/reports/1800000000000000001/notes",- &[- ("HX-Request", "true"),- ("HX-Target", "flash-container"),- ("Cookie", &cookie),- ],- &body,- )- .await;- assert_eq!(status, StatusCode::NO_CONTENT, "{text}");- headers- .get("X-Fluxer-Admin-Toast")- .and_then(|value| value.to_str().ok())- .unwrap_or_else(|| panic!("missing toast header\n{text}"))- .to_owned()- }- };-- let toast = post(format!(- "_csrf={csrf_token}&body=++Waiting+on+the+guild+owner++"- ))- .await;- assert!(toast.contains("success"), "{toast}");- assert!(toast.contains("Note added"), "{toast}");- let toast = post(format!("_csrf={csrf_token}&body=+")).await;- assert!(toast.contains("error"), "{toast}");- assert!(toast.contains("Write a note first"), "{toast}");- assert_eq!(- *received.lock().unwrap(),- vec![json!({"body": "Waiting on the guild owner"})]- );-}--#[tokio::test]-async fn report_notes_hide_the_form_without_report_resolve() {- let api = Router::new()- .route(- "/admin/users/@me",- routing::get(|| async {- let mut admin = user("1500000000000000000", "AdminUser");- admin["acls"] = json!(["report:view"]);- json_response(json!({ "user": admin }))- }),- )- .route(- "/admin/reports/1800000000000000001",- routing::get(|| async { json_response(report_with_note()) }),- )- .fallback(mock_api);- let app = setup_with_api(api).await;- let (_, page) = get_with_headers(&app, "/reports/1800000000000000001", &[]).await;- assert!(- page.contains("Reporter sent more context by email"),- "{page}"- );- assert!(- page.contains(r#"href="/users/1500000000000000000""#),- "{page}"- );- assert!(- !page.contains(r#"action="/reports/1800000000000000001/notes""#),- "{page}"- );-}--#[tokio::test]-async fn report_delete_form_confirms_sends_the_reason_and_toasts_a_held_report() {- let received = Arc::new(Mutex::new(Vec::<Option<String>>::new()));- let sink = received.clone();- let api = Router::new()- .route(- "/admin/reports/1800000000000000001",- routing::delete(move |headers: HeaderMap| {- let sink = sink.clone();- async move {- let reason = headers- .get("X-Audit-Log-Reason")- .and_then(|value| value.to_str().ok())- .map(str::to_owned);- sink.lock().unwrap().push(reason.clone());- if reason.as_deref() == Some("held") {- return (- StatusCode::CONFLICT,- Json(json!({- "code": "REPORT_UNDER_LEGAL_HOLD",- "message": "This report is under a legal hold and can't be deleted."- })),- )- .into_response();- }- StatusCode::NO_CONTENT.into_response()- }- })- .get(|| async { json_response(searched_report()) }),- )- .fallback(mock_api);- let app = setup_with_api(api).await;- let (headers, page) = get_with_headers(&app, "/reports/1800000000000000001", &[]).await;- let csrf_token = csrf_cookie(&headers)- .unwrap_or_else(|| panic!("report page did not set csrf_token cookie\n{page}"));- assert_form_has_csrf(&page, "/reports/1800000000000000001/delete", &csrf_token);- let cookie = format!("{}; csrf_token={}", app.session_cookie, csrf_token);- let post = |body: String| {- let app = &app;- let cookie = cookie.clone();- async move {- post_form_with_headers(- app,- "/reports/1800000000000000001/delete",- &[- ("HX-Request", "true"),- ("HX-Target", "flash-container"),- ("Cookie", &cookie),- ],- &body,- )- .await- }- };- let toast = |headers: &HeaderMap| {- headers- .get("X-Fluxer-Admin-Toast")- .and_then(|value| value.to_str().ok())- .unwrap_or_else(|| panic!("missing toast header {headers:?}"))- .to_owned()- };-- let (status, headers, text) = post(format!(- "_csrf={csrf_token}&audit_log_reason=Erasure+request"- ))- .await;- assert_eq!(status, StatusCode::NO_CONTENT, "{text}");- let message = toast(&headers);- assert!(message.contains("error"), "{message}");- assert!(- message.contains("Confirm that the report should be deleted"),- "{message}"- );- assert!(headers.get("HX-Redirect").is_none(), "{headers:?}");-- let (status, headers, text) = post(format!(- "_csrf={csrf_token}&confirm=true&audit_log_reason=Erasure+request"- ))- .await;- assert_eq!(status, StatusCode::NO_CONTENT, "{text}");- assert_eq!(- headers.get("HX-Redirect").and_then(|v| v.to_str().ok()),- Some("/reports"),- "{headers:?}"- );- let message = toast(&headers);- assert!(message.contains("success"), "{message}");- assert!(message.contains("Report deleted"), "{message}");- assert!(- headers- .get_all(header::SET_COOKIE)- .iter()- .any(|value| value.to_str().is_ok_and(|v| v.starts_with("flash="))),- "{headers:?}"- );-- let (status, headers, text) = post(format!(- "_csrf={csrf_token}&confirm=true&audit_log_reason=held"- ))- .await;- assert_eq!(status, StatusCode::NO_CONTENT, "{text}");- assert!(headers.get("HX-Redirect").is_none(), "{headers:?}");- let message = toast(&headers);- assert!(message.contains("error"), "{message}");- assert!(- message.contains("The report is under a legal hold. Clear the hold before deleting it."),- "{message}"- );-- let (status, headers, text) = post_form_with_headers(- &app,- "/reports/1800000000000000001/delete",- &[("Cookie", &cookie)],- &format!("_csrf={csrf_token}&confirm=true&audit_log_reason=+"),- )- .await;- assert!(status.is_redirection(), "{status} {text}");- assert_eq!(- headers.get(header::LOCATION).and_then(|v| v.to_str().ok()),- Some("/reports"),- "{headers:?}"- );-- assert_eq!(- *received.lock().unwrap(),- vec![- Some("Erasure request".to_owned()),- Some("held".to_owned()),- None- ]- );-}--#[tokio::test]-async fn pending_registration_decision_refreshes_the_list_and_sidebar_count() {- let received = Arc::new(Mutex::new(Vec::<(String, Value)>::new()));- let sink = received.clone();- let api = Router::new()- .route(- "/admin/users/@me",- routing::get(|| async {- json_response(json!({"user": admin_user(), "pending_registration_count": 2}))- }),- )- .route(- "/admin/instance/pending-registrations",- routing::get(|| async {- json_response(json!({"pending_registrations": [- pending_registration("1500000000000000002"),- pending_registration("1500000000000000003"),- ]}))- }),- )- .route(- "/admin/instance/pending-registrations/{user_id}",- routing::patch(- move |Path(user_id): Path<String>, Json(body): Json<Value>| {- let sink = sink.clone();- async move {- sink.lock().unwrap().push((user_id, body));- json_response(json!({"pending_registrations": [- pending_registration("1500000000000000003"),- ]}))- }- },- ),- )- .fallback(mock_api);- let app = setup_with_api(api).await;- let (headers, page) = get_with_headers(&app, "/pending-registrations", &[]).await;- assert!(- page.contains(r#"<span id="pending-registration-count" class="tabular-nums text-neutral-400">2</span>"#),- "{page}"- );- assert!(page.contains("ID: 1500000000000000002"), "{page}");- let csrf_token = csrf_cookie(&headers).unwrap_or_else(|| {- panic!("pending registrations page did not set csrf_token cookie\n{page}")- });- assert_form_has_csrf(&page, "/pending-registrations/approve", &csrf_token);- assert_form_has_csrf(&page, "/pending-registrations/reject", &csrf_token);-- let cookie = format!("{}; csrf_token={}", app.session_cookie, csrf_token);- let (status, headers, fragment) = post_form_with_headers(- &app,- "/pending-registrations/approve",- &[- ("HX-Request", "true"),- ("HX-Target", "pending-registration-list"),- ("Cookie", &cookie),- ],- &format!("_csrf={csrf_token}&user_id=1500000000000000002"),- )- .await;- assert_eq!(status, StatusCode::OK, "{fragment}");- assert!(- fragment.contains(r#"id="pending-registration-list""#),- "{fragment}"- );- assert!(!fragment.contains("ID: 1500000000000000002"), "{fragment}");- assert!(fragment.contains("ID: 1500000000000000003"), "{fragment}");- assert!(- fragment.contains(r#"hx-swap-oob="true">1</span>"#),- "{fragment}"- );- let toast = headers- .get("X-Fluxer-Admin-Toast")- .and_then(|value| value.to_str().ok())- .unwrap_or_default();- assert!(toast.contains("Registration approved"), "{toast}");- assert_eq!(- *received.lock().unwrap(),- vec![(- "1500000000000000002".to_owned(),- json!({"status": "approved"})- )]- );-}--#[tokio::test]-async fn branding_asset_upload_takes_a_large_image_and_swaps_the_field() {- let received = Arc::new(Mutex::new(Vec::<Value>::new()));- let sink = received.clone();- let api = Router::new()- .route(- "/admin/instance/config",- routing::get(|| async {- json_response(instance_config(Some(- "https://media.example.test/branding/0/old.png",- )))- }),- )- .route(- "/admin/instance/config/branding-assets",- routing::post(move |Json(body): Json<Value>| {- let sink = sink.clone();- async move {- sink.lock().unwrap().push(body.clone());- if body["image"] == "data:image/png;base64,bad" {- return (- StatusCode::BAD_REQUEST,- Json(json!({- "code": "INVALID_FORM_BODY",- "message": "Input form validation failed",- "errors": [{"path": "image", "message": "Unsupported image format"}]- })),- )- .into_response();- }- let logo_url = body["image"]- .is_string()- .then_some("https://media.example.test/branding/0/new.png");- json_response(instance_config(logo_url))- }- }),- )- .layer(DefaultBodyLimit::disable())- .fallback(mock_api);- let app = setup_with_api(api).await;- let (headers, page) = get_with_headers(&app, "/instance-config", &[]).await;- let csrf_token = csrf_cookie(&headers)- .unwrap_or_else(|| panic!("instance config page did not set csrf_token cookie\n{page}"));- assert_form_has_csrf(- &page,- "/instance-config?action=update_app_public",- &csrf_token,- );- assert!(page.contains(r#"id="branding-asset-logo""#), "{page}");- assert!(page.contains(r#"id="branding-asset-favicon""#), "{page}");- assert!(- page.contains(r#"src="https://media.example.test/branding/0/old.png""#),- "{page}"- );- assert!(page.contains(r#"accept=".png,.jpeg,.webp"#), "{page}");-- let cookie = format!("{}; csrf_token={}", app.session_cookie, csrf_token);- let post = |action: &'static str, fields: Vec<(&'static str, String)>| {- let app = &app;- let cookie = cookie.clone();- let csrf_token = csrf_token.clone();- async move {- let mut body = url::form_urlencoded::Serializer::new(String::new());- body.append_pair("_csrf", &csrf_token);- for (name, value) in &fields {- body.append_pair(name, value);- }- post_form_with_headers(- app,- &format!("/instance-config?action={action}"),- &[- ("HX-Request", "true"),- ("HX-Target", "branding-asset-logo"),- ("X-CSRF-Token", &csrf_token),- ("Cookie", &cookie),- ],- &body.finish(),- )- .await- }- };- let toast_of = |headers: &HeaderMap| {- headers- .get("X-Fluxer-Admin-Toast")- .and_then(|value| value.to_str().ok())- .unwrap_or_default()- .to_owned()- };-- let image = format!(- "data:image/png;base64,{}",- "iVBO+w/A".repeat(2 * 1024 * 1024 / 8)- );- let (status, headers, fragment) = post(- "upload_branding_asset",- vec![("kind", "logo".to_owned()), ("image", image.clone())],- )- .await;- assert_eq!(status, StatusCode::OK, "{fragment}");- assert!(- fragment.starts_with(r#"<div id="branding-asset-logo""#),- "{fragment}"- );- assert!(- fragment.contains(r#"value="https://media.example.test/branding/0/new.png""#),- "{fragment}"- );- assert!(- fragment.contains("data-branding-asset-remove"),- "{fragment}"- );- assert!(toast_of(&headers).contains("Logo uploaded"));-- let (status, headers, fragment) =- post("remove_branding_asset", vec![("kind", "logo".to_owned())]).await;- assert_eq!(status, StatusCode::OK, "{fragment}");- assert!(- fragment.contains(r#"name="app_logo_url" value="""#),- "{fragment}"- );- assert!(!fragment.contains("<img"), "{fragment}");- assert!(- !fragment.contains("data-branding-asset-remove"),- "{fragment}"- );- assert!(toast_of(&headers).contains("Logo removed"));-- let (status, headers, _) = post(- "upload_branding_asset",- vec![- ("kind", "logo".to_owned()),- ("image", "data:image/png;base64,bad".to_owned()),- ],- )- .await;- assert_eq!(status, StatusCode::NO_CONTENT);- let toast = toast_of(&headers);- assert!(toast.contains("error"), "{toast}");- assert!(- toast.contains("Failed to upload the logo: image: Unsupported image format"),- "{toast}"- );-- let (_, headers, _) = post(- "upload_branding_asset",- vec![("kind", "logo".to_owned()), ("image", " ".to_owned())],- )- .await;- assert!(toast_of(&headers).contains("Choose an image to upload"));- let (_, headers, _) = post(- "upload_branding_asset",- vec![("kind", "banner".to_owned()), ("image", image.clone())],- )- .await;- assert!(toast_of(&headers).contains("Unknown branding asset"));- let (_, headers, _) = post(- "update_app_public",- vec![- ("app_product_name", "Fluxer".to_owned()),- ("app_logo_url", image.clone()),- ],- )- .await;- assert!(toast_of(&headers).contains("Invalid form data"));-- assert_eq!(- *received.lock().unwrap(),- vec![- json!({"kind": "logo", "image": image}),- json!({"kind": "logo", "image": null}),- json!({"kind": "logo", "image": "data:image/png;base64,bad"}),- ]- );-}--fn instance_config(logo_url: Option<&str>) -> Value {- json!({- "sso": {},- "gateway_rollout": {- "session_rollout_percentage": 100,- "session_rollout_mode": "modulo",- "guild_rollout_percentage": 100,- "rpc_request_timeout_ms": 10000,- "max_concurrent_session_starts": 512,- "max_concurrent_guild_starts": 256,- "voice_e2ee_scope": "guild_feature_only"- },- "self_hosted": true,- "app_public": {"branding": {"product_name": "Fluxer", "logo_url": logo_url}}- })-}--async fn setup_with_api(api: Router) -> TestApp {- let api_endpoint = spawn_mock_api(api).await;- let router = build_router(test_config(api_endpoint));- let session_value = session::create_session("1500000000000000000", "test-token", SECRET_KEY);- TestApp {- router,- session_cookie: format!("{}={session_value}", session::SESSION_COOKIE_NAME),- }-}--async fn get_with_headers(- app: &TestApp,- uri: &str,- headers: &[(&str, &str)],-) -> (HeaderMap, String) {- let mut builder = Request::builder()- .method(Method::GET)- .uri(uri)- .header(header::COOKIE, &app.session_cookie);- for (name, value) in headers {- builder = builder.header(*name, *value);- }- let response = app- .router- .clone()- .oneshot(builder.body(Body::empty()).unwrap())- .await- .unwrap();- let status = response.status();- let headers = response.headers().clone();- let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();- let text = String::from_utf8(body.to_vec()).unwrap();- assert_eq!(status, StatusCode::OK, "{text}");- (headers, text)-}--async fn post_form_with_headers(- app: &TestApp,- uri: &str,- headers: &[(&str, &str)],- body: &str,-) -> (StatusCode, HeaderMap, String) {- let has_cookie_header = headers- .iter()- .any(|(name, _)| name.eq_ignore_ascii_case("cookie"));- let mut builder = Request::builder()- .method(Method::POST)- .uri(uri)- .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");- if !has_cookie_header {- builder = builder.header(header::COOKIE, &app.session_cookie);- }- for (name, value) in headers {- builder = builder.header(*name, *value);- }- let response = app- .router- .clone()- .oneshot(builder.body(Body::from(body.to_owned())).unwrap())- .await- .unwrap();- let status = response.status();- let headers = response.headers().clone();- let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();- let text = String::from_utf8(body.to_vec()).unwrap();- (status, headers, text)-}--fn csrf_cookie(headers: &HeaderMap) -> Option<String> {- headers- .get_all(header::SET_COOKIE)- .iter()- .filter_map(|value| value.to_str().ok())- .find_map(|value| {- let pair = value.split(';').next()?;- let token = pair- .strip_prefix("__Host-csrf_token=")- .or_else(|| pair.strip_prefix("csrf_token="))?;- (!token.is_empty()).then(|| token.to_owned())- })-}--fn assert_form_has_csrf(body: &str, action: &str, csrf_token: &str) {- let marker = format!(r#"action="{action}""#);- let Some(action_index) = body.find(&marker) else {- panic!("missing form action {action:?}\n{body}");- };- let csrf_marker = format!(r#"name="_csrf" value="{csrf_token}""#);- let tail = &body[action_index..];- let form = tail.find("</form>").map(|end| &tail[..end]).unwrap_or(tail);- assert!(- form.contains(&csrf_marker),- "form {action:?} did not include matching CSRF token {csrf_token:?}\n{body}"- );-}--async fn spawn_mock_api(api: Router) -> String {- let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- axum::serve(listener, api).await.unwrap();- });- format!("http://{addr}")-}--async fn mock_api(method: Method, uri: Uri) -> Response {- match (method, uri.path()) {- (Method::GET, "/admin/users/@me") => json_response(json!({ "user": admin_user() })),- (Method::GET, "/admin/report-reasons") => json_response(report_reasons()),- (Method::GET, "/admin/reports/1800000000000000001") => json_response(searched_report()),- _ => (StatusCode::NOT_FOUND, Json(json!({ "error": "not found" }))).into_response(),- }-}--fn json_response(value: Value) -> Response {- Json(value).into_response()-}--fn admin_user() -> Value {- let mut user = user("1500000000000000000", "AdminUser");- user["acls"] = json!(["*"]);- user-}--fn user(id: &str, username: &str) -> Value {- json!({- "id": id,- "username": username,- "discriminator": 1,- "avatar": null,- "banner": null,- "email": "[email protected]",- "email_verified": true,- "email_bounced": false,- "global_name": username,- "bio": null,- "pronouns": null,- "accent_color": null,- "date_of_birth": null,- "locale": "en-US",- "acls": [],- "traits": [],- "flags": "0",- "premium_flags": 0,- "bot": false,- "system": false,- "premium_type": null,- "premium_since": null,- "premium_until": null,- "premium_grace_ends_at": null,- "premium_lifetime_sequence": null,- "has_totp": false,- "authenticator_types": [],- "temp_banned_until": null,- "pending_deletion_at": null,- "pending_bulk_message_deletion_at": null,- "deletion_reason_code": null,- "deletion_public_reason": null,- "deletion_audit_log_reason": null,- "deletion_scheduled_by": null,- "deletion_scheduled_at": null,- "last_active_at": null,- "last_active_ip": null,- "last_active_ip_reverse": null,- "last_active_location": null- })-}--fn pending_registration(user_id: &str) -> Value {- json!({- "user_id": user_id,- "username": "applicant",- "discriminator": 0,- "global_name": null,- "email": "[email protected]",- "requested_at": "2026-10-14T12:00:00.000Z",- "registration_url_id": null,- "client_ip": "203.0.113.7"- })-}--fn searched_report() -> Value {- json!({- "report_id": "1800000000000000001",- "reporter_id": "1500000000000000000",- "reporter_tag": "AdminUser#0001",- "reported_at": "2026-05-26T12:00:00.000Z",- "status": 0,- "report_type": 1,- "category": "other",- "additional_info": "Mock report details",- "reported_user_id": "1500000000000000001",- "reported_user_tag": "SearchedUser#0001"- })-}--fn report_with_note() -> Value {- let mut report = searched_report();- report["notes"] = json!([{- "note_id": "1950000000000000001",- "author_id": "1500000000000000000",- "body": "Reporter sent more context by email",- "created_at": "2026-05-26T13:30:00.000Z"- }]);- report-}--fn report_reasons() -> Value {- json!({- "reasons": [- {- "key": "csam",- "label": "Child sexual abuse material",- "highest_priority": true,- "legacy_category_message": "child_safety",- "legacy_category_user": "child_safety",- "legacy_category_guild": "child_safety"- },- {- "key": "harassment",- "label": "Harassment or bullying",- "highest_priority": false,- "legacy_category_message": "harassment",- "legacy_category_user": "harassment",- "legacy_category_guild": "harassment"- }- ]- })-}--fn test_config(api_endpoint: String) -> AdminConfig {- AdminConfig {- host: "127.0.0.1".to_owned(),- port: 0,- secret_key_base: SECRET_KEY.to_owned(),- base_path: String::new(),- api_endpoint,- media_endpoint: "https://media.example.test".to_owned(),- static_cdn_endpoint: "https://static.example.test".to_owned(),- reports_bucket_origin: "https://reports.example.test".to_owned(),- admin_endpoint: "https://admin.example.test".to_owned(),- web_app_endpoint: "https://app.example.test".to_owned(),- oauth_client_id: "admin-client".to_owned(),- oauth_client_secret: "admin-secret".to_owned(),- oauth_redirect_uri: "https://admin.example.test/callback".to_owned(),- build_version: "test".to_owned(),- self_hosted: false,- proxy: ProxyConfig {- trust_client_ip_header: false,- client_ip_header_name: "x-forwarded-for".to_owned(),- },- }-}diff --git a/fluxer_admin/tests/notification_writes.rs b/fluxer_admin/tests/notification_writes.rsdeleted file mode 100644index 09c260061..000000000--- a/fluxer_admin/tests/notification_writes.rs+++ /dev/null@@ -1,413 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--#![recursion_limit = "256"]--use axum::{- Json, Router,- body::{Body, to_bytes},- extract::State,- http::{HeaderMap, Method, Request, StatusCode, Uri, header},- response::{IntoResponse, Response},-};-use fluxer_admin::{- build_router,- config::{AdminConfig, ProxyConfig},- session,-};-use serde_json::{Value, json};-use std::sync::{Arc, Mutex};-use tokio::net::TcpListener;-use tower::ServiceExt;--const SECRET_KEY: &str = "notification-writes-test-secret";-const USER_ID: &str = "1500000000000000001";-const REPORT_ID: &str = "1600000000000000001";--#[derive(Clone)]-struct CapturedRequest {- route: String,- audit_log_reason: Option<String>,- body: Value,-}--type CapturedRequests = Arc<Mutex<Vec<CapturedRequest>>>;--async fn submit(uri: &str, fields: &str) -> CapturedRequest {- let app = setup().await;- let csrf_token = csrf_token(&app).await;- let status = post_form(&app, uri, &format!("_csrf={csrf_token}&{fields}")).await;- assert_eq!(status, StatusCode::SEE_OTHER);- let captured = app.captured.lock().expect("captured requests");- assert_eq!(captured.len(), 1, "expected one write request");- captured[0].clone()-}--#[tokio::test]-async fn unban_sends_the_internal_note_as_a_header_and_no_body() {- let uri = format!("/users/{USER_ID}?action=unban&tab=moderation");- let captured = submit(&uri, "internal_note=Private%20staff%20note").await;- assert_eq!(captured.route, format!("DELETE /admin/users/{USER_ID}/ban"));- assert_eq!(- captured.audit_log_reason.as_deref(),- Some("Private staff note")- );- assert!(!captured.body.to_string().contains("Private staff note"));-}--const DECISION_FIELDS: &str = "reason_code=3&source=own_review&automation=none&statement=You%20sent%20the%20same%20link%20to%20many%20people.";--#[tokio::test]-async fn close_sends_the_basis_and_never_a_notify_flag() {- let uri = format!("/users/{USER_ID}?action=close&tab=moderation");- let holder = submit(- &uri,- "basis=holder_request&days_until_deletion=30&internal_note=Asked%20by%20email",- )- .await;- assert_eq!(holder.route, format!("PUT /admin/users/{USER_ID}/deletion"));- assert_eq!(- holder.body,- json!({"basis": {"type": "holder_request"}, "days_until_deletion": 30})- );- assert_eq!(holder.audit_log_reason.as_deref(), Some("Asked by email"));- let enforcement = submit(- &uri,- &format!(- "basis=enforcement&days_until_deletion=74&{DECISION_FIELDS}&internal_note=Spam%20review&remove_evidence=true"- ),- )- .await;- assert_eq!(enforcement.body["basis"]["type"], json!("enforcement"));- assert_eq!(- enforcement.body["basis"]["decision"]["reason_code"],- json!(3)- );- assert_eq!(enforcement.body["remove_evidence"], json!(true));- assert_eq!(enforcement.audit_log_reason.as_deref(), Some("Spam review"));- assert!(enforcement.body.get("notify_user").is_none());-}--#[tokio::test]-async fn cancel_deletion_sends_only_the_pending_deletion() {- let uri = format!("/users/{USER_ID}?action=cancel_deletion&tab=moderation");- let captured = submit(- &uri,- "expected_pending_deletion_at=2026-12-01T00%3A00%3A00.000Z&confirm=true&internal_note=Asked%20to%20keep%20it",- )- .await;- assert_eq!(- captured.route,- format!("DELETE /admin/users/{USER_ID}/deletion")- );- assert_eq!(- captured.body,- json!({"expected_pending_deletion_at": "2026-12-01T00:00:00.000Z"})- );- assert_eq!(- captured.audit_log_reason.as_deref(),- Some("Asked to keep it")- );-}--#[tokio::test]-async fn limit_features_sends_one_limit_with_its_end() {- let uri = format!("/users/{USER_ID}?action=limit_features&tab=moderation");- let captured = submit(- &uri,- "limit=reports&ends_on=2026-12-01&reason_code=29&source=own_review&automation=none&statement=False%20reports&internal_note=Report%20review",- )- .await;- assert_eq!(- captured.route,- format!("PUT /admin/users/{USER_ID}/feature-limits")- );- assert_eq!(captured.body["limit"], json!("reports"));- assert_eq!(captured.body["ends_at"], json!("2026-12-01T00:00:00Z"));- assert_eq!(captured.body["decision"]["reason_code"], json!(29));- let purchases = submit(- &uri,- "limit=purchases&ends_on=2026-12-01&reason_code=14&source=own_review&automation=none&statement=Disputes&internal_note=Billing",- )- .await;- assert!(purchases.body.get("ends_at").is_none());-}--#[tokio::test]-async fn bulk_close_sends_one_bulk_decision() {- let captured = submit(- "/bulk-actions?action=bulk-schedule-user-deletion",- &format!(- "user_ids={USER_ID}&basis=enforcement&days_until_deletion=74&reason_code=3&automation=none&statement=Same%20invite%20link&internal_note=Spam%20sweep"- ),- )- .await;- assert_eq!(captured.route, "POST /admin/bulk-jobs");- assert_eq!(captured.body["task"], json!("schedule_user_deletion"));- assert_eq!(- captured.body["basis"],- json!({- "type": "enforcement",- "decision": {- "reason_code": 3,- "source": "own_review",- "automation": "none",- "statement": "Same invite link"- }- })- );- assert_eq!(captured.audit_log_reason.as_deref(), Some("Spam sweep"));-}--#[tokio::test]-async fn report_resolve_sends_notify_reporter_from_the_checkbox() {- let uri = format!("/reports/{REPORT_ID}/resolve");- let checked = submit(- &uri,- "resolution=actioned&outcome=removed&public_comment=Handled¬ify_reporter_present=1¬ify_reporter=true",- )- .await;- assert_eq!(checked.route, format!("PATCH /admin/reports/{REPORT_ID}"));- assert_eq!(checked.body["public_comment"], json!("Handled"));- assert_eq!(checked.body["resolution"], json!("actioned"));- assert_eq!(checked.body["outcome"], json!("removed"));- assert_eq!(checked.body["notify_reporter"], json!(true));- let unchecked = submit(- &uri,- "resolution=no_violation&public_comment=Handled¬ify_reporter_present=1",- )- .await;- assert_eq!(unchecked.body["notify_reporter"], json!(false));- assert_eq!(unchecked.body["outcome"], json!("no_violation"));- let duplicate = submit(- &uri,- "resolution=duplicate&outcome=restricted&duplicate_of=1400000000000000001&public_comment=Handled",- )- .await;- assert_eq!(duplicate.body["notify_reporter"], json!(true));- assert!(duplicate.body.get("outcome").is_none());- assert_eq!(duplicate.body["duplicate_of"], json!("1400000000000000001"));- let warned = submit(&uri, "resolution=actioned&outcome=warned").await;- assert_eq!(warned.body["outcome"], json!("warned"));- let other_action = submit(&uri, "resolution=actioned&outcome=action_taken").await;- assert_eq!(other_action.body["outcome"], json!("action_taken"));-}--struct TestApp {- router: Router,- session_cookie: String,- captured: CapturedRequests,-}--async fn setup() -> TestApp {- let captured: CapturedRequests = Arc::new(Mutex::new(Vec::new()));- let api_endpoint = spawn_mock_api(Arc::clone(&captured)).await;- let router = build_router(test_config(api_endpoint));- let session_value = session::create_session("1500000000000000000", "test-token", SECRET_KEY);- TestApp {- router,- session_cookie: format!("{}={session_value}", session::SESSION_COOKIE_NAME),- captured,- }-}--async fn csrf_token(app: &TestApp) -> String {- let response = app- .router- .clone()- .oneshot(- Request::builder()- .method(Method::GET)- .uri("/voice-regions")- .header(header::COOKIE, &app.session_cookie)- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::OK);- response- .headers()- .get_all(header::SET_COOKIE)- .iter()- .filter_map(|value| value.to_str().ok())- .find_map(|value| {- let pair = value.split(';').next()?;- let token = pair- .strip_prefix("__Host-csrf_token=")- .or_else(|| pair.strip_prefix("csrf_token="))?;- (!token.is_empty()).then(|| token.to_owned())- })- .expect("csrf_token cookie")-}--async fn post_form(app: &TestApp, uri: &str, body: &str) -> StatusCode {- let csrf = body- .split('&')- .find_map(|pair| pair.strip_prefix("_csrf="))- .expect("form has a csrf token");- let response = app- .router- .clone()- .oneshot(- Request::builder()- .method(Method::POST)- .uri(uri)- .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")- .header(- header::COOKIE,- format!("{}; __Host-csrf_token={csrf}", app.session_cookie),- )- .body(Body::from(body.to_owned()))- .unwrap(),- )- .await- .unwrap();- response.status()-}--async fn spawn_mock_api(captured: CapturedRequests) -> String {- let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- axum::serve(- listener,- Router::new().fallback(mock_api).with_state(captured),- )- .await- .unwrap();- });- format!("http://{addr}")-}--async fn mock_api(- State(captured): State<CapturedRequests>,- method: Method,- uri: Uri,- headers: HeaderMap,- request: Request<Body>,-) -> Response {- let path = uri.path().to_owned();- if method != Method::GET {- let bytes = to_bytes(request.into_body(), usize::MAX).await.unwrap();- let body: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);- let audit_log_reason = headers- .get("x-audit-log-reason")- .and_then(|value| value.to_str().ok())- .map(ToOwned::to_owned);- captured- .lock()- .expect("captured requests")- .push(CapturedRequest {- route: format!("{method} {path}"),- audit_log_reason,- body,- });- }- match (method, path.as_str()) {- (Method::GET, "/admin/users/@me") => Json(json!({ "user": admin_user() })).into_response(),- (Method::GET, "/admin/voice/regions") => {- Json(json!({ "regions": [region()] })).into_response()- }- (Method::PUT | Method::DELETE, _) if path.starts_with("/admin/users/") => {- Json(json!({ "user": admin_user() })).into_response()- }- (Method::POST, "/admin/bulk-jobs") => Json(json!({ "job_id": "1" })).into_response(),- (Method::PATCH, _) if path.starts_with("/admin/reports/") => Json(json!({- "report_id": REPORT_ID,- "status": 1,- "resolved_at": null,- "public_comment": null- }))- .into_response(),- _ => (- StatusCode::NOT_FOUND,- Json(json!({ "message": "not found" })),- )- .into_response(),- }-}--fn region() -> Value {- json!({- "id": "europe-north",- "name": "Northern Europe",- "emoji": "flag",- "latitude": 59.33,- "longitude": 18.06,- "is_default": true,- "vip_only": false,- "required_guild_features": [],- "allowed_guild_ids": [],- "allowed_user_ids": [],- "created_at": null,- "updated_at": null- })-}--fn admin_user() -> Value {- json!({- "id": "1500000000000000000",- "username": "AdminUser",- "discriminator": 1,- "avatar": null,- "banner": null,- "email": "[email protected]",- "email_verified": true,- "email_bounced": false,- "global_name": "AdminUser",- "bio": null,- "pronouns": null,- "accent_color": null,- "date_of_birth": null,- "locale": "en-US",- "acls": ["*"],- "traits": [],- "flags": "0",- "premium_flags": 0,- "bot": false,- "system": false,- "premium_type": null,- "premium_since": null,- "premium_until": null,- "premium_grace_ends_at": null,- "premium_lifetime_sequence": null,- "has_totp": false,- "authenticator_types": [],- "temp_banned_until": null,- "pending_deletion_at": null,- "pending_bulk_message_deletion_at": null,- "deletion_reason_code": null,- "deletion_public_reason": null,- "deletion_audit_log_reason": null,- "deletion_scheduled_by": null,- "deletion_scheduled_at": null,- "last_active_at": null,- "last_active_ip": null,- "last_active_ip_reverse": null,- "last_active_location": null- })-}--fn test_config(api_endpoint: String) -> AdminConfig {- AdminConfig {- host: "127.0.0.1".to_owned(),- port: 0,- secret_key_base: SECRET_KEY.to_owned(),- base_path: String::new(),- api_endpoint,- media_endpoint: "https://media.example.test".to_owned(),- static_cdn_endpoint: "https://static.example.test".to_owned(),- reports_bucket_origin: "https://reports.example.test".to_owned(),- admin_endpoint: "https://admin.example.test".to_owned(),- web_app_endpoint: "https://app.example.test".to_owned(),- oauth_client_id: "admin-client".to_owned(),- oauth_client_secret: "admin-secret".to_owned(),- oauth_redirect_uri: "https://admin.example.test/callback".to_owned(),- build_version: "test".to_owned(),- self_hosted: false,- proxy: ProxyConfig {- trust_client_ip_header: false,- client_ip_header_name: "x-forwarded-for".to_owned(),- },- }-}diff --git a/fluxer_admin/tests/password_reset_link.rs b/fluxer_admin/tests/password_reset_link.rsdeleted file mode 100644index a35dde9af..000000000--- a/fluxer_admin/tests/password_reset_link.rs+++ /dev/null@@ -1,366 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--#![recursion_limit = "256"]--use axum::{- Json, Router,- body::{Body, to_bytes},- extract::State,- http::{Method, Request, StatusCode, Uri, header},- response::{IntoResponse, Response},-};-use fluxer_admin::{- build_router,- config::{AdminConfig, ProxyConfig},- session,-};-use serde_json::{Value, json};-use std::sync::{Arc, Mutex};-use tokio::net::TcpListener;-use tower::ServiceExt;--const SECRET_KEY: &str = "password-reset-link-test-secret";-const ADMIN_ID: &str = "1500000000000000000";-const TARGET_ID: &str = "1500000000000000042";-const RESET_URL: &str = "https://chat.example.test/reset#token=one-time-reset-token";--#[derive(Clone)]-struct MockApi {- account_identity: &'static str,- admin_acls: Vec<&'static str>,- requests: Arc<Mutex<Vec<String>>>,-}--#[tokio::test]-async fn an_htmx_reset_link_request_gets_only_the_result_fragment() {- let app = setup(true, "username", vec!["*"]).await;- let page = get(&app, &format!("/users/{TARGET_ID}?tab=account")).await;- assert!(page.contains(r##"hx-target="#password-reset-link-result""##));- assert!(page.contains(r#"hx-push-url="false""#));- let csrf_token = csrf_token(&app).await;- let (status, body) = post_form_with_headers(- &app,- &format!("/users/{TARGET_ID}?action=create_password_reset_link&tab=account"),- &format!("_csrf={csrf_token}"),- &[- ("HX-Request", "true"),- ("HX-Target", "password-reset-link-result"),- ],- )- .await;- assert_eq!(status, StatusCode::OK);- assert!(- body.starts_with(r#"<div id="password-reset-link-result""#),- "{body}"- );- assert!(body.contains(r#"hx-history="false""#));- assert!(body.contains(&format!(r#"data-copy-value="{RESET_URL}""#)));- assert!(!body.contains("<html"));- assert!(!body.contains("Create Password Reset Link"));-}--#[tokio::test]-async fn revoking_a_recovery_kit_calls_the_api() {- let app = setup(true, "username", vec!["*"]).await;- let page = get(&app, &format!("/users/{TARGET_ID}?tab=account")).await;- assert!(page.contains("Revoke Recovery Kit"));- let csrf_token = csrf_token(&app).await;- let (status, _) = post_form(- &app,- &format!("/users/{TARGET_ID}?action=revoke_recovery_kit&tab=account"),- &format!("_csrf={csrf_token}"),- )- .await;- assert!(status.is_redirection() || status.is_success(), "{status}");- assert!(app.saw(&format!("DELETE /admin/users/{TARGET_ID}/recovery-kit")));-}--#[tokio::test]-async fn the_revoke_recovery_kit_action_needs_its_acl_and_a_username_instance() {- let without_acl = setup(- true,- "username",- vec![- "admin:authenticate",- "user:lookup",- "user:create:password_reset_link",- ],- )- .await;- let page = get(&without_acl, &format!("/users/{TARGET_ID}?tab=account")).await;- assert!(page.contains("Create Password Reset Link"));- assert!(!page.contains("Revoke Recovery Kit"));-- let with_acl = setup(- true,- "username",- vec![- "admin:authenticate",- "user:lookup",- "user:delete:recovery_kit",- ],- )- .await;- let page = get(&with_acl, &format!("/users/{TARGET_ID}?tab=account")).await;- assert!(page.contains("Revoke Recovery Kit"));-- let email = setup(true, "email", vec!["*"]).await;- let page = get(&email, &format!("/users/{TARGET_ID}?tab=account")).await;- assert!(!page.contains("Revoke Recovery Kit"));-}--#[tokio::test]-async fn the_reset_link_action_needs_its_acl() {- let app = setup(true, "username", vec!["admin:authenticate", "user:lookup"]).await;- let page = get(&app, &format!("/users/{TARGET_ID}?tab=account")).await;- assert!(page.contains("Terminate All Sessions"));- assert!(!page.contains("Create Password Reset Link"));- assert!(!page.contains("Send Password Reset"));-}--struct TestApp {- router: Router,- session_cookie: String,- requests: Arc<Mutex<Vec<String>>>,-}--impl TestApp {- fn saw(&self, route: &str) -> bool {- self.requests- .lock()- .expect("requests")- .iter()- .any(|seen| seen == route)- }-}--async fn setup(- self_hosted: bool,- account_identity: &'static str,- admin_acls: Vec<&'static str>,-) -> TestApp {- let requests = Arc::new(Mutex::new(Vec::new()));- let api_endpoint = spawn_mock_api(MockApi {- account_identity,- admin_acls,- requests: Arc::clone(&requests),- })- .await;- let router = build_router(test_config(api_endpoint, self_hosted));- let session_value = session::create_session(ADMIN_ID, "test-token", SECRET_KEY);- TestApp {- router,- session_cookie: format!("{}={session_value}", session::SESSION_COOKIE_NAME),- requests,- }-}--async fn get(app: &TestApp, uri: &str) -> String {- let response = app- .router- .clone()- .oneshot(- Request::builder()- .method(Method::GET)- .uri(uri)- .header(header::COOKIE, &app.session_cookie)- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::OK, "{uri}");- body_text(response).await-}--async fn csrf_token(app: &TestApp) -> String {- let response = app- .router- .clone()- .oneshot(- Request::builder()- .method(Method::GET)- .uri(format!("/users/{TARGET_ID}?tab=account"))- .header(header::COOKIE, &app.session_cookie)- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::OK);- response- .headers()- .get_all(header::SET_COOKIE)- .iter()- .filter_map(|value| value.to_str().ok())- .find_map(|value| {- let pair = value.split(';').next()?;- let token = pair- .strip_prefix("__Host-csrf_token=")- .or_else(|| pair.strip_prefix("csrf_token="))?;- (!token.is_empty()).then(|| token.to_owned())- })- .expect("csrf_token cookie")-}--async fn post_form(app: &TestApp, uri: &str, body: &str) -> (StatusCode, String) {- post_form_with_headers(app, uri, body, &[]).await-}--async fn post_form_with_headers(- app: &TestApp,- uri: &str,- body: &str,- headers: &[(&str, &str)],-) -> (StatusCode, String) {- let csrf = body- .split('&')- .find_map(|pair| pair.strip_prefix("_csrf="))- .expect("form carries a csrf token");- let mut request = Request::builder()- .method(Method::POST)- .uri(uri)- .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")- .header(- header::COOKIE,- format!("{}; __Host-csrf_token={csrf}", app.session_cookie),- );- for (name, value) in headers {- request = request.header(*name, *value);- }- let response = app- .router- .clone()- .oneshot(request.body(Body::from(body.to_owned())).unwrap())- .await- .unwrap();- let status = response.status();- (status, body_text(response).await)-}--async fn body_text(response: Response) -> String {- let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();- String::from_utf8(bytes.to_vec()).unwrap()-}--async fn spawn_mock_api(mock: MockApi) -> String {- let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- axum::serve(listener, Router::new().fallback(mock_api).with_state(mock))- .await- .unwrap();- });- format!("http://{addr}")-}--async fn mock_api(State(mock): State<MockApi>, method: Method, uri: Uri) -> Response {- let path = uri.path().to_owned();- mock.requests- .lock()- .expect("requests")- .push(format!("{method} {path}"));- let target_user = format!("/admin/users/{TARGET_ID}");- let target_sessions = format!("{target_user}/sessions");- let target_credentials = format!("{target_user}/webauthn-credentials");- let target_reset_link = format!("{target_user}/password-reset-link");- let target_recovery_kit = format!("{target_user}/recovery-kit");- match (method, path.as_str()) {- (Method::GET, "/admin/users/@me") => Json(json!({- "user": user(ADMIN_ID, "AdminUser", &mock.admin_acls)- }))- .into_response(),- (Method::GET, "/.well-known/fluxer") => Json(json!({- "features": {- "premium_enabled": false,- "account_identity": mock.account_identity- }- }))- .into_response(),- (Method::GET, p) if p == target_user => Json(json!({- "users": [user(TARGET_ID, "member", &[])]- }))- .into_response(),- (Method::GET, p) if p == target_sessions => Json(json!({ "sessions": [] })).into_response(),- (Method::GET, p) if p == target_credentials => Json(json!([])).into_response(),- (Method::POST, p) if p == target_reset_link => Json(json!({- "url": RESET_URL,- "expires_at": "2026-10-01T13:00:00.000Z"- }))- .into_response(),- (Method::DELETE, p) if p == target_recovery_kit => StatusCode::NO_CONTENT.into_response(),- _ => (- StatusCode::NOT_FOUND,- Json(json!({ "message": "not found" })),- )- .into_response(),- }-}--fn user(id: &str, username: &str, acls: &[&str]) -> Value {- json!({- "id": id,- "username": username,- "discriminator": 1,- "avatar": null,- "banner": null,- "email": null,- "email_verified": false,- "email_bounced": false,- "global_name": username,- "bio": null,- "pronouns": null,- "accent_color": null,- "date_of_birth": null,- "locale": "en-GB",- "acls": acls,- "traits": [],- "flags": "0",- "premium_flags": 0,- "bot": false,- "system": false,- "premium_type": null,- "premium_since": null,- "premium_until": null,- "premium_grace_ends_at": null,- "premium_lifetime_sequence": null,- "has_totp": false,- "authenticator_types": [],- "temp_banned_until": null,- "pending_deletion_at": null,- "pending_bulk_message_deletion_at": null,- "deletion_reason_code": null,- "deletion_public_reason": null,- "deletion_audit_log_reason": null,- "deletion_scheduled_by": null,- "deletion_scheduled_at": null,- "last_active_at": null,- "last_active_ip": null,- "last_active_ip_reverse": null,- "last_active_location": null- })-}--fn test_config(api_endpoint: String, self_hosted: bool) -> AdminConfig {- AdminConfig {- host: "127.0.0.1".to_owned(),- port: 0,- secret_key_base: SECRET_KEY.to_owned(),- base_path: String::new(),- api_endpoint,- media_endpoint: "https://media.example.test".to_owned(),- static_cdn_endpoint: "https://static.example.test".to_owned(),- reports_bucket_origin: String::new(),- admin_endpoint: "https://admin.example.test".to_owned(),- web_app_endpoint: "https://app.example.test".to_owned(),- oauth_client_id: "admin-client".to_owned(),- oauth_client_secret: "admin-secret".to_owned(),- oauth_redirect_uri: "https://admin.example.test/callback".to_owned(),- build_version: "test".to_owned(),- self_hosted,- proxy: ProxyConfig {- trust_client_ip_header: false,- client_ip_header_name: "x-forwarded-for".to_owned(),- },- }-}diff --git a/fluxer_admin/tests/voice_restriction_writes.rs b/fluxer_admin/tests/voice_restriction_writes.rsdeleted file mode 100644index 71c12ecf9..000000000--- a/fluxer_admin/tests/voice_restriction_writes.rs+++ /dev/null@@ -1,336 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--#![recursion_limit = "256"]--use axum::{- Json, Router,- body::{Body, to_bytes},- extract::State,- http::{Method, Request, StatusCode, Uri, header},- response::{IntoResponse, Response},-};-use fluxer_admin::{- build_router,- config::{AdminConfig, ProxyConfig},- session,-};-use serde_json::{Value, json};-use std::sync::{Arc, Mutex};-use tokio::net::TcpListener;-use tower::ServiceExt;--const SECRET_KEY: &str = "voice-restriction-writes-test-secret";-const REGION_ID: &str = "europe-north";-const SERVER_ID: &str = "europe-north-server-1";--type CapturedBodies = Arc<Mutex<Vec<(String, Value)>>>;--#[tokio::test]-async fn clearing_the_restriction_fields_reaches_the_api_as_empty_lists() {- let app = setup().await;- let csrf_token = csrf_token(&app).await;- let status = post_form(- &app,- "/voice-servers?action=update",- &format!(- "_csrf={csrf_token}®ion_id={REGION_ID}&server_id={SERVER_ID}\- &endpoint=wss%3A%2F%2Fvoice.example.com&is_active=true\- &required_guild_features=&allowed_guild_ids=&soft_connection_limit="- ),- )- .await;- assert_eq!(status, StatusCode::SEE_OTHER);-- let body = captured_body(- &app,- "PATCH /admin/voice/regions/europe-north/servers/europe-north-server-1",- );- assert_eq!(body["required_guild_features"], json!([]));- assert_eq!(body["allowed_guild_ids"], json!([]));- assert_eq!(body["soft_connection_limit"], Value::Null);- assert_eq!(body["vip_only"], json!(false));-}--#[tokio::test]-async fn activating_a_server_leaves_the_restriction_fields_untouched() {- let app = setup().await;- let csrf_token = csrf_token(&app).await;- let status = post_form(- &app,- "/voice-servers?action=update",- &format!(- "_csrf={csrf_token}®ion_id={REGION_ID}&server_id={SERVER_ID}\- &endpoint=wss%3A%2F%2Fvoice.example.com&is_active=false&vip_only=true"- ),- )- .await;- assert_eq!(status, StatusCode::SEE_OTHER);-- let body = captured_body(- &app,- "PATCH /admin/voice/regions/europe-north/servers/europe-north-server-1",- );- let object = body.as_object().expect("object body");- assert!(!object.contains_key("required_guild_features"));- assert!(!object.contains_key("allowed_guild_ids"));- assert_eq!(body["is_active"], json!(false));- assert_eq!(body["vip_only"], json!(true));-}--#[tokio::test]-async fn clearing_the_region_restriction_fields_reaches_the_api_as_empty_lists() {- let app = setup().await;- let csrf_token = csrf_token(&app).await;- let status = post_form(- &app,- "/voice-regions?action=update",- &format!(- "_csrf={csrf_token}&id={REGION_ID}&name=Northern%20Europe&emoji=%F0%9F%87%B8%F0%9F%87%AA\- &latitude=59.33&longitude=18.06&required_guild_features=&allowed_guild_ids="- ),- )- .await;- assert_eq!(status, StatusCode::SEE_OTHER);-- let body = captured_body(&app, "PATCH /admin/voice/regions/europe-north");- assert_eq!(body["required_guild_features"], json!([]));- assert_eq!(body["allowed_guild_ids"], json!([]));-}--struct TestApp {- router: Router,- session_cookie: String,- captured: CapturedBodies,-}--async fn setup() -> TestApp {- let captured: CapturedBodies = Arc::new(Mutex::new(Vec::new()));- let api_endpoint = spawn_mock_api(Arc::clone(&captured)).await;- let router = build_router(test_config(api_endpoint));- let session_value = session::create_session("1500000000000000000", "test-token", SECRET_KEY);- TestApp {- router,- session_cookie: format!("{}={session_value}", session::SESSION_COOKIE_NAME),- captured,- }-}--fn captured_body(app: &TestApp, route: &str) -> Value {- let captured = app.captured.lock().expect("captured bodies");- captured- .iter()- .find(|(seen, _)| seen == route)- .map(|(_, body)| body.clone())- .unwrap_or_else(|| {- panic!(- "no request captured for {route}, saw {:?}",- captured.iter().map(|(seen, _)| seen).collect::<Vec<_>>()- )- })-}--async fn csrf_token(app: &TestApp) -> String {- let response = app- .router- .clone()- .oneshot(- Request::builder()- .method(Method::GET)- .uri("/voice-regions")- .header(header::COOKIE, &app.session_cookie)- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(response.status(), StatusCode::OK);- response- .headers()- .get_all(header::SET_COOKIE)- .iter()- .filter_map(|value| value.to_str().ok())- .find_map(|value| {- let pair = value.split(';').next()?;- let token = pair- .strip_prefix("__Host-csrf_token=")- .or_else(|| pair.strip_prefix("csrf_token="))?;- (!token.is_empty()).then(|| token.to_owned())- })- .expect("csrf_token cookie")-}--async fn post_form(app: &TestApp, uri: &str, body: &str) -> StatusCode {- let csrf = body- .split('&')- .find_map(|pair| pair.strip_prefix("_csrf="))- .expect("form has a csrf token");- let response = app- .router- .clone()- .oneshot(- Request::builder()- .method(Method::POST)- .uri(uri)- .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")- .header(- header::COOKIE,- format!("{}; __Host-csrf_token={csrf}", app.session_cookie),- )- .body(Body::from(body.to_owned()))- .unwrap(),- )- .await- .unwrap();- response.status()-}--async fn spawn_mock_api(captured: CapturedBodies) -> String {- let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- axum::serve(- listener,- Router::new().fallback(mock_api).with_state(captured),- )- .await- .unwrap();- });- format!("http://{addr}")-}--async fn mock_api(- State(captured): State<CapturedBodies>,- method: Method,- uri: Uri,- request: Request<Body>,-) -> Response {- let path = uri.path().to_owned();- if method == Method::PATCH {- let bytes = to_bytes(request.into_body(), usize::MAX).await.unwrap();- let body: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);- captured- .lock()- .expect("captured bodies")- .push((format!("PATCH {path}"), body));- }- match (method, path.as_str()) {- (Method::GET, "/admin/users/@me") => Json(json!({ "user": admin_user() })).into_response(),- (Method::PATCH, "/admin/voice/regions/europe-north") => {- Json(json!({ "region": region() })).into_response()- }- (Method::PATCH, "/admin/voice/regions/europe-north/servers/europe-north-server-1") => {- Json(json!({ "server": server() })).into_response()- }- (Method::GET, "/admin/voice/regions") => {- Json(json!({ "regions": [region()] })).into_response()- }- _ => (- StatusCode::NOT_FOUND,- Json(json!({ "message": "not found" })),- )- .into_response(),- }-}--fn region() -> Value {- json!({- "id": REGION_ID,- "name": "Northern Europe",- "emoji": "flag",- "latitude": 59.33,- "longitude": 18.06,- "is_default": true,- "vip_only": false,- "required_guild_features": [],- "allowed_guild_ids": [],- "allowed_user_ids": [],- "created_at": null,- "updated_at": null- })-}--fn server() -> Value {- json!({- "region_id": REGION_ID,- "server_id": SERVER_ID,- "endpoint": "wss://voice.example.com",- "latitude": null,- "longitude": null,- "is_active": true,- "soft_connection_limit": null,- "vip_only": false,- "required_guild_features": [],- "allowed_guild_ids": [],- "allowed_user_ids": [],- "created_at": null,- "updated_at": null- })-}--fn admin_user() -> Value {- json!({- "id": "1500000000000000000",- "username": "AdminUser",- "discriminator": 1,- "avatar": null,- "banner": null,- "email": "[email protected]",- "email_verified": true,- "email_bounced": false,- "global_name": "AdminUser",- "bio": null,- "pronouns": null,- "accent_color": null,- "date_of_birth": null,- "locale": "en-US",- "acls": ["*"],- "traits": [],- "flags": "0",- "premium_flags": 0,- "bot": false,- "system": false,- "premium_type": null,- "premium_since": null,- "premium_until": null,- "premium_grace_ends_at": null,- "premium_lifetime_sequence": null,- "has_totp": false,- "authenticator_types": [],- "temp_banned_until": null,- "pending_deletion_at": null,- "pending_bulk_message_deletion_at": null,- "deletion_reason_code": null,- "deletion_public_reason": null,- "deletion_audit_log_reason": null,- "deletion_scheduled_by": null,- "deletion_scheduled_at": null,- "last_active_at": null,- "last_active_ip": null,- "last_active_ip_reverse": null,- "last_active_location": null- })-}--fn test_config(api_endpoint: String) -> AdminConfig {- AdminConfig {- host: "127.0.0.1".to_owned(),- port: 0,- secret_key_base: SECRET_KEY.to_owned(),- base_path: String::new(),- api_endpoint,- media_endpoint: "https://media.example.test".to_owned(),- static_cdn_endpoint: "https://static.example.test".to_owned(),- reports_bucket_origin: "https://reports.example.test".to_owned(),- admin_endpoint: "https://admin.example.test".to_owned(),- web_app_endpoint: "https://app.example.test".to_owned(),- oauth_client_id: "admin-client".to_owned(),- oauth_client_secret: "admin-secret".to_owned(),- oauth_redirect_uri: "https://admin.example.test/callback".to_owned(),- build_version: "test".to_owned(),- self_hosted: false,- proxy: ProxyConfig {- trust_client_ip_header: false,- client_ip_header_name: "x-forwarded-for".to_owned(),- },- }-}