diff --git a/pkgs/id/src/local_events.rs b/pkgs/id/src/local_events.rs index ab4778cca8..9c901c2d80 100644 --- a/pkgs/id/src/local_events.rs +++ b/pkgs/id/src/local_events.rs @@ -24,7 +24,7 @@ use p2panda_core::{Hash, SigningKey}; use crate::chain::{ChainExt, Event, MAX_AFTER, sign}; use crate::chat::{CHAT_MESSAGE_KIND, ChatMessage, ChatRecord, SendRate}; use crate::documents::{DOCUMENT_KIND, DocumentRef, REMOVAL_KIND}; -use crate::event_store::{EventStore, Ingest}; +use crate::event_store::{Block, BlockKind, EventStore, Ingest}; use crate::local_claims::LocalClaims; use crate::notes::{ AppliedNote, CREATE_KIND as NOTE_CREATE_KIND, NoteFoldError, NoteOp, NoteRecord, @@ -276,6 +276,52 @@ impl LocalEvents { *self.key.verifying_key().as_bytes() } + /// Adds `block` to the operator block list (#2245), replacing any row + /// that names the same kind and value. The enforcement seams + /// ([`crate::abuse`], [`crate::blob_gate`], [`crate::pull_policy`]) + /// read the list live, so a block lands on the next check. + /// + /// # Errors + /// + /// Fails if the block row cannot be written. + pub fn add_block(&self, block: &Block) -> Result<()> { + self.store + .add_block(block) + .context("add the operator block row") + } + + /// Removes the operator block naming (`kind`, `value`), returning + /// whether a row was removed (#2245). + /// + /// # Errors + /// + /// Fails if the block row cannot be removed. + pub fn remove_block(&self, kind: BlockKind, value: &[u8]) -> Result { + self.store + .remove_block(kind, value) + .context("remove the operator block row") + } + + /// Every operator block row, expired ones included, in (kind, value) + /// order (#2245). + /// + /// # Errors + /// + /// Fails if the block rows cannot be read. + pub fn blocks(&self) -> Result> { + self.store.blocks().context("read the operator block rows") + } + + /// Whether (`kind`, `value`) is blocked right now, judged against the + /// wall clock exactly as the enforcement seams judge it (#2245). + /// Reads go through [`crate::event_store::BlockList`], the same trait + /// [`crate::abuse`], [`crate::blob_gate`] and [`crate::pull_policy`] + /// consult, so a web-written row and an enforced row are one row. + #[must_use] + pub fn is_blocked(&self, kind: BlockKind, value: &[u8]) -> bool { + crate::event_store::BlockList::is_blocked(&self.store, kind, value) + } + /// Publishes `content` as a document of `media_type`, with a tag for each of `tags`. The event /// names the content by its BLAKE3 hash and size. The bytes are not kept here: they are a blob. /// Every tag is checked before anything is recorded, so a bad tag records nothing. diff --git a/pkgs/id/src/web/app_interface.rs b/pkgs/id/src/web/app_interface.rs index 58668a7ada..3adf519249 100644 --- a/pkgs/id/src/web/app_interface.rs +++ b/pkgs/id/src/web/app_interface.rs @@ -119,6 +119,7 @@ pub(crate) const HOST_RESERVED_ROUTES: &[&str] = &[ "/files", "/settings", "/peers", + "/blocks", "/groups", "/edit/{*name}", "/hash/{hash}", @@ -127,6 +128,8 @@ pub(crate) const HOST_RESERVED_ROUTES: &[&str] = &[ "/api/files", "/api/home/feed", "/api/peers", + "/api/blocks", + "/api/blocks/remove", "/api/save", "/api/new", "/api/rename", diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 1c49fa6fe7..1735018588 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -5,7 +5,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use axum::{ - Json, Router, + Form, Json, Router, body::Body, extract::{DefaultBodyLimit, Multipart, Path, Query, State}, http::{HeaderMap, StatusCode, header}, @@ -19,12 +19,14 @@ use super::content_mode::{ContentMode, detect_mode, detect_mode_with_content, ge use super::markdown::prosemirror_to_markdown; use super::security::{self, WebSecurity}; use super::templates::{ - render_binary_viewer, render_editor, render_editor_page, render_file_list, - render_file_list_content, render_main_page_wrapper, render_media_viewer, render_page, - render_peers, render_peers_content, render_settings, + AssetUrls, hex_encode, render_binary_viewer, render_blocks, render_editor, render_editor_page, + render_file_list, render_file_list_content, render_main_page_wrapper, render_media_viewer, + render_page, render_peers, render_peers_content, render_settings, }; +use crate::event_store::{Block, BlockKind}; use crate::fileops::{FileOpError, FileOps, claim_archive_name, snapshot_provenance_tags}; use crate::tags::TagStore; +use iroh_base::EndpointId; mod file_handlers; use file_handlers::*; @@ -570,6 +572,7 @@ fn create_router_inner(state: AppState) -> Router { .route(&world_route, get(world_page_handler)) .route("/settings", get(settings_handler)) .route("/peers", get(peers_handler)) + .route("/blocks", get(blocks_page_handler)) .route("/groups", get(super::groups::groups_page_handler)) .route("/edit/{*name}", get(file_by_name_handler)) .route("/hash/{hash}", get(hash_redirect_handler)) @@ -580,6 +583,8 @@ fn create_router_inner(state: AppState) -> Router { .route("/api/files", get(files_list_handler)) .route("/api/home/feed", get(super::home::feed_handler)) .route("/api/peers", get(peers_partial_handler)) + .route("/api/blocks", get(blocks_partial_handler).post(block_create_handler)) + .route("/api/blocks/remove", post(block_remove_handler)) // File management API routes .route("/api/save", post(save_handler)) .route("/api/new", post(new_file_handler)) @@ -746,7 +751,7 @@ async fn peers_handler(State(state): State, headers: HeaderMap) -> imp Vec::new() }; - let content = render_peers(&peers_data); + let content = render_peers(&peers_data, &blocked_peer_ids(&state).await); if is_partial_request(&headers) { Html(render_main_page_wrapper(&content)) } else { @@ -1088,7 +1093,236 @@ async fn peers_partial_handler(State(state): State) -> impl IntoRespon // Return only the inner content: fetchPartial assigns this as // innerHTML of #peers-content, so the wrapper must not be included // (issue #6956). - Html(render_peers_content(&peers_data)) + Html(render_peers_content( + &peers_data, + &blocked_peer_ids(&state).await, + )) +} + +/// Node-ID strings (peers-page form) that already name a peer-key row on +/// the operator block list (#2245). A store read failure yields an empty +/// set: the page still renders, just without blocked badges. +async fn blocked_peer_ids(state: &AppState) -> std::collections::HashSet { + match state.local_events.lock().await.blocks() { + Ok(rows) => rows + .iter() + .filter(|block| block.kind == BlockKind::PeerKey) + .map(|block| hex_encode(&block.value)) + .collect(), + Err(err) => { + tracing::warn!("[routes] Could not read the block list: {err:#}"); + std::collections::HashSet::new() + } + } +} + +/// Which block rows a list/unblock form addresses (#2245). +fn parse_block_kind(raw: Option<&str>) -> Result { + match raw.unwrap_or("peer_key") { + "peer_key" => Ok(BlockKind::PeerKey), + "ip" => Ok(BlockKind::Ip), + "topic_tag" => Ok(BlockKind::TopicTag), + other => Err(format!( + "unknown block kind {other:?}; want peer_key, ip, or topic_tag" + )), + } +} + +/// Raw row value for `kind` from the operator's text: a peer key parses +/// as an endpoint ID (its 32 key bytes are the row, matching +/// [`BlockList::peer_blocked`](crate::event_store::BlockList::peer_blocked)), +/// an IP parses and stores in text form (the form +/// [`BlockList::ip_blocked`](crate::event_store::BlockList::ip_blocked) +/// checks), a topic tag stores verbatim. +fn parse_block_value(kind: BlockKind, raw: &str) -> Result, String> { + let raw = raw.trim(); + if raw.is_empty() { + return Err("block value must not be empty".to_owned()); + } + match kind { + BlockKind::PeerKey => raw + .parse::() + .map(|id| id.as_bytes().to_vec()) + .map_err(|_| "peer key must be an endpoint ID (64 hex characters)".to_owned()), + BlockKind::Ip => raw + .parse::() + .map(|ip| ip.to_string().into_bytes()) + .map_err(|_| "IP must parse as an IP address".to_owned()), + BlockKind::TopicTag => Ok(raw.as_bytes().to_vec()), + } +} + +/// Only a local path on this host is a valid post-action destination; +/// anything else falls back to the Blocks page (no open redirects). +fn sanitize_return_to(raw: Option<&str>) -> String { + match raw { + Some(path) if path.starts_with('/') && !path.starts_with("//") => path.to_owned(), + _ => "/blocks".to_owned(), + } +} + +/// One operator block form, from a peer row or the Blocks page (#2245). +#[derive(Debug, Deserialize)] +struct BlockForm { + /// Peer endpoint ID, IP text, or topic tag (per `kind`). + value: String, + /// `peer_key` (default), `ip`, or `topic_tag`. + kind: Option, + /// Operator's reason; stored on the row. + reason: Option, + /// Optional expiry as unix milliseconds. + expires_at_ms: Option, + /// Where to land after the write. + return_to: Option, +} + +/// Refusal page for a bad block form: the reason plus a way back. The +/// message carries operator input, so it renders escaped. +fn bad_block_request(message: &str, return_to: &str, assets: &AssetUrls) -> Response { + let content = format!( + "

Blocks

Could not write the block: {}

Back

", + super::templates::html_escape(message), + super::templates::html_escape(return_to), + ); + ( + StatusCode::BAD_REQUEST, + Html(render_page("Blocks", &content, "", assets)), + ) + .into_response() +} + +/// Handler to write one operator block row (`POST /api/blocks`, #2245). +async fn block_create_handler( + State(state): State, + Form(form): Form, +) -> Response { + let return_to = sanitize_return_to(form.return_to.as_deref()); + let kind = match parse_block_kind(form.kind.as_deref()) { + Ok(kind) => kind, + Err(message) => return bad_block_request(&message, &return_to, &state.assets), + }; + let value = match parse_block_value(kind, &form.value) { + Ok(value) => value, + Err(message) => return bad_block_request(&message, &return_to, &state.assets), + }; + let expires_at_ms = match form.expires_at_ms.as_deref().map(str::trim) { + None | Some("") => None, + Some(raw) => match raw.parse::() { + Ok(ts) => Some(ts), + Err(_) => { + return bad_block_request( + "expiry must be unix milliseconds, or left blank for a permanent block", + &return_to, + &state.assets, + ); + } + }, + }; + let block = Block { + kind, + value, + added_at_ms: crate::time::unix_ms(), + reason: form.reason.as_deref().unwrap_or("").trim().to_owned(), + expires_at_ms, + }; + match state.local_events.lock().await.add_block(&block) { + Ok(()) => { + tracing::info!("[routes] Operator block written: {kind:?}"); + Redirect::to(&return_to).into_response() + } + Err(err) => { + tracing::error!("[routes] Could not write the operator block: {err:#}"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Html(format!( + "

Blocks

Could not write the block: {}

", + super::templates::html_escape(&format!("{err:#}")), + )), + ) + .into_response() + } + } +} + +/// Form that names the row an unblock removes (`POST /api/blocks/remove`). +#[derive(Debug, Deserialize)] +struct UnblockForm { + /// The blocked value exactly as the Blocks page rendered it. + value: String, + /// `peer_key` (default), `ip`, or `topic_tag`. + kind: Option, + /// Where to land after the removal. + return_to: Option, +} + +/// Handler to remove one operator block row (`POST /api/blocks/remove`, +/// #2245). Removing a row that is not there still lands back on the page. +async fn block_remove_handler( + State(state): State, + Form(form): Form, +) -> Response { + let return_to = sanitize_return_to(form.return_to.as_deref()); + let kind = match parse_block_kind(form.kind.as_deref()) { + Ok(kind) => kind, + Err(message) => return bad_block_request(&message, &return_to, &state.assets), + }; + let value = match parse_block_value(kind, &form.value) { + Ok(value) => value, + Err(message) => return bad_block_request(&message, &return_to, &state.assets), + }; + match state.local_events.lock().await.remove_block(kind, &value) { + Ok(removed) => { + tracing::info!("[routes] Operator block removed: {kind:?} (row present: {removed})"); + Redirect::to(&return_to).into_response() + } + Err(err) => { + tracing::error!("[routes] Could not remove the operator block: {err:#}"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Html(format!( + "

Blocks

Could not remove the block: {}

", + super::templates::html_escape(&format!("{err:#}")), + )), + ) + .into_response() + } + } +} + +/// Blocks page handler - every operator block row with unblock actions. +async fn blocks_page_handler(State(state): State, headers: HeaderMap) -> Response { + let blocks = match state.local_events.lock().await.blocks() { + Ok(blocks) => blocks, + Err(err) => { + let content = format!( + "

Blocks

Could not read the block list: {}

", + super::templates::html_escape(&format!("{err:#}")), + ); + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Html(render_page("Blocks", &content, "", &state.assets)), + ) + .into_response(); + } + }; + let content = render_blocks(&blocks); + if is_partial_request(&headers) { + Html(render_main_page_wrapper(&content)).into_response() + } else { + Html(render_page("Blocks", &content, "", &state.assets)).into_response() + } +} + +/// API handler for the blocks partial (the Blocks page fragment). +async fn blocks_partial_handler(State(state): State) -> Response { + match state.local_events.lock().await.blocks() { + Ok(blocks) => Html(render_blocks(&blocks)).into_response(), + Err(err) => ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Could not read the block list: {err:#}"), + ) + .into_response(), + } } /// Static assets handler. diff --git a/pkgs/id/src/web/templates.rs b/pkgs/id/src/web/templates.rs index a4aaee1699..2b2e994e78 100644 --- a/pkgs/id/src/web/templates.rs +++ b/pkgs/id/src/web/templates.rs @@ -11,6 +11,7 @@ use std::fmt::Write; use super::content_mode::MediaType; use super::routes::{FileKind, FileListPage}; +use crate::event_store::{Block, BlockKind}; /// Asset URLs for templates. /// @@ -91,6 +92,7 @@ pub fn render_main_page_wrapper(content: &str) -> String { html.push_str("