//! Write handlers, footnotes and endorsements. use axum::{ Form, extract::Path, http::StatusCode, response::{IntoResponse, Redirect, Response}, }; use uuid::Uuid; use crate::AppState; use crate::auth::RequireUser; use super::super::{ CommunityScope, FootnoteForm, WriteScope, check_community_access, check_user_post_rate, check_write_state, db_error, validate_body, }; use super::posts::{MAX_FOOTNOTES_PER_POST, resolve_and_render_mentions}; use mt_db::queries::PostForEdit; /// Why a footnote add was rejected. Pure predicate result; the handler /// translates each variant to an HTTP response. #[derive(Debug, PartialEq, Eq)] pub(super) enum FootnoteDenial { NotAuthor, PostRemoved, TooManyFootnotes, } /// Check whether `user_id` may add a footnote to a post. Pure, no I/O. pub(super) fn check_footnote_permission( user_id: Uuid, post_author_id: Uuid, post_removed: bool, existing_footnote_count: i64, ) -> Result<(), FootnoteDenial> { if user_id != post_author_id { return Err(FootnoteDenial::NotAuthor); } if post_removed { return Err(FootnoteDenial::PostRemoved); } if existing_footnote_count >= MAX_FOOTNOTES_PER_POST as i64 { return Err(FootnoteDenial::TooManyFootnotes); } Ok(()) } /// Why an endorsement toggle was rejected. #[derive(Debug, PartialEq, Eq)] pub(super) enum EndorsementDenial { CannotEndorseOwn, PostRemoved, UserSuspended, } /// Check whether `user_id` may toggle an endorsement on a post. Pure, no I/O. pub(super) fn check_endorsement_permission( user_id: Uuid, post_author_id: Uuid, post_removed: bool, user_suspended: bool, ) -> Result<(), EndorsementDenial> { if user_id == post_author_id { return Err(EndorsementDenial::CannotEndorseOwn); } if post_removed { return Err(EndorsementDenial::PostRemoved); } if user_suspended { return Err(EndorsementDenial::UserSuspended); } Ok(()) } // Footnote handler #[tracing::instrument(skip_all)] pub(in crate::routes) async fn add_footnote_handler( axum::extract::State(state): axum::extract::State, Path((slug, category_slug, thread_id_str, post_id_str)): Path<(String, String, String, String)>, RequireUser(user): RequireUser, Form(form): Form, ) -> Result { let scope = CommunityScope::::resolve(&state.db, &slug, &post_id_str).await?; let post_id = scope.resource.id; let removed = mt_db::queries::is_post_removed(&state.db, post_id) .await .map_err(db_error)?; let footnote_count = mt_db::queries::count_footnotes_for_post(&state.db, post_id) .await .map_err(db_error)?; check_footnote_permission( user.user_id, scope.resource.author_id, removed, footnote_count, ) .map_err(|denial| match denial { FootnoteDenial::NotAuthor | FootnoteDenial::PostRemoved => { StatusCode::FORBIDDEN.into_response() } FootnoteDenial::TooManyFootnotes => ( StatusCode::UNPROCESSABLE_ENTITY, "Maximum footnotes reached for this post.", ) .into_response(), })?; // Write access (suspension + ban + mute) against the scope-verified community; // CommunityScope already proved the post belongs to this slug's community, so // the old hand-copied `post_data.community_id != community.id` guard is gone. scope.require_write_access(&state.db, user.user_id).await?; let community = scope.community; check_write_state(&state, &community, &user, WriteScope::ContinueExisting).await?; mt_db::mutations::ensure_membership(&state.db, user.user_id, community.id) .await .map_err(db_error)?; check_user_post_rate(&state.db, user.user_id).await?; let body = validate_body(&form.body, 65536, "Footnote")?; let author_plus = user.perks.effective_plus(); if !author_plus { crate::routes::reject_embeds_for_free_user(body)?; } let (body_html, _mention_ids) = resolve_and_render_mentions( &state.db, body, community.id, &slug, user.user_id, author_plus, ) .await?; mt_db::mutations::insert_footnote(&state.db, post_id, user.user_id, body, &body_html) .await .map_err(db_error)?; Ok(Redirect::to(&format!( "/p/{slug}/{category_slug}/{thread_id_str}?toast=Footnote+added" ))) } // Endorsement handler #[tracing::instrument(skip_all)] pub(in crate::routes) async fn toggle_endorsement_handler( axum::extract::State(state): axum::extract::State, Path((slug, category_slug, thread_id_str, post_id_str)): Path<(String, String, String, String)>, RequireUser(user): RequireUser, ) -> Result { let scope = CommunityScope::::resolve(&state.db, &slug, &post_id_str).await?; let post_id = scope.resource.id; let removed = mt_db::queries::is_post_removed(&state.db, post_id) .await .map_err(db_error)?; // Community access (suspension + ban) against the scope-verified community, // no mute check since endorsing is not content. CommunityScope already proved // the post belongs to this slug's community. let community = scope.community; check_community_access(&state.db, &community, Some(user.user_id)).await?; // Endorsement is a write action, so it's blocked by Frozen/Archived state. check_write_state(&state, &community, &user, WriteScope::ContinueExisting).await?; let suspended = mt_db::queries::is_user_suspended(&state.db, user.user_id) .await .map_err(db_error)?; check_endorsement_permission(user.user_id, scope.resource.author_id, removed, suspended) .map_err(|denial| match denial { EndorsementDenial::CannotEndorseOwn | EndorsementDenial::PostRemoved => { StatusCode::FORBIDDEN.into_response() } EndorsementDenial::UserSuspended => { (StatusCode::FORBIDDEN, "Your account has been suspended.").into_response() } })?; mt_db::mutations::toggle_endorsement(&state.db, post_id, user.user_id) .await .map_err(db_error)?; Ok(Redirect::to(&format!( "/p/{slug}/{category_slug}/{thread_id_str}#post-{post_id_str}" ))) } #[cfg(test)] mod permission_tests { use super::*; fn uid(b: u8) -> Uuid { Uuid::from_bytes([b; 16]) } #[test] fn footnote_author_can_add_when_not_removed_and_under_cap() { let me = uid(1); let result = check_footnote_permission(me, me, false, 0); assert!(result.is_ok()); } #[test] fn footnote_non_author_is_rejected() { // Pins `user_id != post_author_id` vs `==`. let me = uid(1); let other = uid(2); assert_eq!( check_footnote_permission(me, other, false, 0), Err(FootnoteDenial::NotAuthor) ); } #[test] fn footnote_on_removed_post_is_rejected_even_for_author() { let me = uid(1); assert_eq!( check_footnote_permission(me, me, true, 0), Err(FootnoteDenial::PostRemoved) ); } #[test] fn footnote_at_cap_is_rejected() { // Pins `count >= MAX` vs `>`. At exactly MAX, must reject. let me = uid(1); let cap = MAX_FOOTNOTES_PER_POST as i64; assert_eq!( check_footnote_permission(me, me, false, cap), Err(FootnoteDenial::TooManyFootnotes) ); } #[test] fn footnote_one_below_cap_is_allowed() { let me = uid(1); let just_below = MAX_FOOTNOTES_PER_POST as i64 - 1; assert!(check_footnote_permission(me, me, false, just_below).is_ok()); } #[test] fn footnote_above_cap_is_rejected() { let me = uid(1); let over = MAX_FOOTNOTES_PER_POST as i64 + 1; assert_eq!( check_footnote_permission(me, me, false, over), Err(FootnoteDenial::TooManyFootnotes) ); } #[test] fn footnote_check_order_author_then_removal_then_cap() { // The author check fires first, even on a removed post over the cap, // a non-author gets NotAuthor (not PostRemoved or TooMany). let me = uid(1); let other = uid(2); let cap = MAX_FOOTNOTES_PER_POST as i64; assert_eq!( check_footnote_permission(me, other, true, cap), Err(FootnoteDenial::NotAuthor) ); // Removal check fires second. assert_eq!( check_footnote_permission(me, me, true, cap), Err(FootnoteDenial::PostRemoved) ); } #[test] fn endorsement_other_user_on_live_post_is_allowed() { let me = uid(1); let author = uid(2); assert!(check_endorsement_permission(me, author, false, false).is_ok()); } #[test] fn endorsement_self_is_rejected() { // Pins `user_id == post_author_id` vs `!=`. let me = uid(1); assert_eq!( check_endorsement_permission(me, me, false, false), Err(EndorsementDenial::CannotEndorseOwn) ); } #[test] fn endorsement_on_removed_post_is_rejected() { let me = uid(1); let author = uid(2); assert_eq!( check_endorsement_permission(me, author, true, false), Err(EndorsementDenial::PostRemoved) ); } #[test] fn endorsement_by_suspended_user_is_rejected() { let me = uid(1); let author = uid(2); assert_eq!( check_endorsement_permission(me, author, false, true), Err(EndorsementDenial::UserSuspended) ); } #[test] fn endorsement_check_order_self_then_removal_then_suspension() { // Self-check fires first: even if removed AND suspended, self attempt // returns CannotEndorseOwn. let me = uid(1); assert_eq!( check_endorsement_permission(me, me, true, true), Err(EndorsementDenial::CannotEndorseOwn) ); // With author check passing, removal fires before suspension. let author = uid(2); assert_eq!( check_endorsement_permission(me, author, true, true), Err(EndorsementDenial::PostRemoved) ); } }