feat(reports): add server-driven report flows (#3330)

This commit is contained in:
Hampus authored and GitHub committed 2026-10-09 01:38:00 +02:00
1 parent bc17922b02
commit ece622e800
471 files changed
+56262 -35932

No files matched your search

+7 -2
View File
@@ -8,6 +8,7 @@ use crate::{
flash::{self, FlashData},
},
state::AppState,
templates::components::message_list::MessageActions,
utils::forms::MultiValueForm,
};
use axum::{
@@ -321,7 +322,11 @@ pub(crate) async fn messages_browse_fragment(
.as_ref()
.map(|user| user.acls.as_slice())
.unwrap_or(&[]);
let can_delete = acl::has_permission(admin_acls, acl::MESSAGE_DELETE);
let actions = MessageActions {
delete: acl::has_permission(admin_acls, acl::MESSAGE_DELETE),
ncmec: acl::has_all_permissions(admin_acls, acl::NCMEC_ATTACHMENT_REPORT),
source_report_id: None,
};
let client = AdminApiClient::new(state.http_client(), config, &auth.0.session);
let result = client
.browse_channel(
@@ -334,7 +339,7 @@ pub(crate) async fn messages_browse_fragment(
match result {
Ok(resp) => {
let markup = crate::templates::pages::messages_page::browse_messages_fragment(
config, &resp.data, can_delete, None,
config, &resp.data, actions, None,
);
Html(markup.into_string()).into_response()
}
+2
View File
@@ -73,6 +73,7 @@ async fn messages_page(
.unwrap_or(&[]);
let can_lookup = acl::has_permission(admin_acls, acl::MESSAGE_LOOKUP);
let can_delete = acl::has_permission(admin_acls, acl::MESSAGE_DELETE);
let can_report_ncmec = acl::has_all_permissions(admin_acls, acl::NCMEC_ATTACHMENT_REPORT);
let client = AdminApiClient::new(state.http_client(), config, &auth.0.session);
let channel_id = query.channel_id.as_deref().filter(|s| !s.is_empty());
let message_id = query.message_id.as_deref().filter(|s| !s.is_empty());
@@ -137,6 +138,7 @@ async fn messages_page(
prefill_channel_id: channel_id,
can_lookup,
can_delete,
can_report_ncmec,
lookup_result: lookup_result.as_ref(),
browse_result: browse_result.as_ref(),
search_result: search_result.as_ref(),
+244 -21
View File
@@ -1,9 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
use crate::{
acl,
api::{
client::{AdminApiClient, ApiResultExt},
client::{AdminApiClient, ApiError, ApiResultExt},
reports::SearchReportsParams,
types::ReportEntry,
},
config::AdminConfig,
middleware::{
@@ -14,7 +16,7 @@ use crate::{
},
state::AppState,
templates,
utils::forms::clean_string,
utils::{forms::clean_string, timestamps::format_admin_timestamp},
};
use axum::{
Form, Router,
@@ -35,8 +37,10 @@ struct ReportsQuery {
#[serde(rename = "type")]
report_type: Option<String>,
category: Option<String>,
reason: Option<String>,
reporter_id: Option<String>,
reported_user_id: Option<String>,
reported_webhook_id: Option<String>,
reported_guild_id: Option<String>,
reported_channel_id: Option<String>,
guild_context_id: Option<String>,
@@ -46,6 +50,18 @@ struct ReportsQuery {
page: Option<u32>,
}
#[derive(Deserialize)]
struct LegalHoldForm {
#[serde(default)]
_csrf: Option<String>,
#[serde(default)]
legal_hold_until: Option<String>,
#[serde(default)]
legal_hold_reason: Option<String>,
#[serde(default)]
clear: Option<String>,
}
#[derive(Deserialize)]
struct ResolveForm {
#[serde(default)]
@@ -67,6 +83,10 @@ pub fn router() -> Router<AppState> {
"/reports/{report_id}/resolve",
axum::routing::post(report_resolve),
)
.route(
"/reports/{report_id}/legal-hold",
axum::routing::post(report_legal_hold),
)
}
async fn reports_list(
@@ -95,25 +115,30 @@ async fn reports_list(
.report_type
.as_deref()
.and_then(|s| s.parse::<i32>().ok());
let reports = client
.search_reports(&SearchReportsParams {
query: search_query.as_deref(),
status,
report_type,
category: query.category.as_deref(),
reporter_id: query.reporter_id.as_deref(),
reported_user_id: query.reported_user_id.as_deref(),
reported_guild_id: query.reported_guild_id.as_deref(),
reported_channel_id: query.reported_channel_id.as_deref(),
guild_context_id: query.guild_context_id.as_deref(),
resolved_by_admin_id: query.resolved_by_admin_id.as_deref(),
sort_by: Some(sort_by),
sort_order: Some(sort_order),
limit,
offset,
})
.await
.log_error("search reports");
let reason = query.reason.as_deref().and_then(clean_string);
let params = SearchReportsParams {
query: search_query.as_deref(),
status,
report_type,
category: query.category.as_deref(),
reason: reason.as_deref(),
reporter_id: query.reporter_id.as_deref(),
reported_user_id: query.reported_user_id.as_deref(),
reported_webhook_id: query.reported_webhook_id.as_deref(),
reported_guild_id: query.reported_guild_id.as_deref(),
reported_channel_id: query.reported_channel_id.as_deref(),
guild_context_id: query.guild_context_id.as_deref(),
resolved_by_admin_id: query.resolved_by_admin_id.as_deref(),
sort_by: Some(sort_by),
sort_order: Some(sort_order),
limit,
offset,
};
let (reports, reasons) = tokio::join!(
client.search_reports(&params),
state.report_reasons(&client)
);
let reports = reports.log_error("search reports");
let markup = templates::pages::reports_list::reports_list_page(
config,
@@ -124,14 +149,17 @@ async fn reports_list(
status: query.status.as_deref(),
report_type: query.report_type.as_deref(),
category: query.category.as_deref(),
reason: reason.as_deref(),
reporter_id: query.reporter_id.as_deref(),
reported_user_id: query.reported_user_id.as_deref(),
reported_webhook_id: query.reported_webhook_id.as_deref(),
reported_guild_id: query.reported_guild_id.as_deref(),
reported_channel_id: query.reported_channel_id.as_deref(),
guild_context_id: query.guild_context_id.as_deref(),
resolved_by_admin_id: query.resolved_by_admin_id.as_deref(),
sort: query.sort.as_deref().unwrap_or("reportedAt_desc"),
},
reasons.as_deref(),
page,
limit,
);
@@ -167,10 +195,12 @@ async fn report_detail(
.log_error("load report detail");
match report {
Some(report) => {
let live = load_live_profile(&client, &auth.0, &report).await;
let markup = templates::pages::report_detail::report_detail_page(
config,
&auth.0,
&report,
&live,
&csrf_token,
is_detail_fragment,
);
@@ -183,6 +213,49 @@ async fn report_detail(
}
}
async fn load_live_profile(
client: &AdminApiClient,
auth: &AuthContext,
report: &ReportEntry,
) -> templates::pages::report_detail::LiveProfile {
let can = |permission: &str| {
auth.admin_user
.as_ref()
.is_some_and(|admin| acl::has_permission(&admin.acls, permission))
};
let snapshot = report.reported_profile_snapshot.as_ref();
let user_id = snapshot
.and_then(|snapshot| snapshot.user.as_ref())
.map(|user| user.id.as_str())
.filter(|_| can(acl::USER_LOOKUP));
let guild_id = snapshot
.and_then(|snapshot| snapshot.guild.as_ref())
.map(|guild| guild.id.as_str())
.filter(|_| can(acl::GUILD_LOOKUP));
let (user, guild) = tokio::join!(
async {
match user_id {
Some(id) => client
.get_user_by_id(id)
.await
.log_error("load live reported user"),
None => None,
}
},
async {
match guild_id {
Some(id) => client
.lookup_guild(id)
.await
.log_error("load live reported guild")
.flatten(),
None => None,
}
}
);
templates::pages::report_detail::LiveProfile { user, guild }
}
async fn report_fragment(
State(state): State<AppState>,
auth: axum::Extension<AuthContext>,
@@ -261,6 +334,108 @@ async fn report_resolve(
}
}
async fn report_legal_hold(
State(state): State<AppState>,
auth: axum::Extension<AuthContext>,
Path(report_id): Path<String>,
request: Request,
) -> Response {
let config = state.config();
let base = &config.base_path;
let back = format!("{base}/reports/{report_id}");
let form: LegalHoldForm = match Form::from_request(request, &state).await {
Ok(Form(f)) => f,
Err(error) => {
tracing::warn!(%error, report_id, "failed to parse report legal hold form");
return flash::redirect_with_flash(
&back,
FlashData::error("Invalid form data"),
config.secure_cookies(),
);
}
};
let clearing = form.clear.is_some();
let until = if clearing {
None
} else {
match form.legal_hold_until.as_deref().and_then(legal_hold_date) {
Some(date) if date < time::OffsetDateTime::now_utc().date() => {
return flash::redirect_with_flash(
&back,
FlashData::error(LEGAL_HOLD_IN_PAST),
config.secure_cookies(),
);
}
Some(date) => Some(legal_hold_end_of_day(date)),
None => {
return flash::redirect_with_flash(
&back,
FlashData::error("Choose the date the hold ends"),
config.secure_cookies(),
);
}
}
};
let reason = clean_string(form.legal_hold_reason.as_deref().unwrap_or(""));
if until.is_some() && reason.is_none() {
return flash::redirect_with_flash(
&back,
FlashData::error(LEGAL_HOLD_NEEDS_REASON),
config.secure_cookies(),
);
}
let client = AdminApiClient::new(state.http_client(), config, &auth.0.session);
let result = client
.set_report_legal_hold(&report_id, until.as_deref(), reason.as_deref())
.await;
let flash = match result {
Ok(response) => match response.legal_hold_until {
Some(until) => FlashData::success(format!(
"Legal hold placed until {}",
format_admin_timestamp(&until)
)),
None => FlashData::success("Legal hold cleared"),
},
Err(error) => {
tracing::warn!(%error, report_id, "admin API request failed: set report legal hold");
match error {
ApiError::Http {
status: 400,
message,
} => FlashData::error(legal_hold_refusal(&message)),
_ => FlashData::error("Failed to update the legal hold"),
}
}
};
flash::redirect_with_flash(&back, flash, config.secure_cookies())
}
const LEGAL_HOLD_IN_PAST: &str = "The hold must end in the future";
const LEGAL_HOLD_NEEDS_REASON: &str = "Give a reason for the hold";
fn legal_hold_date(date: &str) -> Option<time::Date> {
let format = time::format_description::parse_borrowed::<2>("[year]-[month]-[day]").ok()?;
time::Date::parse(date.trim(), &format).ok()
}
fn legal_hold_end_of_day(date: time::Date) -> String {
format!("{date}T23:59:59.999Z")
}
fn legal_hold_refusal(body: &str) -> &'static str {
let body: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
let reason_refused = body["errors"]
.as_array()
.into_iter()
.flatten()
.any(|error| error["path"] == "legal_hold_reason");
if reason_refused {
LEGAL_HOLD_NEEDS_REASON
} else {
LEGAL_HOLD_IN_PAST
}
}
fn decode_sort(sort: Option<&str>) -> (&'static str, &'static str) {
match sort.unwrap_or("reportedAt_desc") {
"reportedAt_asc" => ("reportedAt", "asc"),
@@ -271,3 +446,51 @@ fn decode_sort(sort: Option<&str>) -> (&'static str, &'static str) {
_ => ("reportedAt", "desc"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legal_hold_dates_end_at_the_end_of_the_day_in_utc() {
assert_eq!(
legal_hold_date("2027-01-31")
.map(legal_hold_end_of_day)
.as_deref(),
Some("2027-01-31T23:59:59.999Z")
);
assert_eq!(
legal_hold_date(" 2027-02-01 ")
.map(legal_hold_end_of_day)
.as_deref(),
Some("2027-02-01T23:59:59.999Z")
);
for invalid in ["", "2027-02-30", "31/01/2027", "2027-1-31", "tomorrow"] {
assert_eq!(legal_hold_date(invalid), None, "{invalid}");
}
}
#[test]
fn a_refused_hold_names_the_field_the_api_refused() {
let refusal = |path: &str| {
serde_json::json!({
"code": "INVALID_FORM_BODY",
"message": "Input Validation Error",
"errors": [{"path": path, "message": "refused"}]
})
.to_string()
};
assert_eq!(
legal_hold_refusal(&refusal("legal_hold_until")),
"The hold must end in the future"
);
assert_eq!(
legal_hold_refusal(&refusal("legal_hold_reason")),
"Give a reason for the hold"
);
assert_eq!(
legal_hold_refusal("not json"),
"The hold must end in the future"
);
}
}