diff --git a/.changeset/mcp-write-tools.md b/.changeset/mcp-write-tools.md new file mode 100644 index 000000000..b219202ed --- /dev/null +++ b/.changeset/mcp-write-tools.md @@ -0,0 +1,22 @@ +--- +--- + +feat(mcp): add the delete_event and reports_action tools + +`delete_event` marks one stored event deleted through the store's own soft delete: the event +leaves REQ and COUNT, keeps its row, and the payload says so — `get_event` and `list_events` still +return it with `deleted_at` set unless an actionable report hides it, and the four outcomes are +`deleted`, `already_deleted`, `not_deleteable` (kind 62 is never deleted) and `not_found`. `reports_action` acts on a report's +own kind-1984 event id, flipping `Report.actionable` for `hide` and `allow` on every row that +event wrote. + +The report store now reaches the MCP door as a `reports` field on `ServiceStores`, and +`ReportRepository` gains one setter: the LMDB arm moves the three denormalised +`reports_actionable_*` entries with the flag, so the NIP-56 gate and the actionable reads follow a +flip at once, and the Postgres arm is one `UPDATE` with no migration. The hidden-content mirror +needs no work: reads are gated per query and the mirror refreshes wholesale every 30 s. +`reports_list` remains out of scope and unowned. + +Rust only; no published package changes. The decisions are in +`docs/rewrite/decisions/0017-report-and-event-writes.md`, and ADR 0014's audit table gains the two +`mcp.*` names. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 764cd8dbd..4849fcf66 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -75,7 +75,8 @@ The following environment variables can be set: ## The admin MCP mode (`--mcp-stdio`) `nostreamd --mcp-stdio` serves the admin MCP server (`settings_get`, `settings_set`, -`list_events`, `get_event`) on stdin/stdout and exits when stdin closes. It binds no socket, +`list_events`, `get_event`, `delete_event`, `reports_action`) on stdin/stdout and exits when stdin +closes. It binds no socket, opens no store of its own, and writes its log lines to **stderr** so nothing but JSON-RPC crosses stdout. @@ -96,7 +97,7 @@ The document is JSON, and `scopes` is optional: | Document | What it may call | |---|---| | `{}` or `{ "scopes": [] }` | The read tools: `settings_get`, `list_events`, `get_event`. | -| `{ "scopes": ["write"] }` | The read tools and `settings_set`. | +| `{ "scopes": ["write"] }` | The read tools, and the three that change something: `settings_set`, `delete_event` (soft-deletes **any author's** stored event by id — there is no per-author restriction, the holder of the token is the operator) and `reports_action` (sets the relay-wide NIP-56 filter for the target an actionable report names). | `write` is the only accepted scope, and an unknown name — a typo, or a document from another tool — refuses to start rather than being narrowed silently. A call the document's scopes deny is diff --git a/crates/nostream-admin/tests/common/mod.rs b/crates/nostream-admin/tests/common/mod.rs index 3a54771d5..0eee96d9e 100644 --- a/crates/nostream-admin/tests/common/mod.rs +++ b/crates/nostream-admin/tests/common/mod.rs @@ -182,6 +182,8 @@ impl TestServer { Arc::clone(&backend) as Arc }), + reports: Arc::clone(&backend) + as Arc, }); let client = Arc::new(ReqwestClient::new().unwrap()); @@ -531,6 +533,13 @@ impl EventRepository for SlowEventRepository { Box::pin(async { Err(not_implemented()) }) } + fn find_stored<'a>( + &'a self, + _id: &'a nostream_core::EventId, + ) -> nostream_storage::repositories::StorageFuture<'a, Option> { + Box::pin(async { Err(not_implemented()) }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, _pubkey: &'a nostream_core::Pubkey, diff --git a/crates/nostream-mcp/src/lib.rs b/crates/nostream-mcp/src/lib.rs index 2f747cbd1..91255c72e 100644 --- a/crates/nostream-mcp/src/lib.rs +++ b/crates/nostream-mcp/src/lib.rs @@ -1,4 +1,4 @@ -//! `nostream-mcp` owns the admin MCP server: the tool router, the five tools, the credential +//! `nostream-mcp` owns the admin MCP server: the tool router, the seven tools, the credential //! and its scopes, and the audit sink. //! //! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on @@ -24,8 +24,8 @@ //! `nostream-admin` (used here, not re-implemented); //! - the settings merge, validation, redaction and the guided catalogue — `nostream-config`; //! - the event store and the repositories — `nostream-storage`; -//! - every tool family outside this surface: `delete_event`, `user_admin`, `invoices_*`, -//! `reports_*` and `maintenance_*` are later slices of #1183. +//! - every tool family outside this surface: `user_admin`, `invoices_*` and `maintenance_*` are +//! later slices of #1183. mod credential; mod error; @@ -36,8 +36,10 @@ pub use credential::{ }; pub use error::McpError; pub use server::{ - AUDIT_DENIED, AdminMcp, FORBIDDEN, GetEventArgs, ListEventsArgs, MAX_FILTER_TERMS, - MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, Requires, SettingsSetArgs, - TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + AUDIT_DENIED, AdminMcp, DeleteEventArgs, FORBIDDEN, GetEventArgs, ListEventsArgs, + MAX_FILTER_TERMS, MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, + OUTCOME_ALREADY_DELETED, OUTCOME_DELETED, OUTCOME_NOT_DELETEABLE, OUTCOME_NOT_FOUND, + ReportAction, ReportsActionArgs, Requires, SettingsSetArgs, TOOL_DELETE_EVENT, TOOL_GET_EVENT, + TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, Tool, UNAUTHORIZED, arguments_parse, audit_action, required_scope, }; diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 8fe6764cf..8c91e65cf 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -1,4 +1,4 @@ -//! The MCP server: the five tools, the credential gate and the audit sink. +//! The MCP server: the seven tools, the credential gate and the audit sink. //! //! Every tool is a thin handler over a seam that already exists — `AdminState` for the settings, //! `EventRepository` for the events — and nothing here knows what an HTTP status is (R3). The @@ -15,7 +15,7 @@ use nostream_admin::AdminState; use nostream_admin::controllers::admin_json_body_middleware::settings_patch; use nostream_admin::controllers::patch_settings::{self, SettingsWrite}; use nostream_admin::utils::status; -use nostream_core::{Filter, Kind}; +use nostream_core::{EventId, Filter, Kind}; use nostream_relay::nip11; use nostream_storage::repositories::{EventRecord, collect_page, collect_records}; use rmcp::handler::server::router::tool::ToolRouter; @@ -47,7 +47,8 @@ pub const MCP_INSTRUCTIONS: &str = "\ The nostream admin MCP server. Every call is decided by the scoped token document the mode was \ started with — `--admin-token-file ` or `--admin-token-fd `, exactly one, its shape \ {\"scopes\": [\"write\"]}: the document's presence authorises `settings_get`, `list_events`, \ -`get_event` and `relay_status`, and the \"write\" scope authorises `settings_set` (else the call \ +`get_event` and `relay_status`, and the \"write\" scope authorises `settings_set`, \ +`delete_event` and `reports_action` (else the call \ is `Forbidden`). \ `admin.enabled` must be true in the settings, or every call answers `Not Found`; a document \ that cannot be read answers `Unauthorized`. Each executed call appends one `mcp.` line to \ @@ -60,6 +61,21 @@ pub const TOOL_SETTINGS_SET: &str = "settings_set"; pub const TOOL_LIST_EVENTS: &str = "list_events"; pub const TOOL_GET_EVENT: &str = "get_event"; pub const TOOL_RELAY_STATUS: &str = "relay_status"; +pub const TOOL_DELETE_EVENT: &str = "delete_event"; +pub const TOOL_REPORTS_ACTION: &str = "reports_action"; + +/// What a delete call did, as the payload's `outcome` (R3, R4): this call marked the row +/// deleted. +pub const OUTCOME_DELETED: &str = "deleted"; + +/// The row already carried `deleted_at`, so the store skipped it and this call changed nothing. +pub const OUTCOME_ALREADY_DELETED: &str = "already_deleted"; + +/// The store skipped a live row for the only other reason it has: kind 62 is never deleted. +pub const OUTCOME_NOT_DELETEABLE: &str = "not_deleteable"; + +/// No row carries the id this call named. +pub const OUTCOME_NOT_FOUND: &str = "not_found"; /// The most `ids` or `authors` criteria one call may carry. /// @@ -188,6 +204,16 @@ pub const TOOLS: &[Tool] = &[ parses: accepts_any_arguments, needs: Requires::Read, }, + Tool { + name: TOOL_DELETE_EVENT, + parses: delete_event_parses, + needs: Requires::Write, + }, + Tool { + name: TOOL_REPORTS_ACTION, + parses: reports_action_parses, + needs: Requires::Write, + }, ]; /// `tool`'s row; `None` when the table does not name it. @@ -232,6 +258,14 @@ fn get_event_parses(arguments: Option<&Map>) -> bool { serde_json::from_value::(arguments_value(arguments)).is_ok() } +fn delete_event_parses(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + +fn reports_action_parses(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + fn arguments_value(arguments: Option<&Map>) -> Value { Value::Object(arguments.cloned().unwrap_or_default()) } @@ -271,6 +305,52 @@ pub struct GetEventArgs { pub id: String, } +/// The delete tool's arguments: one id and nothing else (R2). +#[derive(Debug, Clone, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct DeleteEventArgs { + /// The event's hex id, in either case; a prefix shorter than 64 characters is refused and deletes nothing + pub id: String, +} + +/// The report action's arguments: one report event's id and the decision to give it (R12). +#[derive(Debug, Clone, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReportsActionArgs { + /// The report's own kind-1984 event id, exactly 64 hex characters in either case; not the reported event's id + pub id: String, + /// `hide` marks the report's targets hidden; `allow` clears them + pub action: ReportAction, +} + +/// The two decisions a report can be given. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ReportAction { + /// `hide`: the report's targets are hidden (`actionable: true`). + Hide, + /// `allow`: the report's targets are not hidden (`actionable: false`). + Allow, +} + +impl JsonSchema for ReportAction { + fn schema_name() -> Cow<'static, str> { + "ReportAction".into() + } + + /// The closed set as the schema's `enum`, which is what a validating client reads and what + /// the field's own description calls it. The derive would state a described unit enum as a + /// `oneOf` of `const` variants instead, because each variant's doc comment has nowhere to go + /// in a plain `enum` list; the set is the same either way. + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ "type": "string", "enum": ["hide", "allow"] }) + } + + fn inline_schema() -> bool { + true + } +} + /// The `settings_set` arguments: the same JSON object the console's HTTP body carries (R12). /// /// Kept as a raw map rather than a typed struct because the schema's rule is that an explicit @@ -443,6 +523,110 @@ impl AdminMcp { } } + /// The store's own soft delete, on one row: the exact-id read names the pubkey the seam + /// needs, one call flips the row, and the read-back carries the `deleted_at` the store + /// stamped (R1, R3). + #[tool( + description = "Mark one stored event deleted: the same soft delete a NIP-09 request from the \ +author makes. The event leaves REQ and COUNT and keeps its row, so `get_event` and `list_events` \ +still return it with `deleted_at` set — unless an actionable report hides it, in which case it \ +stays hidden until the report is allowed. The argument is the event's hex id; a prefix shorter \ +than 64 characters is refused rather than widened to whatever the store's range would match. Answers `outcome` — `deleted`, \ +`already_deleted`, `not_deleteable` (kind 62 is never deleted), or `not_found` — and the row as \ +it stands after the call" + )] + async fn delete_event( + &self, + Parameters(arguments): Parameters, + ) -> CallToolResult { + match self.deleted(&arguments.id).await { + Ok(payload) => tool_ok(payload), + Err(error) => tool_error(&error), + } + } + + /// One report event's triage decision: its own id, resolved through the report store, and + /// every row it wrote flipped to `actionable` or off it (R7, R13). + #[tool( + description = "Act on one report event: `hide` marks its targets hidden (`actionable: true`, \ +so REQ and COUNT withhold them while `nip56.hideActionableReports` is on) and `allow` clears them \ +(`actionable: false`). The argument is the report's own kind-1984 event id — exactly 64 hex \ +characters, not the reported event's id — and every report row that event wrote is flipped. \ +Answers `reports` (the rows as they stand, by `id`) and `changed` (how many this call flipped). \ +Every new REQ reflects the change at once; already-connected subscriptions see it at the relay's \ +next refresh, up to 30 s" + )] + async fn reports_action( + &self, + Parameters(arguments): Parameters, + ) -> CallToolResult { + match self.act_on_report(&arguments).await { + Ok(payload) => tool_ok(payload), + Err(error) => tool_error(&error), + } + } + + /// The delete payload: one outcome from the store's own count and the row **as it stands + /// after** the call, and that row (R3, R4). + /// + /// The read is [`EventRepository::find_stored`], not `get_event`'s gated read: a delete must + /// reach the events a moderator has just hidden, or this slice's two tools contradict each + /// other. The outcome comes from the post-call row rather than the pre-read, because a + /// pre-read is stale the moment a second caller deletes the row first — that row answers + /// `already_deleted`, and only a live one answers `not_deleteable`. + async fn deleted(&self, id: &str) -> Result { + let id = hex_prefix("id", id)?; + if id.len() != 64 { + return Err(McpError::Criterion(format!( + "id: {id:?} is not a 64-character hex id" + ))); + } + let event_id = EventId::try_from(id.as_str()) + .map_err(|error| McpError::Criterion(error.to_string()))?; + let events = &self.state.stores().events; + let Some(row) = events.find_stored(&event_id).await? else { + return Ok(json!({ "outcome": OUTCOME_NOT_FOUND, "event": null })); + }; + let count = events + .delete_by_pubkey_and_ids(&row.event.pubkey, &[row.event.id]) + .await?; + let after = events.find_stored(&event_id).await?; + let outcome = if count > 0 { + OUTCOME_DELETED + } else if after.as_ref().is_some_and(|row| row.deleted_at.is_some()) { + OUTCOME_ALREADY_DELETED + } else { + OUTCOME_NOT_DELETEABLE + }; + Ok(json!({ "outcome": outcome, "event": after })) + } + + /// The report payload: the rows one report event wrote, sorted by `id` because neither + /// backend orders that read, and how many this call flipped (R13). + /// + /// An id with no rows is a result rather than an error — the answer `get_event` gives an + /// unknown id — so a caller that mistyped one sees an empty list and not `Not Found`. + async fn act_on_report(&self, arguments: &ReportsActionArgs) -> Result { + let id = hex_prefix("id", &arguments.id)?; + if id.len() != 64 { + return Err(McpError::Criterion(format!( + "id: {id:?} is not a 64-character hex id" + ))); + } + let event_id = EventId::try_from(id.as_str()) + .map_err(|error| McpError::Criterion(error.to_string()))?; + let reports = &self.state.stores().reports; + if reports.find_by_event_id(&event_id).await?.is_empty() { + return Ok(json!({ "reports": [], "changed": 0 })); + } + let changed = reports + .set_actionable(&event_id, !matches!(arguments.action, ReportAction::Allow)) + .await?; + let mut rows = reports.find_by_event_id(&event_id).await?; + rows.sort_by_key(|report| report.id); + Ok(json!({ "reports": rows, "changed": changed })) + } + fn settings_document(&self) -> Result { let (merged, defaults) = self.state.merged_document()?; let filtered = nostream_config::store::filter_against_defaults(&merged, &defaults); diff --git a/crates/nostream-mcp/tests/audit.rs b/crates/nostream-mcp/tests/audit.rs index 1cb3f3aa2..521207686 100644 --- a/crates/nostream-mcp/tests/audit.rs +++ b/crates/nostream-mcp/tests/audit.rs @@ -2,10 +2,11 @@ //! //! | case | what it proves | //! |---|---| -//! | `each_call_appends_one_line` | five calls append six lines in call order — the five `mcp.*` lines, then `settings_set`'s own `settings.updated` | +//! | `each_call_appends_one_line` | seven calls append eight lines in call order — the seven `mcp.*` lines, then `settings_set`'s own `settings.updated` | //! | `a_refused_call_appends_nothing` | a call with bad arguments and a call with no credential each leave the file untouched | //! | `every_registered_tool_has_a_table_row` | the table is total over the router's own list, so no tool can execute unaudited or ungated | //! | `the_audit_check_is_no_stricter_than_the_router` | the table's rule is the router's deserialiser, not the schema: a stricter check would fail open | +//! | `the_write_tools_detail_carries_only_the_tool` | the two write tools' lines carry `{"tool": …}` and nothing else: no id, no action, no address | //! R9 appends the `mcp.*` line at dispatch, before the handler's work, so the order in the file //! is the order of the calls and a domain line always follows its own dispatch line. The one //! refusal that does write is a credential's scope denial — `mcp.denied`, R28 — and it has its @@ -19,8 +20,8 @@ use std::collections::BTreeSet; use common::{TestMcp, event, id_of, object, text}; use nostream_mcp::{ - TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, - TOOLS, audit_action, + TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, + TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, audit_action, }; use serde_json::json; @@ -35,6 +36,14 @@ async fn each_call_appends_one_line() { client.call(TOOL_SETTINGS_GET, json!({})).await; client.call(TOOL_LIST_EVENTS, json!({})).await; client.call(TOOL_GET_EVENT, json!({ "id": id })).await; + client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await; + let report_id = "ab".repeat(32); + client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id, "action": "allow" }), + ) + .await; client.call(TOOL_RELAY_STATUS, json!({})).await; let written = client .call( @@ -55,6 +64,8 @@ async fn each_call_appends_one_line() { "mcp.settings_get", "mcp.list_events", "mcp.get_event", + "mcp.delete_event", + "mcp.reports_action", "mcp.relay_status", "mcp.settings_set", "settings.updated", @@ -66,6 +77,8 @@ async fn each_call_appends_one_line() { TOOL_SETTINGS_GET, TOOL_LIST_EVENTS, TOOL_GET_EVENT, + TOOL_DELETE_EVENT, + TOOL_REPORTS_ACTION, TOOL_RELAY_STATUS, TOOL_SETTINGS_SET, ]) { @@ -80,20 +93,68 @@ async fn each_call_appends_one_line() { } assert_eq!( - entries[3]["detail"]["tool"], + entries[5]["detail"]["tool"], json!(TOOL_RELAY_STATUS), - "the fourth line is the status call's own: {entries:?}" + "the sixth line is the status call's own: {entries:?}" ); assert_eq!( - entries[4]["detail"]["paths"], + entries[6]["detail"]["paths"], json!(["wot.enabled"]), "the settings write names the paths it asked for, never the values" ); assert!( - entries[4]["detail"].get("value").is_none(), + entries[6]["detail"].get("value").is_none(), "no value is recorded: {}", - entries[4] + entries[6] + ); +} + +/// R24: both write tools' lines carry the tool and nothing else. A `detail` carrying the id or +/// the action would let a caller's own text shape a record, which the `settings_set` arm +/// deliberately does not do — it passes the requested paths, which are its request. +#[tokio::test] +async fn the_write_tools_detail_carries_only_the_tool() { + let fixture = TestMcp::start().await; + let record = event(22, 1, 1_699_999_961); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let deleted = client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await; + assert_eq!(deleted.is_error, Some(false), "{}", text(&deleted)); + let report_id = "cd".repeat(32); + let acted = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id, "action": "allow" }), + ) + .await; + assert_eq!(acted.is_error, Some(false), "{}", text(&acted)); + + let entries = fixture.audit_entries(); + let actions: Vec = entries + .iter() + .map(|entry| entry["action"].as_str().unwrap_or_default().to_owned()) + .collect(); + assert_eq!( + actions, + vec![ + audit_action(TOOL_DELETE_EVENT), + audit_action(TOOL_REPORTS_ACTION) + ], + "{entries:?}" ); + for (entry, tool) in entries.iter().zip([TOOL_DELETE_EVENT, TOOL_REPORTS_ACTION]) { + assert_eq!( + entry["detail"], + json!({ "tool": tool }), + "{tool}'s detail names the tool and nothing else: {entry}" + ); + assert!( + entry.get("remoteAddress").is_none(), + "a stdio caller has no address: {entry}" + ); + } } #[tokio::test] diff --git a/crates/nostream-mcp/tests/auth.rs b/crates/nostream-mcp/tests/auth.rs index 903a3786b..c6abe6f87 100644 --- a/crates/nostream-mcp/tests/auth.rs +++ b/crates/nostream-mcp/tests/auth.rs @@ -3,13 +3,13 @@ //! //! | case | what it proves | //! |---|---| -//! | `a_revoked_token_refuses_every_tool` | a deleted document answers `Unauthorized` to all five tools, writes nothing, and still lists them | +//! | `a_revoked_token_refuses_every_tool` | a deleted document answers `Unauthorized` to all seven tools, writes nothing, and still lists them | //! | `a_read_only_token_is_refused_the_write` | a document with no scope reads and is refused `settings_set`, and the denial is a line in `admin-audit.jsonl` | //! | `a_disabled_surface_is_refused` | `admin.enabled: false` answers `Not Found`, as the console does | //! | `an_unknown_scope_refuses_the_load` | a document naming a scope the door does not know is refused when it is loaded, naming the scope and the accepted set | //! | `a_file_rewrite_changes_the_decision` | rewriting the file on a running server narrows the write, and rewriting it back restores it: the file's lifetime is the credential's | //! | `an_inherited_descriptor_authenticates` | the descriptor form answers `tools/list` and a read, and keeps the grant it was handed when the file it came from changes | -//! | `only_the_writing_tool_needs_a_scope` | the table names every registered tool and declares a scope for each: the four read tools read, `settings_set` needs `write`, and a name the table does not carry needs `write` | +//! | `only_the_writing_tool_needs_a_scope` | the table names every registered tool and declares a scope for each: the four read tools read, the three writes need `write`, and a name the table does not carry needs `write` | //! | `an_unregistered_tool_is_refused_before_the_scopes` | a name the surface does not register is refused with the router's own `-32602` before the scope decision, so a read-only document writes no denial line for it | //! | `a_group_readable_descriptor_refuses_to_start` | a `0644` document on a descriptor is refused as the same file by path is | //! | `a_device_descriptor_refuses_to_start` | a device on the descriptor is refused before a byte is read, so `/dev/zero` cannot hang the start | @@ -31,14 +31,14 @@ use std::os::unix::fs::PermissionsExt; use common::{Fixture, Grant, TestMcp, text, write_token}; use nostream_mcp::{ AUDIT_DENIED, Credential, FORBIDDEN, MAX_TOKEN_DOCUMENT_BYTES, NOT_FOUND, Requires, - TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, - TOOLS, UNAUTHORIZED, audit_action, required_scope, + TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, + TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, UNAUTHORIZED, audit_action, required_scope, }; use serde_json::json; -/// The five tools, each with arguments its schema accepts, so the refusal cannot be a +/// The seven tools, each with arguments its schema accepts, so the refusal cannot be a /// deserialisation failure in disguise. -fn calls() -> [(&'static str, serde_json::Value); 5] { +fn calls() -> [(&'static str, serde_json::Value); 7] { [ (TOOL_SETTINGS_GET, json!({})), ( @@ -47,6 +47,11 @@ fn calls() -> [(&'static str, serde_json::Value); 5] { ), (TOOL_LIST_EVENTS, json!({})), (TOOL_GET_EVENT, json!({ "id": "0123456789abcdef" })), + (TOOL_DELETE_EVENT, json!({ "id": "0123456789abcdef" })), + ( + TOOL_REPORTS_ACTION, + json!({ "id": "ab".repeat(32), "action": "hide" }), + ), (TOOL_RELAY_STATUS, json!({})), ] } @@ -58,7 +63,7 @@ async fn a_revoked_token_refuses_every_tool() { fixture.revoke(); let client = fixture.client().await; - assert_eq!(client.tools().await.len(), 5, "tools/list is not gated"); + assert_eq!(client.tools().await.len(), 7, "tools/list is not gated"); for (tool, arguments) in calls() { let result = client.call(tool, arguments).await; assert_eq!(result.is_error, Some(true), "{tool}: {}", text(&result)); @@ -227,7 +232,7 @@ async fn an_inherited_descriptor_authenticates() { .iter() .map(|tool| tool.name.to_string()) .collect(); - assert_eq!(names.len(), 5, "{names:?}"); + assert_eq!(names.len(), 7, "{names:?}"); let read = client.call(TOOL_SETTINGS_GET, json!({})).await; assert_eq!(read.is_error, Some(false), "{}", text(&read)); @@ -285,15 +290,15 @@ async fn only_the_writing_tool_needs_a_scope() { ); assert_eq!( writing, - vec![TOOL_SETTINGS_SET], - "the one tool that changes the relay is the one a document opts into" + vec![TOOL_DELETE_EVENT, TOOL_REPORTS_ACTION, TOOL_SETTINGS_SET], + "the tools that change the relay are the ones a document opts into" ); // A name the table does not carry needs the write: that is this helper's answer for it, and // the reason a missing row fails closed rather than open. `call_tool` refuses such a name // before it asks — see `an_unregistered_tool_is_refused_before_the_scopes` — so a rowless tool // never reaches dispatch at all. - assert_eq!(required_scope("delete_event"), Requires::Write); + assert_eq!(required_scope("user_admin"), Requires::Write); } /// A name the surface does not register is refused before the scope decision, so a document that @@ -310,7 +315,7 @@ async fn an_unregistered_tool_is_refused_before_the_scopes() { let client = fixture.client().await; let error = client - .try_call("delete_event", json!({})) + .try_call("user_admin", json!({})) .await .expect_err("a name the table does not carry is not a tool"); let rmcp::ServiceError::McpError(error) = error else { diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index 5c79e6ac5..4c7e7e8cf 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -70,7 +70,7 @@ pub fn base_settings() -> serde_yaml::Value { /// The scopes the fixture's token document names. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Grant { - /// `{"scopes": ["write"]}`: the four read tools and `settings_set`. + /// `{"scopes": ["write"]}`: the four read tools and the three writes. #[default] Write, /// `{"scopes": []}`: the read tools only — the door's default (R28). @@ -109,6 +109,8 @@ pub struct Fixture { pub now_ms: u64, /// The store bundle the state is composed over. pub stores: Stores, + /// The report repository a case supplies in place of the backend's own. + pub reports: Option, } impl Default for Fixture { @@ -119,6 +121,7 @@ impl Default for Fixture { grant: Grant::Write, now_ms: NOW_MS, stores: Stores::Seeded, + reports: None, } } } @@ -136,6 +139,14 @@ impl Fixture { pub type EventRepositoryFactory = Arc) -> Arc + Send + Sync>; +/// Builds the report repository a case wants over the harness's own backend — for a case whose +/// subject is the handler's own ordering, which a store that answers ascending cannot show. +pub type ReportRepositoryFactory = Arc< + dyn Fn(Arc) -> Arc + + Send + + Sync, +>; + /// One composed server over a temporary config dir, and what it was composed with. pub struct TestMcp { pub state: Arc, @@ -176,10 +187,20 @@ impl TestMcp { let token_path = write_token(&config_dir, fixture.grant.names()); let credential = Credential::from_file(&token_path).unwrap(); + // The paths both the store and the state read: the backend is opened with the settings + // the state serves, so the NIP-56 gate a case turns on is the gate its store applies. + let paths = SettingsPaths::from_config_dir(&repo_root(), &config_dir); // The backend is always opened, so a case can seed it; when the fixture asks for the // daemon's bundle the state reads `unavailable::stores()` instead, and the seeded rows // are simply never reached. - let backend = LmdbBackend::open(temp.path().join("store")).await.unwrap(); + let backend = LmdbBackend::open(temp.path().join("store")) + .await + .unwrap() + .with_settings(Arc::new( + nostream_config::load(&paths) + .expect("the fixture's settings load") + .settings, + )); let backend = Arc::new(backend); let stores = match fixture.stores { Stores::Seeded => Arc::new(ServiceStores { @@ -199,6 +220,13 @@ impl TestMcp { as Arc, notification_delivery_log: Arc::clone(&backend) as Arc, + reports: fixture.reports.as_ref().map_or_else( + || { + Arc::clone(&backend) + as Arc + }, + |wrap| wrap(Arc::clone(&backend)), + ), }), Stores::Unavailable => Arc::new(nostream_services::unavailable::stores()), }; @@ -210,7 +238,7 @@ impl TestMcp { let clock = Arc::new(TestClock::new(fixture.now_ms)); let state = Arc::new(AdminState::with_random( AdminStateConfig { - paths: SettingsPaths::from_config_dir(&repo_root(), &config_dir), + paths, resources_root: resources_root(), secret: fixture.secret, stores, @@ -565,6 +593,12 @@ impl EventRepository for VanishingRepository { self.inner.find_reconciliation_items(filter) } + /// Fully qualified rather than a method call, so the ungated read has exactly one call site + /// in the workspace and the criterion that counts it (AC8's fourth leg) can hold. + fn find_stored<'a>(&'a self, id: &'a EventId) -> StorageFuture<'a, Option> { + EventRepository::find_stored(&*self.inner, id) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, pubkey: &'a Pubkey, @@ -628,3 +662,144 @@ impl EventRepository for VanishingRepository { self.inner.delete_all_events() } } + +/// The real backend, whose delete reports that it changed nothing even though it did. +/// +/// The tool takes its outcome from the row as it stands **after** the call, and neither real +/// backend can disagree with itself: each answers the count of rows it changed, so a zero beside a +/// deleted row needs a row that changed between the two reads. That is the race two concurrent +/// deletes make — this call reads the row live, another deletes it, and this one's own delete finds +/// it already marked — and no single-writer run reaches it. This double performs the real soft +/// delete and answers `0`, which leaves the read-back to say what happened. +pub struct ZeroCountDeleter { + inner: Arc, +} + +impl ZeroCountDeleter { + /// The backend, with a delete that under-reports its count. + pub fn new(inner: Arc) -> Self { + Self { inner } + } +} + +impl EventRepository for ZeroCountDeleter { + fn create<'a>(&'a self, record: &'a EventRecord) -> StorageFuture<'a, u64> { + self.inner.create(record) + } + + fn create_many<'a>(&'a self, records: &'a [EventRecord]) -> StorageFuture<'a, u64> { + self.inner.create_many(records) + } + + fn upsert<'a>(&'a self, record: &'a EventRecord) -> StorageFuture<'a, u64> { + self.inner.upsert(record) + } + + fn upsert_many<'a>(&'a self, records: &'a [EventRecord]) -> StorageFuture<'a, u64> { + self.inner.upsert_many(records) + } + + fn find_by_filters<'a>( + &'a self, + filters: &'a [Filter], + ) -> StorageFuture<'a, QueryStream<'a, StreamedEvent>> { + self.inner.find_by_filters(filters) + } + + fn count_by_filters<'a>(&'a self, filters: &'a [Filter]) -> StorageFuture<'a, u64> { + self.inner.count_by_filters(filters) + } + + fn page_bound(&self) -> u64 { + self.inner.page_bound() + } + + fn search_rule(&self) -> nostream_storage::repositories::SearchRule { + self.inner.search_rule() + } + + fn empty_tag_rule(&self) -> nostream_storage::repositories::EmptyTagRule { + self.inner.empty_tag_rule() + } + + fn find_reconciliation_items<'a>( + &'a self, + filter: &'a Filter, + ) -> StorageFuture<'a, QueryStream<'a, nostream_storage::repositories::ReconciliationItem>> + { + self.inner.find_reconciliation_items(filter) + } + + /// Fully qualified rather than a method call, so the ungated read has exactly one call site + /// in the workspace and the criterion that counts it (AC8's fourth leg) can hold. + fn find_stored<'a>(&'a self, id: &'a EventId) -> StorageFuture<'a, Option> { + EventRepository::find_stored(&*self.inner, id) + } + + /// The real soft delete, and a count that says nothing happened. + fn delete_by_pubkey_and_ids<'a>( + &'a self, + pubkey: &'a Pubkey, + ids: &'a [EventId], + ) -> StorageFuture<'a, u64> { + Box::pin(async move { + self.inner.delete_by_pubkey_and_ids(pubkey, ids).await?; + Ok(0) + }) + } + + fn delete_by_addresses<'a>( + &'a self, + pubkey: &'a Pubkey, + addresses: &'a [(Kind, String)], + not_after: i64, + ) -> StorageFuture<'a, u64> { + self.inner.delete_by_addresses(pubkey, addresses, not_after) + } + + fn delete_by_pubkey_except_kinds<'a>( + &'a self, + pubkey: &'a Pubkey, + excluded_kinds: &'a [Kind], + ) -> StorageFuture<'a, u64> { + self.inner + .delete_by_pubkey_except_kinds(pubkey, excluded_kinds) + } + + fn has_active_request_to_vanish<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, bool> { + self.inner.has_active_request_to_vanish(pubkey) + } + + fn delete_expired_and_retained<'a>( + &'a self, + options: &'a nostream_storage::repositories::EventRetentionOptions, + ) -> StorageFuture<'a, nostream_storage::repositories::EventPurgeCounts> { + self.inner.delete_expired_and_retained(options) + } + + fn scan_live<'a>( + &'a self, + after: Option, + limit: u64, + ) -> StorageFuture<'a, QueryStream<'a, nostream_storage::repositories::EventRecord>> { + self.inner.scan_live(after, limit) + } + + fn count_by_criteria<'a>( + &'a self, + criteria: &'a nostream_storage::repositories::EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + self.inner.count_by_criteria(criteria) + } + + fn delete_by_criteria<'a>( + &'a self, + criteria: &'a nostream_storage::repositories::EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + self.inner.delete_by_criteria(criteria) + } + + fn delete_all_events(&self) -> StorageFuture<'_, ()> { + self.inner.delete_all_events() + } +} diff --git a/crates/nostream-mcp/tests/fixtures/tools_list.json b/crates/nostream-mcp/tests/fixtures/tools_list.json index c43c083cc..7c115224a 100644 --- a/crates/nostream-mcp/tests/fixtures/tools_list.json +++ b/crates/nostream-mcp/tests/fixtures/tools_list.json @@ -1,5 +1,23 @@ { "tools": [ + { + "description": "Mark one stored event deleted: the same soft delete a NIP-09 request from the author makes. The event leaves REQ and COUNT and keeps its row, so `get_event` and `list_events` still return it with `deleted_at` set — unless an actionable report hides it, in which case it stays hidden until the report is allowed. The argument is the event's hex id; a prefix shorter than 64 characters is refused rather than widened to whatever the store's range would match. Answers `outcome` — `deleted`, `already_deleted`, `not_deleteable` (kind 62 is never deleted), or `not_found` — and the row as it stands after the call", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "id": { + "description": "The event's hex id, in either case; a prefix shorter than 64 characters is refused and deletes nothing", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "name": "delete_event" + }, { "description": "Read one stored event by its exact 64-character hex id, in either case; null when no such id is stored", "inputSchema": { @@ -95,6 +113,33 @@ }, "name": "relay_status" }, + { + "description": "Act on one report event: `hide` marks its targets hidden (`actionable: true`, so REQ and COUNT withhold them while `nip56.hideActionableReports` is on) and `allow` clears them (`actionable: false`). The argument is the report's own kind-1984 event id — exactly 64 hex characters, not the reported event's id — and every report row that event wrote is flipped. Answers `reports` (the rows as they stand, by `id`) and `changed` (how many this call flipped). Every new REQ reflects the change at once; already-connected subscriptions see it at the relay's next refresh, up to 30 s", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "action": { + "description": "`hide` marks the report's targets hidden; `allow` clears them", + "enum": [ + "hide", + "allow" + ], + "type": "string" + }, + "id": { + "description": "The report's own kind-1984 event id, exactly 64 hex characters in either case; not the reported event's id", + "type": "string" + } + }, + "required": [ + "id", + "action" + ], + "type": "object" + }, + "name": "reports_action" + }, { "description": "Read the merged settings document, narrowed to the defaults' keys and redacted. The document arrives under `settings`", "inputSchema": { diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs index e70952799..bf406f131 100644 --- a/crates/nostream-mcp/tests/tool_payloads.rs +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -330,7 +330,7 @@ async fn an_unknown_tool_is_a_protocol_error() { let client = fixture.client().await; let error = client - .try_call("delete_event", json!({})) + .try_call("user_admin", json!({})) .await .expect_err("an absent tool is a JSON-RPC error, not a result"); let rmcp::ServiceError::McpError(error) = error else { diff --git a/crates/nostream-mcp/tests/tools_list.rs b/crates/nostream-mcp/tests/tools_list.rs index 76bcc76f9..f21858654 100644 --- a/crates/nostream-mcp/tests/tools_list.rs +++ b/crates/nostream-mcp/tests/tools_list.rs @@ -18,8 +18,8 @@ mod common; use common::TestMcp; use nostream_mcp::{ - MAX_ROWS_PER_PAGE, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, - TOOL_SETTINGS_SET, + MAX_ROWS_PER_PAGE, TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, + TOOL_REPORTS_ACTION, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, }; use serde_json::{Value, json}; @@ -173,13 +173,15 @@ async fn the_required_parameters_are_typed() { assert_eq!( names, vec![ + TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, + TOOL_REPORTS_ACTION, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET ], - "the five tools, name-sorted" + "the seven tools, name-sorted" ); } @@ -215,6 +217,8 @@ async fn initialize_publishes_the_prerequisites() { "write", "mcp.denied", TOOL_RELAY_STATUS, + TOOL_DELETE_EVENT, + TOOL_REPORTS_ACTION, ] { assert!( instructions.contains(needle), diff --git a/crates/nostream-mcp/tests/write_tools.rs b/crates/nostream-mcp/tests/write_tools.rs new file mode 100644 index 000000000..2c235771d --- /dev/null +++ b/crates/nostream-mcp/tests/write_tools.rs @@ -0,0 +1,763 @@ +//! The two write tools' oracle: every outcome a delete can answer, the read-back the payload +//! discloses, the gate moving under `hide`/`allow`, and the two refusal paths — through the +//! protocol a client uses. +//! +//! | case | what it proves | +//! |---|---| +//! | `a_first_delete_marks_the_row_and_says_so` | a live row is marked deleted, the payload carries the store's own `deleted_at`, and both event tools still return it | +//! | `a_second_delete_says_already_deleted` | the store skips the second call and the timestamp does not move | +//! | `a_prefix_is_not_an_id_and_deletes_nothing` | a four-character prefix is refused by the length check before any read, and the row it named is still live | +//! | `an_unknown_id_is_not_found_not_an_error` | an id nothing carries is a result, not an error | +//! | `a_request_to_vanish_is_never_deleted` | kind 62 is the store's own skip, and the payload says which row it was | +//! | `a_deleted_event_leaves_the_counts` | a soft delete leaves COUNT, through the door's own call | +//! | `a_read_only_document_is_refused_both_writes` | both writes are refused by name, two `mcp.denied` lines are written, and nothing moved | +//! | `allowing_a_report_returns_its_target_to_the_listing` | `allow` flips the row and all three indexes, so the event comes back to a REQ | +//! | `hiding_a_report_withholds_its_target_again` | `hide` puts it back | +//! | `a_second_allow_changes_nothing` | a value that already holds is not written and not counted | +//! | `every_row_of_one_report_event_moves` | one report event writes one row per target, and one call moves them all | +//! | `an_unknown_report_is_an_empty_answer` | an id with no rows answers an empty list and zero | +//! | `a_report_id_that_is_not_an_exact_id_is_refused` | a short id is refused by the handler, after its dispatch line | +//! | `an_unknown_action_never_reaches_the_handler` | the closed set is the arguments type, so nothing is written | +//! | `an_allow_leaves_a_target_another_report_still_hides` | the action is one row's flag: another actionable report keeps the target hidden | +//! | `a_mixed_report_counts_only_the_rows_that_moved` | `changed` counts the rows that moved, and the payload lists every row of the event | +//! | `a_hidden_event_is_deleted_and_stays_hidden` | an event an actionable report hides is deleted through the ungated read, and the read tools still hide it afterwards | +//! | `a_delete_the_store_underreports_reads_the_row_as_deleted` | the outcome is the post-call row: a zero count beside a deleted row is `already_deleted`, not `not_deleteable` | +//! +//! Four fixtures carry the NIP-56 gate on (`nip56.enabled` and `nip56.hideActionableReports`) — +//! the three report cases and the hidden-event case — which is the only way the setter's index work +//! and the hidden delete are observable. Cases that seed a report row +//! without the gate still exercise the write and the row's flag; what they cannot see is the +//! NIP-56 filter, because their settings leave `nip56.enabled` off and the gate never fires. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use std::sync::Arc; + +use common::{Fixture, Grant, TestMcp, ZeroCountDeleter, event, id_of, payload, text}; +use nostream_core::{EventId, Filter, Pubkey}; +use nostream_mcp::{ + AUDIT_DENIED, FORBIDDEN, OUTCOME_ALREADY_DELETED, OUTCOME_DELETED, OUTCOME_NOT_DELETEABLE, + OUTCOME_NOT_FOUND, TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_REPORTS_ACTION, +}; +use nostream_storage::lmdb::LmdbBackend; +use nostream_storage::repositories::{ + ActionableTarget, EventRepository, NewReport, Report, ReportRepository, ReportType, + StorageFuture, collect_records, +}; +use serde_json::{Value, json}; + +/// The `ids` a `list_events` answer carried, in payload order. +fn listed(payload: &Value) -> Vec { + payload["events"] + .as_array() + .expect("a list_events payload") + .iter() + .map(|event| event["event"]["id"].as_str().unwrap_or_default().to_owned()) + .collect() +} + +/// One `list_events` call for a kind, and the ids it answered. +async fn listing(client: &common::Mcp, kinds: &[u64]) -> Vec { + let result = client + .call(TOOL_LIST_EVENTS, json!({ "kinds": kinds })) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + listed(&payload(&result)) +} + +/// An actionable report row naming `record`'s pubkey and id, keyed by its own event id. +async fn seed_report( + fixture: &TestMcp, + report_event: [u8; 32], + record: &nostream_storage::repositories::EventRecord, +) { + let report = NewReport { + event_id: EventId::from_byte_array(report_event), + reporter_pubkey: Pubkey::from_byte_array([90; 32]), + reported_pubkey: Some(record.event.pubkey), + reported_event_id: Some(record.event.id), + report_type: ReportType::Spam, + weight: 1.0, + actionable: true, + }; + ReportRepository::create(&*fixture.backend, &report) + .await + .expect("the report stores"); +} + +#[tokio::test] +async fn a_first_delete_marks_the_row_and_says_so() { + let fixture = TestMcp::start().await; + let record = event(21, 1, 1_699_999_960); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let deleted = client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await; + assert_eq!(deleted.is_error, Some(false), "{}", text(&deleted)); + let answer = payload(&deleted); + assert_eq!(answer["outcome"], OUTCOME_DELETED, "{answer}"); + assert!( + answer["event"]["deleted_at"].is_string(), + "the payload carries the store's own deletion time: {answer}" + ); + assert_eq!(answer["event"]["event"]["id"], json!(id), "{answer}"); + let first = answer["event"]["deleted_at"].clone(); + + // R5's disclosure, checked rather than asserted in prose: the row is still readable by both + // event tools, with its deletion time. + let read = client.call(TOOL_GET_EVENT, json!({ "id": id })).await; + assert_eq!(read.is_error, Some(false), "{}", text(&read)); + assert_eq!(payload(&read)["event"]["deleted_at"], first); + + let listing = client.call(TOOL_LIST_EVENTS, json!({ "ids": [id] })).await; + assert_eq!(listing.is_error, Some(false), "{}", text(&listing)); + let events = payload(&listing)["events"].as_array().unwrap().clone(); + assert_eq!(events.len(), 1, "one row, still listed: {events:?}"); + assert_eq!(events[0]["deleted_at"], first); +} + +#[tokio::test] +async fn a_second_delete_says_already_deleted() { + let fixture = TestMcp::start().await; + let record = event(22, 1, 1_699_999_961); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let first = payload(&client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await); + let second = payload(&client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await); + assert_eq!(second["outcome"], OUTCOME_ALREADY_DELETED, "{second}"); + assert_eq!( + second["event"]["deleted_at"], first["event"]["deleted_at"], + "the second call does not move the timestamp: {first} {second}" + ); +} + +#[tokio::test] +async fn a_prefix_is_not_an_id_and_deletes_nothing() { + let fixture = TestMcp::start().await; + let record = event(23, 1, 1_699_999_962); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let prefix = &id[..4]; + let refused = client + .call(TOOL_DELETE_EVENT, json!({ "id": prefix })) + .await; + assert_eq!(refused.is_error, Some(true), "{}", text(&refused)); + assert_eq!( + text(&refused), + format!("id: {prefix:?} is not a 64-character hex id"), + "the length check refuses a prefix before any read" + ); + + let read = client.call(TOOL_GET_EVENT, json!({ "id": id })).await; + assert!( + payload(&read)["event"]["deleted_at"].is_null(), + "the row the prefix widened to is untouched: {}", + payload(&read) + ); +} + +#[tokio::test] +async fn an_unknown_id_is_not_found_not_an_error() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let deleted = client + .call(TOOL_DELETE_EVENT, json!({ "id": "ab".repeat(32) })) + .await; + assert_eq!(deleted.is_error, Some(false), "{}", text(&deleted)); + let answer = payload(&deleted); + assert_eq!(answer["outcome"], OUTCOME_NOT_FOUND, "{answer}"); + assert!(answer["event"].is_null(), "{answer}"); +} + +#[tokio::test] +async fn a_request_to_vanish_is_never_deleted() { + let fixture = TestMcp::start().await; + let record = event(24, 62, 1_699_999_963); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let deleted = client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await; + let answer = payload(&deleted); + assert_eq!(answer["outcome"], OUTCOME_NOT_DELETEABLE, "{answer}"); + assert_eq!(answer["event"]["event"]["kind"], 62, "{answer}"); + assert!(answer["event"]["deleted_at"].is_null(), "{answer}"); + + let read = client.call(TOOL_GET_EVENT, json!({ "id": id })).await; + assert!(payload(&read)["event"]["deleted_at"].is_null()); +} + +#[tokio::test] +async fn a_deleted_event_leaves_the_counts() { + let fixture = TestMcp::start().await; + let record = event(25, 1, 1_699_999_964); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let filters = [Filter { + ids: Some(vec![id.clone()]), + ..Filter::default() + }]; + assert_eq!( + fixture.backend.count_by_filters(&filters).await.unwrap(), + 1, + "the row is counted to begin with" + ); + + let deleted = client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await; + assert_eq!(payload(&deleted)["outcome"], OUTCOME_DELETED); + + assert_eq!( + fixture.backend.count_by_filters(&filters).await.unwrap(), + 0, + "COUNT applies the live predicate (V13)" + ); +} + +#[tokio::test] +async fn a_read_only_document_is_refused_both_writes() { + let fixture = TestMcp::start_with(Fixture { + grant: Grant::Read, + ..Fixture::default() + }) + .await; + let record = event(26, 1, 1_699_999_965); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let report_id = EventId::from_byte_array([46; 32]).to_string(); + seed_report(&fixture, [46; 32], &record).await; + let client = fixture.client().await; + + let deleted = client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await; + let acted = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id, "action": "allow" }), + ) + .await; + + // The state is asserted before the refusals, so the subject of "nothing ran" is a row the + // call would have moved: `allow` at an actionable row is a write, `hide` at one is a skip + // the store does not perform. + let rows = collect_records( + fixture + .backend + .find_by_filters(&[Filter { + ids: Some(vec![id.clone()]), + ..Filter::default() + }]) + .await + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(rows.len(), 1); + assert!( + rows[0].deleted_at.is_none(), + "the refused delete moved nothing" + ); + let reports = fixture + .backend + .find_by_event_id(&EventId::from_byte_array([46; 32])) + .await + .unwrap(); + assert_eq!(reports.len(), 1, "the report row the refused call named"); + assert!( + reports[0].actionable, + "the refused report action moved nothing: {reports:?}" + ); + + for (tool, refused) in [(TOOL_DELETE_EVENT, &deleted), (TOOL_REPORTS_ACTION, &acted)] { + assert_eq!(refused.is_error, Some(true), "{tool}"); + let refusal = text(refused); + assert!(refusal.contains(FORBIDDEN), "{tool}: {refusal}"); + assert!(refusal.contains(tool), "{tool}: {refusal}"); + } + + let entries = fixture.audit_entries(); + let actions: Vec<&str> = entries + .iter() + .map(|entry| entry["action"].as_str().unwrap_or_default()) + .collect(); + assert_eq!(actions, vec![AUDIT_DENIED, AUDIT_DENIED], "{entries:?}"); + for entry in &entries { + assert_eq!(entry["detail"]["scope"], "write", "{entry}"); + assert!(entry["detail"]["tool"].as_str().is_some(), "{entry}"); + assert!( + entry.get("remoteAddress").is_none(), + "a stdio caller has no address: {entry}" + ); + } +} + +#[tokio::test] +async fn allowing_a_report_returns_its_target_to_the_listing() { + let fixture = TestMcp::start_with( + Fixture::default() + .with("nip56.enabled", json!(true)) + .with("nip56.hideActionableReports", json!(true)), + ) + .await; + let record = event(27, 1, 1_699_999_966); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let report_id = EventId::from_byte_array([47; 32]).to_string(); + seed_report(&fixture, [47; 32], &record).await; + let client = fixture.client().await; + + assert!( + !listing(&client, &[1]).await.contains(&id), + "the gate withholds the reported event" + ); + + let acted = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id, "action": "allow" }), + ) + .await; + assert_eq!(acted.is_error, Some(false), "{}", text(&acted)); + let answer = payload(&acted); + assert_eq!(answer["changed"], 1, "{answer}"); + assert_eq!(answer["reports"][0]["actionable"], false, "{answer}"); + + assert!( + listing(&client, &[1]).await.contains(&id), + "the event returns to a REQ once the row stops being actionable" + ); + assert!( + fixture + .backend + .find_actionable_targets() + .await + .unwrap() + .is_empty(), + "the index entry is gone, not only the row's flag" + ); + assert!( + fixture + .backend + .find_actionable(10) + .await + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn hiding_a_report_withholds_its_target_again() { + let fixture = TestMcp::start_with( + Fixture::default() + .with("nip56.enabled", json!(true)) + .with("nip56.hideActionableReports", json!(true)), + ) + .await; + let record = event(28, 1, 1_699_999_967); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let report_id = EventId::from_byte_array([48; 32]).to_string(); + seed_report(&fixture, [48; 32], &record).await; + let client = fixture.client().await; + + let allowed = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id, "action": "allow" }), + ) + .await; + assert_eq!(payload(&allowed)["changed"], 1); + assert!(listing(&client, &[1]).await.contains(&id)); + + let hidden = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id, "action": "hide" }), + ) + .await; + assert_eq!(hidden.is_error, Some(false), "{}", text(&hidden)); + let answer = payload(&hidden); + assert_eq!(answer["changed"], 1, "{answer}"); + assert_eq!(answer["reports"][0]["actionable"], true, "{answer}"); + assert!( + !listing(&client, &[1]).await.contains(&id), + "the gate withholds it again: the index entry came back with the flag" + ); +} + +#[tokio::test] +async fn a_second_allow_changes_nothing() { + let fixture = TestMcp::start().await; + let record = event(29, 1, 1_699_999_968); + fixture.seed(std::slice::from_ref(&record)).await; + let report_id = EventId::from_byte_array([49; 32]).to_string(); + seed_report(&fixture, [49; 32], &record).await; + let client = fixture.client().await; + + let first = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id, "action": "allow" }), + ) + .await; + assert_eq!(payload(&first)["changed"], 1); + + let second = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id, "action": "allow" }), + ) + .await; + assert_eq!(second.is_error, Some(false), "{}", text(&second)); + let answer = payload(&second); + assert_eq!(answer["changed"], 0, "{answer}"); + assert_eq!(answer["reports"][0]["actionable"], false, "{answer}"); + assert_eq!(answer["reports"].as_array().unwrap().len(), 1, "{answer}"); +} + +/// A report store that answers one event's rows **newest id first**, which is not the order the +/// handler must publish. LMDB walks `(event_id, report_id)` ascending by construction, so a case +/// reading the real store cannot tell a sorted payload from an unsorted one; every other method is +/// the backend's own. +struct NewestFirst(Arc); + +impl ReportRepository for NewestFirst { + fn create<'a>(&'a self, report: &'a NewReport) -> StorageFuture<'a, Report> { + self.0.create(report) + } + + fn create_many<'a>(&'a self, reports: &'a [NewReport]) -> StorageFuture<'a, Vec> { + self.0.create_many(reports) + } + + fn find_by_event_id<'a>(&'a self, event_id: &'a EventId) -> StorageFuture<'a, Vec> { + Box::pin(async move { + let mut rows = self.0.find_by_event_id(event_id).await?; + rows.reverse(); + Ok(rows) + }) + } + + fn find_actionable<'a>(&'a self, limit: u64) -> StorageFuture<'a, Vec> { + self.0.find_actionable(limit) + } + + fn find_actionable_targets<'a>(&'a self) -> StorageFuture<'a, Vec> { + self.0.find_actionable_targets() + } + + fn set_actionable<'a>( + &'a self, + event_id: &'a EventId, + actionable: bool, + ) -> StorageFuture<'a, u64> { + self.0.set_actionable(event_id, actionable) + } +} + +#[tokio::test] +async fn every_row_of_one_report_event_moves() { + let fixture = TestMcp::start_with(Fixture { + reports: Some(Arc::new(|backend| { + Arc::new(NewestFirst(backend)) as Arc + })), + ..Fixture::default() + }) + .await; + let one = event(30, 1, 1_699_999_969); + let two = event(31, 1, 1_699_999_970); + fixture.seed(&[one.clone(), two.clone()]).await; + let report_id = EventId::from_byte_array([50; 32]); + let rows = [ + NewReport { + event_id: report_id, + reporter_pubkey: Pubkey::from_byte_array([91; 32]), + reported_pubkey: Some(one.event.pubkey), + reported_event_id: Some(one.event.id), + report_type: ReportType::Spam, + weight: 1.0, + actionable: true, + }, + NewReport { + event_id: report_id, + reporter_pubkey: Pubkey::from_byte_array([91; 32]), + reported_pubkey: Some(two.event.pubkey), + reported_event_id: Some(two.event.id), + report_type: ReportType::Spam, + weight: 1.0, + actionable: true, + }, + ]; + ReportRepository::create_many(&*fixture.backend, &rows) + .await + .expect("the two report rows store"); + let client = fixture.client().await; + + let acted = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id.to_string(), "action": "allow" }), + ) + .await; + assert_eq!(acted.is_error, Some(false), "{}", text(&acted)); + let answer = payload(&acted); + assert_eq!(answer["changed"], 2, "{answer}"); + let reports = answer["reports"].as_array().unwrap(); + assert_eq!(reports.len(), 2, "{answer}"); + assert!(reports.iter().all(|row| row["actionable"] == false)); + let ids: Vec = reports + .iter() + .map(|row| row["id"].as_i64().expect("a report id")) + .collect(); + assert!(ids[0] < ids[1], "the payload is ordered by `id`: {ids:?}"); +} + +#[tokio::test] +async fn an_unknown_report_is_an_empty_answer() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let acted = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": "ab".repeat(32), "action": "hide" }), + ) + .await; + assert_eq!(acted.is_error, Some(false), "{}", text(&acted)); + let answer = payload(&acted); + assert_eq!(answer["reports"], json!([]), "{answer}"); + assert_eq!(answer["changed"], 0, "{answer}"); +} + +#[tokio::test] +async fn a_report_id_that_is_not_an_exact_id_is_refused() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let refused = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": "abcd", "action": "hide" }), + ) + .await; + assert_eq!(refused.is_error, Some(true)); + assert_eq!( + text(&refused), + "id: \"abcd\" is not a 64-character hex id", + "the handler's own sentence" + ); + + // The dispatch line precedes the handler's refusal, so the file carries exactly one. + let entries = fixture.audit_entries(); + assert_eq!(entries.len(), 1, "{entries:?}"); + assert_eq!(entries[0]["action"], "mcp.reports_action", "{entries:?}"); +} + +#[tokio::test] +async fn an_unknown_action_never_reaches_the_handler() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let refused = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": "ab".repeat(32), "action": "maybe" }), + ) + .await; + assert_eq!(refused.is_error, Some(true), "{}", text(&refused)); + assert!( + fixture.audit_entries().is_empty(), + "the arguments type refuses it before dispatch: {:?}", + fixture.audit_entries() + ); +} + +#[tokio::test] +async fn an_allow_leaves_a_target_another_report_still_hides() { + let fixture = TestMcp::start_with( + Fixture::default() + .with("nip56.enabled", json!(true)) + .with("nip56.hideActionableReports", json!(true)), + ) + .await; + let record = event(32, 1, 1_699_999_971); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let first = EventId::from_byte_array([62; 32]).to_string(); + let second = EventId::from_byte_array([63; 32]).to_string(); + seed_report(&fixture, [62; 32], &record).await; + seed_report(&fixture, [63; 32], &record).await; + let client = fixture.client().await; + + let allowed = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": first, "action": "allow" }), + ) + .await; + assert_eq!(allowed.is_error, Some(false), "{}", text(&allowed)); + assert_eq!(payload(&allowed)["changed"], 1, "one report's rows"); + assert!( + !listing(&client, &[1]).await.contains(&id), + "the other actionable report still names the target, so it stays hidden" + ); + + let both = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": second, "action": "allow" }), + ) + .await; + assert_eq!(payload(&both)["changed"], 1); + assert!( + listing(&client, &[1]).await.contains(&id), + "no actionable report names it now" + ); +} + +#[tokio::test] +async fn a_mixed_report_counts_only_the_rows_that_moved() { + let fixture = TestMcp::start().await; + let record = event(33, 1, 1_699_999_972); + fixture.seed(std::slice::from_ref(&record)).await; + let report_event = EventId::from_byte_array([64; 32]); + ReportRepository::create_many( + &*fixture.backend, + &[ + NewReport { + event_id: report_event, + reporter_pubkey: Pubkey::from_byte_array([92; 32]), + reported_pubkey: Some(record.event.pubkey), + reported_event_id: None, + report_type: ReportType::Spam, + weight: 1.0, + actionable: false, + }, + NewReport { + event_id: report_event, + reporter_pubkey: Pubkey::from_byte_array([92; 32]), + reported_pubkey: None, + reported_event_id: Some(record.event.id), + report_type: ReportType::Spam, + weight: 1.0, + actionable: true, + }, + ], + ) + .await + .expect("the report rows store"); + let client = fixture.client().await; + + let acted = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_event.to_string(), "action": "allow" }), + ) + .await; + assert_eq!(acted.is_error, Some(false), "{}", text(&acted)); + let answer = payload(&acted); + assert_eq!( + answer["changed"], 1, + "only the row whose value moved is counted: {answer}" + ); + let reports = answer["reports"].as_array().unwrap(); + assert_eq!(reports.len(), 2, "both rows are listed: {answer}"); + assert!(reports.iter().all(|row| row["actionable"] == false)); +} + +#[tokio::test] +async fn a_hidden_event_is_deleted_and_stays_hidden() { + let fixture = TestMcp::start_with( + Fixture::default() + .with("nip56.enabled", json!(true)) + .with("nip56.hideActionableReports", json!(true)), + ) + .await; + let record = event(34, 1, 1_699_999_973); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + seed_report(&fixture, [65; 32], &record).await; + let client = fixture.client().await; + + assert!( + !listing(&client, &[1]).await.contains(&id), + "an actionable report hides the event to begin with" + ); + + let deleted = client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await; + assert_eq!(deleted.is_error, Some(false), "{}", text(&deleted)); + let answer = payload(&deleted); + assert_eq!( + answer["outcome"], OUTCOME_DELETED, + "a hidden row is still a stored row, so the delete reaches it: {answer}" + ); + assert!(answer["event"]["deleted_at"].is_string(), "{answer}"); + + // The delete went through the ungated read; the read tools keep the gate. + assert!( + !listing(&client, &[1]).await.contains(&id), + "the list still applies the gate after the delete" + ); + let read = client.call(TOOL_GET_EVENT, json!({ "id": id })).await; + assert!( + payload(&read)["event"].is_null(), + "and so does the exact-id read: {}", + payload(&read) + ); + + let report_id = EventId::from_byte_array([65; 32]).to_string(); + let allowed = client + .call( + TOOL_REPORTS_ACTION, + json!({ "id": report_id, "action": "allow" }), + ) + .await; + assert_eq!(payload(&allowed)["changed"], 1); + let listing = client + .call( + TOOL_LIST_EVENTS, + json!({ "ids": [id.clone()], "kinds": [1] }), + ) + .await; + assert_eq!( + payload(&listing)["events"].as_array().unwrap().len(), + 1, + "the pair coheres: the allowed event is the deleted row" + ); +} + +/// A store whose delete under-reports: it performs the soft delete and answers `0`, which is the +/// state two concurrent deletes leave behind. The row the first read saw live is deleted by the +/// time the read-back runs, so the payload has to call it `already_deleted`; a handler judging the +/// pre-read would answer `not_deleteable` about a row it had just deleted. +#[tokio::test] +async fn a_delete_the_store_underreports_reads_the_row_as_deleted() { + let fixture = TestMcp::start_with_events( + Fixture::default(), + Some(Arc::new(|backend: Arc| { + Arc::new(ZeroCountDeleter::new(backend)) as Arc + })), + ) + .await; + let record = event(1, 1, 1_699_999_974); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let deleted = client.call(TOOL_DELETE_EVENT, json!({ "id": id })).await; + assert_eq!(deleted.is_error, Some(false), "{}", text(&deleted)); + let answer = payload(&deleted); + assert_eq!( + answer["outcome"], OUTCOME_ALREADY_DELETED, + "a zero count beside a deleted row is a delete that lost its race: {answer}" + ); + assert!(answer["event"]["deleted_at"].is_string(), "{answer}"); +} diff --git a/crates/nostream-relay/src/testing.rs b/crates/nostream-relay/src/testing.rs index 0d28cd3a7..c05f30d3c 100644 --- a/crates/nostream-relay/src/testing.rs +++ b/crates/nostream-relay/src/testing.rs @@ -737,6 +737,19 @@ impl EventRepository for InMemoryEventRepository { ) } + /// The recorded rows, by exact id, ungated: this double applies no NIP-56 rule at all. + fn find_stored<'a>(&'a self, id: &'a EventId) -> StorageFuture<'a, Option> { + Box::pin(async move { + Ok(self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .find(|stored| stored.event.id == *id) + .cloned()) + }) + } + /// `UPDATE … SET deleted_at = now()` for the given ids of one author, skipping kind 62. fn delete_by_pubkey_and_ids<'a>( &'a self, @@ -1626,6 +1639,17 @@ impl ReportRepository for InMemoryReportRepository { .clone()) }) } + + /// A double that does not model the setter: no relay case reaches it, and a double that did + /// would have to model the three actionable indexes too — a second implementation of the + /// thing under test. The type's doc calls it a settable-snapshot double, which stays true. + fn set_actionable<'a>( + &'a self, + _event_id: &'a EventId, + _actionable: bool, + ) -> StorageFuture<'a, u64> { + Box::pin(async move { Ok(0) }) + } } /// How many report rows the recorded writes hold. diff --git a/crates/nostream-relay/src/unavailable.rs b/crates/nostream-relay/src/unavailable.rs index a1c09a761..746b323c1 100644 --- a/crates/nostream-relay/src/unavailable.rs +++ b/crates/nostream-relay/src/unavailable.rs @@ -106,6 +106,10 @@ impl EventRepository for UnavailableEventRepository { Box::pin(async { Err(unavailable()) }) } + fn find_stored<'a>(&'a self, _id: &'a EventId) -> StorageFuture<'a, Option> { + Box::pin(async { Err(unavailable()) }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, _pubkey: &'a Pubkey, @@ -340,4 +344,12 @@ impl ReportRepository for UnavailableReportRepository { fn find_actionable_targets<'a>(&'a self) -> StorageFuture<'a, Vec> { Box::pin(async { Err(unavailable()) }) } + + fn set_actionable<'a>( + &'a self, + _event_id: &'a EventId, + _actionable: bool, + ) -> StorageFuture<'a, u64> { + Box::pin(async { Err(unavailable()) }) + } } diff --git a/crates/nostream-services/src/testing.rs b/crates/nostream-services/src/testing.rs index c59842ef9..2842799b2 100644 --- a/crates/nostream-services/src/testing.rs +++ b/crates/nostream-services/src/testing.rs @@ -589,6 +589,18 @@ impl EventRepository for InMemoryEventRepository { }) } + fn find_stored<'a>(&'a self, id: &'a EventId) -> StorageFuture<'a, Option> { + Box::pin(async move { + Ok(self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .find(|stored| stored.event.id == *id) + .cloned()) + }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, pubkey: &'a Pubkey, @@ -1903,6 +1915,7 @@ pub fn context(settings: nostream_config::Settings) -> crate::context::ServiceCo dvm_jobs: InMemoryDvmJobRepository::new(), notification_outbox: InMemoryOutboxRepository::new(), notification_delivery_log: InMemoryDeliveryLogRepository::new(), + reports: nostream_relay::testing::InMemoryReportRepository::new(), }), hub, http, diff --git a/crates/nostream-services/src/unavailable.rs b/crates/nostream-services/src/unavailable.rs index 138cedf13..a3b1caac7 100644 --- a/crates/nostream-services/src/unavailable.rs +++ b/crates/nostream-services/src/unavailable.rs @@ -2,10 +2,11 @@ //! yet hands it. //! //! The relay has its own `Stores` (`nostream_relay::handlers::Stores`) for the six -//! repositories its handlers call; this bundle carries the seven the services call, -//! including the three the relay's bundle does not (invoices, outbox, delivery log). Every -//! call reports `StorageError::NotImplemented`, which is the workspace's convention for an -//! unwired backend (`CLAUDE.md:148-151`). +//! repositories its handlers call; this bundle carries the eight the door and the services +//! reach, including the three the relay's bundle does not (invoices, outbox, delivery log) and +//! `reports`, which only the MCP door's tools read. Every call reports +//! `StorageError::NotImplemented`, which is the workspace's convention for an unwired backend +//! (`CLAUDE.md:148-151`). use std::sync::Arc; @@ -15,11 +16,11 @@ use nostream_storage::repositories::{ DeliveryLogEntry, DeliveryLogFilters, DvmJob, DvmJobRepository, DvmJobUpdate, EventRecord, EventRepository, Invoice, InvoiceRepository, InvoiceStatus, NewDeliveryLogEntry, Nip05Verification, Nip05VerificationRepository, NotificationDeliveryLogRepository, - NotificationOutboxRepository, OutboxMessage, OutboxPayload, QueryStream, + NotificationOutboxRepository, OutboxMessage, OutboxPayload, QueryStream, ReportRepository, StorageFuture as StoreFuture, User, UserPatch, UserRepository, }; -/// The seven repositories the services read and write. +/// The eight repositories the services read and write. #[derive(Clone)] pub struct ServiceStores { pub events: Arc, @@ -29,6 +30,9 @@ pub struct ServiceStores { pub dvm_jobs: Arc, pub notification_outbox: Arc, pub notification_delivery_log: Arc, + /// Read by the MCP door's `reports_action`; no services worker calls it, and + /// `nostream_relay`'s own `UnavailableReportRepository` is the double. + pub reports: Arc, } fn unavailable() -> StorageError { @@ -37,7 +41,7 @@ fn unavailable() -> StorageError { } } -/// The seven stores, every call reporting `NotImplemented`. +/// The eight stores, every call reporting `NotImplemented`. pub fn stores() -> ServiceStores { ServiceStores { events: Arc::new(UnavailableEventRepository), @@ -47,6 +51,7 @@ pub fn stores() -> ServiceStores { dvm_jobs: Arc::new(UnavailableDvmJobRepository), notification_outbox: Arc::new(UnavailableOutboxRepository), notification_delivery_log: Arc::new(UnavailableDeliveryLogRepository), + reports: Arc::new(nostream_relay::unavailable::UnavailableReportRepository), } } @@ -92,6 +97,10 @@ impl EventRepository for UnavailableEventRepository { Box::pin(async { Err(unavailable()) }) } + fn find_stored<'a>(&'a self, _id: &'a EventId) -> StoreFuture<'a, Option> { + Box::pin(async { Err(unavailable()) }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, _pubkey: &'a nostream_core::Pubkey, diff --git a/crates/nostream-services/tests/dvm_worker.rs b/crates/nostream-services/tests/dvm_worker.rs index 17d7cac71..94f705f89 100644 --- a/crates/nostream-services/tests/dvm_worker.rs +++ b/crates/nostream-services/tests/dvm_worker.rs @@ -97,6 +97,7 @@ fn build_all( dvm_jobs: Arc::clone(&jobs) as Arc, notification_outbox: testing::InMemoryOutboxRepository::new(), notification_delivery_log: testing::InMemoryDeliveryLogRepository::new(), + reports: nostream_relay::testing::InMemoryReportRepository::new(), }); let (hub, _receiver) = broadcast::channel(16); let mut settings = testing::settings(); diff --git a/crates/nostream-services/tests/invoice_walk.rs b/crates/nostream-services/tests/invoice_walk.rs index 7d17d191e..164c933e9 100644 --- a/crates/nostream-services/tests/invoice_walk.rs +++ b/crates/nostream-services/tests/invoice_walk.rs @@ -43,6 +43,7 @@ fn build(with_key: bool) -> Fixture { notification_outbox: Arc::clone(&outbox) as Arc, notification_delivery_log: testing::InMemoryDeliveryLogRepository::new(), + reports: nostream_relay::testing::InMemoryReportRepository::new(), }); let (hub, _receiver) = broadcast::channel(16); let mut settings = testing::settings(); diff --git a/crates/nostream-services/tests/maintenance.rs b/crates/nostream-services/tests/maintenance.rs index 512ce8d7d..fb0b327d5 100644 --- a/crates/nostream-services/tests/maintenance.rs +++ b/crates/nostream-services/tests/maintenance.rs @@ -293,6 +293,7 @@ async fn the_relay_restarted_notification_is_one_enqueue_and_obeys_its_toggle() notification_outbox: Arc::clone(&outbox) as Arc, notification_delivery_log: Arc::clone(&delivery_log) as Arc, + reports: nostream_relay::testing::InMemoryReportRepository::new(), }; // R8: the process's one row, through the same function `serve` calls. @@ -398,6 +399,7 @@ fn runner( dvm_jobs: testing::InMemoryDvmJobRepository::new(), notification_outbox: testing::InMemoryOutboxRepository::new(), notification_delivery_log: testing::InMemoryDeliveryLogRepository::new(), + reports: nostream_relay::testing::InMemoryReportRepository::new(), }; let settings = Arc::new(settings); let clock = testing::clock(1_700_000_000_000); diff --git a/crates/nostream-services/tests/notifications.rs b/crates/nostream-services/tests/notifications.rs index 2b79cacb5..eea3aed33 100644 --- a/crates/nostream-services/tests/notifications.rs +++ b/crates/nostream-services/tests/notifications.rs @@ -286,6 +286,7 @@ fn runner( as Arc, notification_delivery_log: Arc::clone(&delivery_log) as Arc, + reports: nostream_relay::testing::InMemoryReportRepository::new(), }; let settings = Arc::new(settings); let clock = testing::clock(NOW_MS); diff --git a/crates/nostream-services/tests/payments_service.rs b/crates/nostream-services/tests/payments_service.rs index 5aad29209..635069248 100644 --- a/crates/nostream-services/tests/payments_service.rs +++ b/crates/nostream-services/tests/payments_service.rs @@ -60,6 +60,7 @@ fn build(settings: nostream_config::Settings, with_key: bool) -> Fixture { notification_outbox: Arc::clone(&outbox) as Arc, notification_delivery_log: testing::InMemoryDeliveryLogRepository::new(), + reports: nostream_relay::testing::InMemoryReportRepository::new(), }); let (hub, _receiver) = broadcast::channel(16); let clock = Arc::new(TestClock::new(NOW_MS)); diff --git a/crates/nostream-storage/src/lmdb/events.rs b/crates/nostream-storage/src/lmdb/events.rs index 7bdb60f13..bb55b69e1 100644 --- a/crates/nostream-storage/src/lmdb/events.rs +++ b/crates/nostream-storage/src/lmdb/events.rs @@ -362,6 +362,18 @@ fn soft_delete( Ok(()) } +/// `EventRepository::find_stored`: one `get` on the events table — no filter pass, no gate. +pub(crate) fn find_stored( + txn: &RoTxn<'_>, + databases: &Databases, + id: &EventId, +) -> Result, StorageError> { + let Some(value) = databases.events.get(txn, id.as_bytes())? else { + return Ok(None); + }; + rows::decode_event(value).map(Some) +} + /// `delete_by_pubkey_and_ids`: a soft delete that never touches kind 62 or a deleted row. pub(crate) fn delete_by_pubkey_and_ids( txn: &mut RwTxn<'_>, diff --git a/crates/nostream-storage/src/lmdb/metadata.rs b/crates/nostream-storage/src/lmdb/metadata.rs index d2d08b3f2..66b24e618 100644 --- a/crates/nostream-storage/src/lmdb/metadata.rs +++ b/crates/nostream-storage/src/lmdb/metadata.rs @@ -740,6 +740,61 @@ pub(crate) fn report_find_actionable_targets( .collect()) } +/// `ReportRepository::set_actionable`: flips the flag on every row one report event wrote and +/// moves the three actionable indexes with it. +/// +/// `report_write` puts those indexes only when the flag is true, and nothing removes one, so a +/// row that stops being actionable would leave its keys behind: `report_find_actionable`, +/// `report_find_actionable_targets` and the NIP-56 gate walk the indexes without re-checking +/// the row. The deletion is therefore this function's work, and it is why the setter cannot be +/// an update of the value alone. The row is rewritten through [`report_write`], so the +/// re-insert is the same code that wrote the row originally. +pub(crate) fn report_set_actionable( + txn: &mut RwTxn<'_>, + databases: &Databases, + event_id: &EventId, + actionable: bool, +) -> Result { + // The walk's ids are collected before any write: the iterator holds the transaction, and + // one report event writes a handful of rows rather than a page. + let mut ids = Vec::new(); + for entry in databases + .reports_by_event_id + .prefix_iter(txn, event_id.as_bytes())? + { + let (key, _) = entry?; + ids.push(encoding::i32_from_key(&key[32..])?); + } + + let mut changed = 0; + for id in ids { + let Some(report) = report_load(txn, databases, id)? else { + continue; + }; + if report.actionable == actionable { + continue; + } + databases + .reports_actionable_by_created_at + .delete(txn, &report_created_key(&report))?; + if let Some(target) = &report.reported_event_id { + databases + .reports_actionable_event + .delete(txn, &report_event_key(&report, target))?; + } + if let Some(pubkey) = &report.reported_pubkey { + databases + .reports_actionable_pubkey + .delete(txn, &report_pubkey_key(&report, pubkey))?; + } + let mut updated = report; + updated.actionable = actionable; + report_write(txn, databases, &updated)?; + changed += 1; + } + Ok(changed) +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] diff --git a/crates/nostream-storage/src/lmdb/mod.rs b/crates/nostream-storage/src/lmdb/mod.rs index fc5e03c74..164550e76 100644 --- a/crates/nostream-storage/src/lmdb/mod.rs +++ b/crates/nostream-storage/src/lmdb/mod.rs @@ -598,6 +598,14 @@ impl EventRepository for LmdbBackend { }) } + fn find_stored<'a>(&'a self, id: &'a EventId) -> StorageFuture<'a, Option> { + Box::pin(async move { + let id = *id; + self.read(move |txn, databases| events::find_stored(txn, databases, &id)) + .await + }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, pubkey: &'a Pubkey, @@ -1117,6 +1125,20 @@ impl ReportRepository for LmdbBackend { fn find_actionable_targets<'a>(&'a self) -> StorageFuture<'a, Vec> { Box::pin(async move { self.read(metadata::report_find_actionable_targets).await }) } + + fn set_actionable<'a>( + &'a self, + event_id: &'a EventId, + actionable: bool, + ) -> StorageFuture<'a, u64> { + Box::pin(async move { + let event_id = *event_id; + self.write(move |txn, databases| { + metadata::report_set_actionable(txn, databases, &event_id, actionable) + }) + .await + }) + } } impl NotificationDeliveryLogRepository for LmdbBackend { diff --git a/crates/nostream-storage/src/postgres/events.rs b/crates/nostream-storage/src/postgres/events.rs index 112e0d169..626b20255 100644 --- a/crates/nostream-storage/src/postgres/events.rs +++ b/crates/nostream-storage/src/postgres/events.rs @@ -354,6 +354,27 @@ where }) } +/// `EventRepository::find_stored`: one exact-id select — no filter, and no NIP-56 gate. +pub(crate) async fn find_stored<'e, E>( + executor: E, + id: &EventId, +) -> Result, StorageError> +where + E: Executor<'e, Database = Postgres>, +{ + let mut args = Args::default(); + let id_slot = args.push(Arg::Bytes(id.as_bytes().to_vec())); + let sql = format!( + "SELECT {} FROM events WHERE events.event_id = {id_slot}", + sql::EVENT_COLUMNS + ); + let row = EventQuery { sql, args } + .into_query() + .fetch_optional(executor) + .await?; + row.map(|row| super::rows::event_record(&row)).transpose() +} + /// `delete_by_pubkey_and_ids`: a soft delete, never touching kind 62 or a deleted row. pub(crate) async fn delete_by_pubkey_and_ids<'e, E>( executor: E, diff --git a/crates/nostream-storage/src/postgres/metadata.rs b/crates/nostream-storage/src/postgres/metadata.rs index 9b387f5b5..44ca22e7d 100644 --- a/crates/nostream-storage/src/postgres/metadata.rs +++ b/crates/nostream-storage/src/postgres/metadata.rs @@ -605,3 +605,29 @@ where }) .collect() } + +/// `ReportRepository::set_actionable`: one statement over every row of one report event, and +/// the partial indexes maintain themselves. The `actionable <> $2` predicate is the "already +/// holds" rule: such a row is not written and the count does not name it. +pub(crate) async fn report_set_actionable<'e, E>( + executor: E, + event_id: &EventId, + actionable: bool, +) -> Result +where + E: Executor<'e, Database = Postgres>, +{ + let mut args = Args::default(); + let event_slot = args.push(Arg::Bytes(event_id.as_bytes().to_vec())); + let actionable_slot = args.push(Arg::Bool(actionable)); + let sql = format!( + "UPDATE reports SET actionable = {actionable_slot} WHERE event_id = {event_slot} \ + AND actionable <> {actionable_slot}" + ); + + Ok(EventQuery { sql, args } + .into_query() + .execute(executor) + .await? + .rows_affected()) +} diff --git a/crates/nostream-storage/src/postgres/repository.rs b/crates/nostream-storage/src/postgres/repository.rs index 4996887b7..c68da46dd 100644 --- a/crates/nostream-storage/src/postgres/repository.rs +++ b/crates/nostream-storage/src/postgres/repository.rs @@ -61,6 +61,10 @@ impl EventRepository for PostgresBackend { }) } + fn find_stored<'a>(&'a self, id: &'a EventId) -> StorageFuture<'a, Option> { + Box::pin(async move { events::find_stored(&self.master, id).await }) + } + fn delete_by_pubkey_and_ids<'a>( &'a self, pubkey: &'a Pubkey, @@ -367,6 +371,16 @@ impl ReportRepository for PostgresBackend { fn find_actionable_targets<'a>(&'a self) -> StorageFuture<'a, Vec> { Box::pin(async move { metadata::report_find_actionable_targets(&self.master).await }) } + + fn set_actionable<'a>( + &'a self, + event_id: &'a EventId, + actionable: bool, + ) -> StorageFuture<'a, u64> { + Box::pin(async move { + metadata::report_set_actionable(&self.master, event_id, actionable).await + }) + } } impl NotificationDeliveryLogRepository for PostgresBackend { diff --git a/crates/nostream-storage/src/repositories.rs b/crates/nostream-storage/src/repositories.rs index 6546cc5bb..e7894f8a0 100644 --- a/crates/nostream-storage/src/repositories.rs +++ b/crates/nostream-storage/src/repositories.rs @@ -650,7 +650,21 @@ pub trait EventRepository: Send + Sync { filter: &'a nostream_core::Filter, ) -> StorageFuture<'a, QueryStream<'a, ReconciliationItem>>; + /// Loads one row by exact id **without the NIP-56 gate**, deleted or not, hidden or not. + /// + /// The gate has always been a *read's*: `find_by_filters` drops a row an actionable report + /// names (`lmdb/events.rs`'s `reported`), which is what a REQ must not see. A delete is not a + /// read of that kind — it must be able to delete what a moderator just hid — so this one + /// exact-id lookup skips the gate, and **only the delete path may call it**. Every reader + /// that answers a client keeps the gated path. + fn find_stored<'a>(&'a self, id: &'a EventId) -> StorageFuture<'a, Option>; + /// Soft-deletes the given ids of one pubkey, returning the count. + /// + /// Two conditions are the store's own, implemented by both backends and not by a caller: + /// kind 62 is never touched (`lmdb/events.rs:391-393`, `postgres/events.rs:393-394`), and a + /// row already carrying `deleted_at` is not deleted again. A row either skip answers is not + /// counted. fn delete_by_pubkey_and_ids<'a>( &'a self, pubkey: &'a Pubkey, @@ -929,6 +943,19 @@ pub trait ReportRepository: Send + Sync { /// Loads every distinct actionable report target. fn find_actionable_targets<'a>(&'a self) -> StorageFuture<'a, Vec>; + + /// Sets `actionable` on every report row whose source event is `event_id`, returning the + /// rows whose value changed. One transaction: a reader sees the old value or the new one. + /// + /// The LMDB arm moves the three `reports_actionable_*` entries with the flag, because + /// `find_actionable`, `find_actionable_targets` and the NIP-56 gate read those indexes + /// without re-checking the row. A row whose value already equals the argument is not + /// written and is not counted. + fn set_actionable<'a>( + &'a self, + event_id: &'a EventId, + actionable: bool, + ) -> StorageFuture<'a, u64>; } /// Notification delivery-log storage (`src/@types/repositories.ts` diff --git a/crates/nostream-storage/tests/parity.rs b/crates/nostream-storage/tests/parity.rs index 805364a6c..390d446c0 100644 --- a/crates/nostream-storage/tests/parity.rs +++ b/crates/nostream-storage/tests/parity.rs @@ -311,3 +311,205 @@ async fn the_same_replay_over_tls_matches_the_capture_and_the_plaintext_run() { // Read by scripts/storage-parity.sh with --nocapture as proof the assertions ran. println!("TLS_PARITY_COMPLETE"); } + +/// The Postgres arm of the report setter, on a scratch database of its own: one `UPDATE` flips +/// every row of the report event, and the partial indexes the NIP-56 gate reads maintain +/// themselves, so the reported event returns to `find_by_filters` at once. +/// +/// The LMDB arm's four cases (`tests/parity_lmdb.rs`) are the ones `cargo test --workspace` runs; +/// this one needs the CI database, like the two replays above. +#[tokio::test] +#[ignore = "needs PARITY_ADMIN_URL; scripts/storage-parity.sh sets it"] +async fn set_actionable_flips_the_column_and_the_gate() { + use nostream_core::{EventId, Filter, Pubkey}; + use nostream_storage::repositories::{NewReport, ReportRepository, ReportType}; + + let admin_url = admin_url(); + let database = "nostream_parity_set_actionable"; + let admin = PgPool::connect(&admin_url) + .await + .expect("the administrative database is reachable"); + admin + .execute(sqlx::AssertSqlSafe(format!( + "DROP DATABASE IF EXISTS {database} WITH (FORCE)" + ))) + .await + .expect("the scratch database drops"); + admin + .execute(sqlx::AssertSqlSafe(format!("CREATE DATABASE {database}"))) + .await + .expect("the scratch database is created"); + drop(admin); + + let fixture = fixture(); + let backend = PostgresBackend::connect(&with_database(&admin_url, database)) + .await + .expect("the scratch database is reachable") + .with_settings(Arc::new(settings_from_fixture(&fixture))); + backend.migrate().await.expect("the schema migrates"); + + let record = common::event_record(&fixture["corpus"][0]); + EventRepository::create(&backend, &record) + .await + .expect("the event stores"); + let report = ReportRepository::create( + &backend, + &NewReport { + event_id: EventId::from_byte_array([70; 32]), + reporter_pubkey: Pubkey::from_byte_array([71; 32]), + reported_pubkey: Some(record.event.pubkey), + reported_event_id: Some(record.event.id), + report_type: ReportType::Spam, + weight: 1.0, + actionable: true, + }, + ) + .await + .expect("the report stores"); + + let filter = Filter { + ids: Some(vec![record.event.id.to_string()]), + ..Filter::default() + }; + assert!( + page_of_pg(&backend, std::slice::from_ref(&filter)) + .await + .is_empty(), + "the gate withholds the reported event" + ); + + assert_eq!( + backend + .set_actionable(&report.event_id, false) + .await + .unwrap(), + 1 + ); + assert!(backend.find_actionable(10).await.unwrap().is_empty()); + assert!(backend.find_actionable_targets().await.unwrap().is_empty()); + assert_eq!( + page_of_pg(&backend, std::slice::from_ref(&filter)) + .await + .len(), + 1, + "the event returns once no actionable report names it" + ); +} + +/// `find_stored` answers a row the NIP-56 gate withholds, and answers it after the soft delete +/// with the store's own timestamp — the read `delete_event` resolves its row through. +/// +/// The arm is one `SELECT ... WHERE event_id = $1`; this case is what proves it exists and CI runs +/// it, the same rule the setter's case follows. +#[tokio::test] +#[ignore = "needs PARITY_ADMIN_URL; scripts/storage-parity.sh sets it"] +async fn find_stored_answers_a_hidden_and_a_deleted_row() { + use nostream_core::{EventId, Filter, Pubkey}; + use nostream_storage::repositories::{NewReport, ReportRepository, ReportType}; + + let admin_url = admin_url(); + let database = "nostream_parity_find_stored"; + let admin = PgPool::connect(&admin_url) + .await + .expect("the administrative database is reachable"); + admin + .execute(sqlx::AssertSqlSafe(format!( + "DROP DATABASE IF EXISTS {database} WITH (FORCE)" + ))) + .await + .expect("the scratch database drops"); + admin + .execute(sqlx::AssertSqlSafe(format!("CREATE DATABASE {database}"))) + .await + .expect("the scratch database is created"); + drop(admin); + + let fixture = fixture(); + let backend = PostgresBackend::connect(&with_database(&admin_url, database)) + .await + .expect("the scratch database is reachable") + .with_settings(Arc::new(settings_from_fixture(&fixture))); + backend.migrate().await.expect("the schema migrates"); + + let record = common::event_record(&fixture["corpus"][0]); + EventRepository::create(&backend, &record) + .await + .expect("the event stores"); + let filter = Filter { + ids: Some(vec![record.event.id.to_string()]), + ..Filter::default() + }; + assert!( + EventRepository::find_stored(&backend, &record.event.id) + .await + .unwrap() + .is_some(), + "a live row answers" + ); + assert!( + EventRepository::find_stored(&backend, &EventId::from_byte_array([72; 32])) + .await + .unwrap() + .is_none(), + "an id nothing carries answers none" + ); + + ReportRepository::create( + &backend, + &NewReport { + event_id: EventId::from_byte_array([73; 32]), + reporter_pubkey: Pubkey::from_byte_array([74; 32]), + reported_pubkey: Some(record.event.pubkey), + reported_event_id: Some(record.event.id), + report_type: ReportType::Spam, + weight: 1.0, + actionable: true, + }, + ) + .await + .expect("the report stores"); + assert!( + page_of_pg(&backend, std::slice::from_ref(&filter)) + .await + .is_empty(), + "the gate withholds the row the next assertion reaches" + ); + assert!( + EventRepository::find_stored(&backend, &record.event.id) + .await + .unwrap() + .is_some(), + "the ungated read answers a hidden row" + ); + + assert_eq!( + EventRepository::delete_by_pubkey_and_ids( + &backend, + &record.event.pubkey, + &[record.event.id] + ) + .await + .unwrap(), + 1 + ); + let deleted = EventRepository::find_stored(&backend, &record.event.id) + .await + .unwrap() + .expect("the ungated read answers a deleted row"); + assert!( + deleted.deleted_at.is_some(), + "and it carries the store's own timestamp" + ); +} + +/// One Postgres filter read, drained into its rows. +async fn page_of_pg( + backend: &PostgresBackend, + filters: &[nostream_core::Filter], +) -> Vec { + nostream_storage::repositories::collect_records( + backend.find_by_filters(filters).await.expect("the page"), + ) + .await + .expect("the stream") +} diff --git a/crates/nostream-storage/tests/parity_lmdb.rs b/crates/nostream-storage/tests/parity_lmdb.rs index f900766ca..406a16ac0 100644 --- a/crates/nostream-storage/tests/parity_lmdb.rs +++ b/crates/nostream-storage/tests/parity_lmdb.rs @@ -2392,3 +2392,227 @@ async fn an_index_from_an_older_tokenizer_is_rebuilt_on_open() { vec![records[1].event.id] ); } + +// --------------------------------------------------------------------------------------- +// The report setter: the row's flag and the three indexes `report_write` fills. +// --------------------------------------------------------------------------------------- + +/// A filter selecting one stored event by id. +fn by_id(record: &EventRecord) -> Filter { + Filter { + ids: Some(vec![record.event.id.to_string()]), + ..Filter::default() + } +} + +#[tokio::test] +async fn find_stored_answers_a_hidden_and_a_deleted_row() { + use nostream_storage::repositories::ReportRepository; + + let (_directory, backend) = open_store().await; + let record = event(56, 1, 1_700_000_300); + EventRepository::create(&backend, &record) + .await + .expect("the event stores"); + + assert!( + EventRepository::find_stored(&backend, &record.event.id) + .await + .unwrap() + .is_some(), + "a live row answers" + ); + assert!( + EventRepository::find_stored(&backend, &EventId::from_byte_array([57; 32])) + .await + .unwrap() + .is_none(), + "an id nothing carries answers none" + ); + + ReportRepository::create( + &backend, + &NewReport { + event_id: EventId::from_byte_array([58; 32]), + reporter_pubkey: Pubkey::from_byte_array([59; 32]), + reported_pubkey: Some(record.event.pubkey), + reported_event_id: Some(record.event.id), + report_type: ReportType::Spam, + weight: 1.0, + actionable: true, + }, + ) + .await + .expect("the report stores"); + assert!( + rows_of(&backend, &by_id(&record)).await.is_empty(), + "the gate withholds the row the next assertion reaches" + ); + let hidden = EventRepository::find_stored(&backend, &record.event.id) + .await + .unwrap() + .expect("the ungated read answers a hidden row"); + assert_eq!(hidden.event.id, record.event.id); + + assert_eq!( + EventRepository::delete_by_pubkey_and_ids( + &backend, + &record.event.pubkey, + &[record.event.id] + ) + .await + .unwrap(), + 1 + ); + let deleted = EventRepository::find_stored(&backend, &record.event.id) + .await + .unwrap() + .expect("the ungated read answers a deleted row"); + assert!( + deleted.deleted_at.is_some(), + "and it carries the store's own timestamp" + ); +} + +#[tokio::test] +async fn set_actionable_false_clears_every_index_and_the_gate() { + use nostream_storage::repositories::ReportRepository; + + let (_directory, backend) = open_store().await; + let record = event(51, 1, 1_700_000_000); + EventRepository::create(&backend, &record) + .await + .expect("the event stores"); + let report = ReportRepository::create( + &backend, + &NewReport { + event_id: EventId::from_byte_array([52; 32]), + reporter_pubkey: Pubkey::from_byte_array([53; 32]), + reported_pubkey: Some(record.event.pubkey), + reported_event_id: Some(record.event.id), + report_type: ReportType::Spam, + weight: 1.0, + actionable: true, + }, + ) + .await + .expect("the report stores"); + + assert!( + rows_of(&backend, &by_id(&record)).await.is_empty(), + "the gate withholds the reported event" + ); + assert_eq!( + backend + .set_actionable(&report.event_id, false) + .await + .unwrap(), + 1 + ); + assert!(backend.find_actionable(10).await.unwrap().is_empty()); + assert!(backend.find_actionable_targets().await.unwrap().is_empty()); + assert_eq!( + rows_of(&backend, &by_id(&record)).await.len(), + 1, + "the event returns once no actionable report names it" + ); +} + +#[tokio::test] +async fn set_actionable_true_puts_every_row_of_one_report_back() { + use nostream_storage::repositories::ReportRepository; + + let (_directory, backend) = open_store().await; + let named_by_pubkey = event(54, 1, 1_700_000_100); + let named_by_id = event(55, 1, 1_700_000_200); + EventRepository::create_many(&backend, &[named_by_pubkey.clone(), named_by_id.clone()]) + .await + .expect("the events store"); + let report_event = EventId::from_byte_array([56; 32]); + ReportRepository::create_many( + &backend, + &[ + NewReport { + event_id: report_event, + reporter_pubkey: Pubkey::from_byte_array([57; 32]), + reported_pubkey: Some(named_by_pubkey.event.pubkey), + reported_event_id: None, + report_type: ReportType::Spam, + weight: 1.0, + actionable: false, + }, + NewReport { + event_id: report_event, + reporter_pubkey: Pubkey::from_byte_array([57; 32]), + reported_pubkey: None, + reported_event_id: Some(named_by_id.event.id), + report_type: ReportType::Spam, + weight: 1.0, + actionable: false, + }, + ], + ) + .await + .expect("the report rows store"); + + assert_eq!( + backend.set_actionable(&report_event, true).await.unwrap(), + 2 + ); + let rows = backend.find_by_event_id(&report_event).await.unwrap(); + assert_eq!(rows.len(), 2); + assert!(rows.iter().all(|row| row.actionable)); + let mut targets = backend.find_actionable_targets().await.unwrap(); + targets.sort_by_key(|left| left.reported_pubkey); + assert_eq!( + targets.len(), + 2, + "each target is named once, by the deduplicating walk" + ); + assert!(rows_of(&backend, &by_id(&named_by_pubkey)).await.is_empty()); + assert!(rows_of(&backend, &by_id(&named_by_id)).await.is_empty()); +} + +#[tokio::test] +async fn set_actionable_answers_zero_for_a_value_that_already_holds() { + use nostream_storage::repositories::ReportRepository; + + let (_directory, backend) = open_store().await; + let report_event = EventId::from_byte_array([58; 32]); + let report = ReportRepository::create( + &backend, + &NewReport { + event_id: report_event, + reporter_pubkey: Pubkey::from_byte_array([59; 32]), + reported_pubkey: Some(Pubkey::from_byte_array([60; 32])), + reported_event_id: None, + report_type: ReportType::Spam, + weight: 1.0, + actionable: true, + }, + ) + .await + .expect("the report stores"); + + assert_eq!( + backend.set_actionable(&report_event, true).await.unwrap(), + 0 + ); + let rows = backend.find_by_event_id(&report_event).await.unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0], report, "the row is unchanged, its id included"); +} + +#[tokio::test] +async fn set_actionable_answers_zero_for_an_unknown_event() { + use nostream_storage::repositories::ReportRepository; + + let (_directory, backend) = open_store().await; + assert_eq!( + backend + .set_actionable(&EventId::from_byte_array([61; 32]), true) + .await + .unwrap(), + 0 + ); +} diff --git a/crates/nostream-storage/tests/storage.rs b/crates/nostream-storage/tests/storage.rs index 22712ffcb..1e7bc2cc2 100644 --- a/crates/nostream-storage/tests/storage.rs +++ b/crates/nostream-storage/tests/storage.rs @@ -97,6 +97,10 @@ async fn the_repository_traits_are_dyn_compatible() { unsupported("noop::events::find_reconciliation_items") } + fn find_stored<'a>(&'a self, _id: &'a EventId) -> StorageFuture<'a, Option> { + unsupported("noop::events::find_stored") + } + fn delete_by_pubkey_and_ids<'a>( &'a self, _pubkey: &'a Pubkey, @@ -360,6 +364,14 @@ async fn the_repository_traits_are_dyn_compatible() { fn find_actionable_targets<'a>(&'a self) -> StorageFuture<'a, Vec> { unsupported("noop::reports::find_actionable_targets") } + + fn set_actionable<'a>( + &'a self, + _event_id: &'a EventId, + _actionable: bool, + ) -> StorageFuture<'a, u64> { + unsupported("noop::reports::set_actionable") + } } impl NotificationDeliveryLogRepository for Noop { diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index 4746e34a0..6d0ec7e66 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -51,7 +51,7 @@ struct Cli { /// /// The document is `{"scopes": ["write"]}`; a document with no scopes grants the read tools /// (`settings_get`, `list_events`, `get_event`, `relay_status`), and the "write" scope adds - /// `settings_set`. + /// `settings_set`, `delete_event` and `reports_action`. /// An unknown scope refuses to start, naming it. The mode also needs `admin.enabled: true` in /// the settings. /// diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 62d8b0f9b..f9e6db296 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -11,6 +11,7 @@ //! | `the_mode_binds_no_socket` | the dialogue completes while the port the flag names is held by the test | //! | `the_process_exits_zero_on_stdin_eof` | closing stdin ends the process with `0` | //! | `the_store_backed_tools_report_the_unwired_store` | `list_events` answers the store's own `NotImplemented` message, not an empty list | +//! | `the_write_tools_report_the_unwired_store` | both write tools reach the unwired store and answer its message, rather than a protocol error | //! | `the_help_text_names_the_credential` | `--help` names the two flags, the document's shape and scopes, the file rule and the retired variable | //! | `a_console_session_token_in_the_environment_refuses_to_start` | the retired variable is named rather than ignored, even when it carries a token the console would accept | //! | `a_group_readable_token_file_refuses_to_start` | mode 0644 fails the start, and the message names both modes | @@ -488,7 +489,7 @@ async fn the_mode_binds_no_socket() { assert_eq!( listed["result"]["tools"].as_array().map(Vec::len), - Some(5), + Some(7), "{listed}" ); assert!(outcome.status.success(), "{}", outcome.stderr); @@ -522,6 +523,38 @@ async fn the_store_backed_tools_report_the_unwired_store() { assert!(outcome.status.success(), "{}", outcome.stderr); } +/// The two write tools exist in the real binary and reach the daemon's unwired bundle: their +/// answer is the store's own message, not the router's `tool not found` that was true before +/// this slice. +#[tokio::test] +async fn the_write_tools_report_the_unwired_store() { + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &[]); + daemon.initialize().await; + let deleted = daemon + .call("delete_event", json!({ "id": "ab".repeat(32) })) + .await; + let acted = daemon + .call( + "reports_action", + json!({ "id": "cd".repeat(32), "action": "hide" }), + ) + .await; + let outcome = daemon.finish().await; + + for (tool, response) in [("delete_event", &deleted), ("reports_action", &acted)] { + assert_eq!(response["result"]["isError"], true, "{tool}: {response}"); + let text = response["result"]["content"][0]["text"] + .as_str() + .unwrap_or_default(); + assert!( + text.contains("not implemented in Phase 1 (job 005): storage::backend::wiring"), + "{tool}: {text}" + ); + } + assert!(outcome.status.success(), "{}", outcome.stderr); +} + #[tokio::test] async fn the_help_text_names_the_credential() { let output = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")) @@ -549,6 +582,8 @@ async fn the_help_text_names_the_credential() { "write", "admin.enabled", "relay_status", + "delete_event", + "reports_action", ] { assert!(help.contains(needle), "the help names `{needle}`: {help}"); } @@ -717,7 +752,7 @@ async fn an_inherited_descriptor_authenticates() { assert_eq!( listed["result"]["tools"].as_array().map(Vec::len), - Some(5), + Some(7), "{listed}" ); assert_eq!(read["result"]["isError"], false, "{read}"); diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 9a9cd373a..911a0230e 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -118,8 +118,9 @@ Nostr` branch exists; a request without a valid session is always The daemon already builds `Arc` for the relay and the services (`crates/nostreamd/src/main.rs`); the admin surface is handed the same `Arc` rather than a -second bundle. The event store, the NIP-05 verifications, the notification outbox and the -delivery log are the four it reads, and every one of them is a field of that struct. The +second bundle. The event store, the report store, the NIP-05 verifications, the notification +outbox and the delivery log are the five it reads (the report store since ADR 0017 D3), and every +one of them is a field of that struct. The oracle test builds the bundle over `LmdbBackend::open(tempdir)`, which implements every trait the bundle needs (`crates/nostream-storage/src/lmdb/mod.rs:481,664,734,805,1027,1074`). @@ -280,8 +281,8 @@ backend, whose query is a real await, that the shape is for. The MCP server writes its calls to the same `/admin-audit.jsonl` (D9), one line per executed call, and it extends the recorded action vocabulary by **one name per registered tool** -rather than reusing one. Four names landed with the first slice; `relay_status` adds the fifth, and -each later slice adds its own: +rather than reusing one. Seven names have landed: four with the first slice, `relay_status` with +the second, and `delete_event` and `reports_action` with the third; each later slice adds its own: | action | written by | |---|---| @@ -290,6 +291,8 @@ each later slice adds its own: | `mcp.list_events` | a dispatched `list_events` | | `mcp.get_event` | a dispatched `get_event` | | `mcp.relay_status` | a dispatched `relay_status` (ADR 0016) | +| `mcp.delete_event` | a dispatched `delete_event` (ADR 0017) | +| `mcp.reports_action` | a dispatched `reports_action` (ADR 0017) | **These extend the capture's nine names; they do not replace them.** The capture's vocabulary is a closed nine-name union (`src/@types/admin-audit.ts:1-10`), and the rewrite's writer takes @@ -306,8 +309,9 @@ into a field the page does not show. The cost is one more line in this record; t costs the column its meaning. **What each line carries.** `detail` holds `{"tool": ""}`, plus `{"paths": [...]}` for -`settings_set` (the paths requested, never a value), and `remoteAddress` is omitted because a -stdio caller has no address (`state.rs:509-525`). The line is appended at dispatch, before the +`settings_set` (the paths requested, never a value); `delete_event` and `reports_action` carry +`{"tool": …}` and nothing else, so neither an id nor an action enters the file, and +`remoteAddress` is omitted because a stdio caller has no address (`state.rs:509-525`). The line is appended at dispatch, before the tool's work, so the file's order is the dispatch order: `mcp.settings_set` precedes the `settings.updated` line the shared write path then appends, and a call the credential refuses appends nothing at all — matching `admin_auth_middleware.rs:52-63`, which logs a warning and @@ -341,7 +345,9 @@ has one row in `crates/nostream-mcp`'s `TOOLS` table: its name, the check that s router can deserialise a call's arguments (R9), and the scope the call needs (R28). The dispatch path looks a name up there instead of defaulting, and `every_registered_tool_has_a_table_row` reads the router's own list, so no call can execute unaudited and none can execute ungated. The -scope column names the read tools explicitly and keeps `settings_set` as the only `write`; a name +scope column names each tool's requirement — `read` for the read tools, `write` for +`settings_set` and for `delete_event` and `reports_action` (ADR 0017 D5), so the column is the +gate's whole answer rather than a default with one exception; a name the table does not carry is **refused there**, with the router's own `-32602 tool not found`, before the scope decision and before any line is written — so a tool that arrived without its row is unreachable rather than unaudited, and the name an audit line records is always one of the diff --git a/docs/rewrite/decisions/0017-report-and-event-writes.md b/docs/rewrite/decisions/0017-report-and-event-writes.md new file mode 100644 index 000000000..aa70e794a --- /dev/null +++ b/docs/rewrite/decisions/0017-report-and-event-writes.md @@ -0,0 +1,190 @@ +# ADR 0017: The two event and report writes, and the report store at the door + +- **Status:** accepted (job 036, Phase 2) +- **Deciders:** the rewrite team, on the operator's steer recorded in #1183 and this job's spec +- **Date:** 2026-11-21 + +## Context + +Slice 3 of #1183 adds two MCP tools, `delete_event` and `reports_action`, and the repository +plumbing both need. Three facts at the base commit shaped it. + +**The tree has exactly one single-event delete, and it is soft.** `EventRepository`'s +`delete_by_pubkey_and_ids` takes the pubkey **as well as** the ids, so a caller that has not read +the row cannot call it truthfully; both backends skip a row whose pubkey does not match. Its rules +are the store's, implemented twice and nowhere else: the row keeps its value with `deleted_at` +set, kind 62 is never touched, an already-deleted row is not re-deleted, and the return value is +the count of rows flipped. The relay compensates on its read path only (a subscription drops a row +whose `deleted_at` is set); the two MCP event tools read through `collect_records` and +`collect_page`, which do not, so a soft delete leaves the row visible to `get_event` and +`list_events`. + +**`Report.actionable` is a create-time property that nothing ever changes.** The report strategy +writes it from `is_trusted_moderator`, one row per extracted target, so one report event with +three targets writes three rows with the same `event_id`. LMDB denormalises the flag into three +indexes at write time and no function removes one; the NIP-56 gate reads two of them per query. +The relay's `HiddenContentCache` is a mirror of actionable **targets** — a latency optimisation for +live fan-out, refreshed wholesale every 30 s — and not the source of truth. + +**The door cannot see the report store.** `AdminState` carries `Arc`, and that +bundle's seven repositories did not include reports; the relay has its own `Stores` for six, and +the MCP mode composes its own state in a process of its own. + +## Decisions + +### D1 — `delete_event` is the store's own soft delete behind one ungated read, and its payload says what that means + +The tool resolves the row through **one new `EventRepository` method**, `find_stored(&EventId)` — +an exact-id read that returns the row whether or not it is deleted and **whether or not an +actionable report hides it**. LMDB answers it with one `get` on the events table, Postgres with one +`SELECT ... WHERE event_id = $1`, and the eight other implementors carry it — the relay's and the +services' in-memory and unavailable doubles, the admin test's `SlowEventRepository`, the door's +`VanishingRepository` and `ZeroCountDeleter`, and the storage test's `Noop` — every one of them +truthfully: a double that answered `None` for a row would redden the case that relies on it, and +the hidden-event case runs over the real backend rather than a double. +It exists because the gate has always been a read's (`lmdb/events.rs:1968-1978`'s `reported`, one +predicate of a filter's row walk, and `postgres/sql.rs`'s equivalent): resolving the row +through `get_event`'s gated read made `reports_action hide` followed by `delete_event` answer +`not_found` and delete nothing, which made the two tools this slice ships incoherent with each +other. The method is `pub` on a trait every consumer holds, so "only the delete path may call it" +is not left as a comment: `.find_stored(` is an acceptance leg that reads exactly two lines across +`crates/`, both the handler's, so a third caller using the method-call form fails the criterion. The +leg is a deterrent, not a proof — a fully qualified `EventRepository::find_stored` spells past it, +and the parity cases themselves use that form — which is why the doc comment states the rule as +well; the commit that adds a parity caller is the place to see the leg is a spelling's. + +The argument is the event's hex id, and a prefix shorter than 64 characters is refused with the +same `Criterion` error `reports_action` gives rather than widened to whatever the store's range +would match — the `EventId` the read takes is an exact id, so answering `not_found` for characters +the tool never looked up would be the one lie this tool must not tell. + +The call is `delete_by_pubkey_and_ids` with **the row's own** pubkey and id, then one read-back, +and the answer is `{outcome, event}` with one of four literals: `deleted`, `already_deleted`, +`not_deleteable` (kind 62), `not_found`. The outcome is decided by the row **as it stands after** +the call, not by the read before it: a pre-read is stale under two deletes in flight, and the +second call would answer `not_deleteable` for a row that was merely already deleted. `count > 0` +stays authoritative; the post-read only explains a zero, and kind 62 is the store's only remaining +skip once the pubkey is the row's own. + +The event leaves REQ and COUNT and keeps its row: `get_event` and `list_events` still return it +with `deleted_at` set — **unless an actionable report hides it**, in which case it stays hidden +until the report is allowed, and deleting it does not change that. Both halves are stated in the +tool's description rather than left for an operator to discover, and the read-back makes the +timestamp the store's own wall-clock value instead of a guess. + +**Cost:** a soft delete is not an erasure: the row and its content stay in the store, and an +operator who needs the bytes gone still needs the retention path or `clean-db`. The disclosure is +prose, so a client that reads only the schema learns nothing about it; the cheap alternative — a +fifth outcome — was rejected because the store's answer is already one of four. Three store round +trips per call (read, delete, read-back), all on the answering process's own store. The ungated +read is a second way to reach a row, which is why it is one method with one caller and a criterion +guarding the call count rather than a flag on the read path. + +### D2 — `reports_action` acts on the report's own event id and flips one row's flag per row + +The argument is the report's **own** kind-1984 event id, exactly 64 hex characters — the +`find_by_event_id` argument, no new reader — and `hide` means `Report.actionable = true`, `allow` +means `false`. One call flips every row the report event wrote, returns the rows sorted by `id` +and `changed`, the rows whose value moved. The sort is the handler's and the contract's: LMDB's +prefix walk happens to answer ascending by `report_id`, and Postgres does not order, so relying on +either would be relying on an accident — which is why the branch's report seam reverses what the +store answers and the case goes red when the sort is removed. An id with no rows +answers `{"reports": [], "changed": 0}` — a result, as an unknown id is for `get_event`. An +unknown action never reaches the handler: the closed set is the arguments type's deserialiser and +the schema's `enum`. + +**The action is one row's flag, not a recomputation across reports.** A target named by two +actionable reports stays hidden while the other remains actionable — which is what the flag means +and what `find_actionable_targets`' dedup already implements. Discovery is stated, not invented: a +caller finds a report event with `list_events {"kinds": [1984]}` and acts on each row's own id, +and `reports_list` stays out of this slice and unowned. + +**Cost:** a caller cannot act on a report whose kind-1984 event was never stored, because the +reports table is keyed by that id and reaching rows another way would need a reader no surface +has. Recomputing a target's actionability across all its reports would change +`find_actionable_targets`' contract; the flag's per-row meaning is the cheaper and already-written +rule. + +### D3 — The report store reaches the door as a `reports` field on `ServiceStores` + +`ServiceStores` gains `pub reports: Arc`, and the door reads it as +`self.state.stores().reports`. Ten construction sites each name one value: `unavailable::stores()` +reuses `nostream_relay`'s `UnavailableReportRepository` (the dependency already exists), the admin +and MCP fixtures alias the `LmdbBackend` they already hold, and the services' tests and +`testing::context` use `nostream_relay::testing::InMemoryReportRepository`. + +The alternative was an `AdminState` field, which is one field, one accessor and three +`AdminStateConfig` sites **plus** a new `compose` parameter with two callers — and it would put a +second report repository in the daemon's process beside the relay's own. The bundle is the tree's +existing answer to "the relay and services share repositories"; the console not reading the field +is the cost, paid once. + +**The LMDB setter removes the three `reports_actionable_*` entries.** They are written by +`report_write` only when the flag is true, and nothing removed one; `find_actionable`, +`find_actionable_targets` and the gate read the indexes without re-checking the row, so a flip +that wrote only the value would leave every index stale. The setter deletes the row's keys, +rewrites the value with the new flag, and re-inserts the keys through `report_write` when the new +value is true — one write transaction, so a reader sees the old value or the new one. Postgres +needs one `UPDATE … WHERE event_id = $1 AND actionable <> $2` and no migration: the partial +indexes maintain themselves. + +**Cost:** eight repositories in a bundle seven services call, one of which no services worker +touches; and the `InMemoryReportRepository` answers `Ok(0)` rather than modelling the setter, +because a double that modelled rows would have to model the three indexes too — a second +implementation of the thing under test, reached by no relay case. The double records the writes it +is given and answers every read empty, so `Ok(0)` is the count it can honestly produce rather than +a suppressed index constraint; a case that needs rows to move, like the ordering case, reads +through the door's own report seam instead. + +### D4 — The hidden-content cache needs no work + +The cache holds report **targets**, never events, and it is read only on live dispatch. A write to +`Report.actionable` needs no push from the door for three separate reasons. Every read answers +from the store per query on both backends, so a flip is in force for the very next +REQ/COUNT/`list_events` call, with no cache in that path. The live path converges by itself: +`refresh` re-reads `find_actionable_targets` every 30 s and `replace`s the snapshot wholesale, +which removes a target as well as adds one. And the door **cannot** reach the cache: it lives in +the relay process, `AdminState` holds no relay handle, and the stdio mode hosts no relay; the only +cross-process artifact is one-way (ADR 0016). + +A delete leaves nothing in the cache to clear either: the mirror is keyed on report targets and +the delete writes no report row, so an event that is both deleted and a report target stays in the +mirror for exactly as long as its report stays actionable — the correct state, not a stale one. + +**Cost:** the one consequence is disclosure, not mechanism — every new REQ reflects a flip at +once, and already-connected subscriptions see it at the relay's next refresh, up to 30 s. It is +said in the tool's description and here, and no test can reach a second process's memory. + +### D5 — The audit vocabulary gains two names, and their `detail` is the tool and nothing else + +`mcp.delete_event` and `mcp.reports_action` join the per-tool actions, composed by `audit_action` +from the `TOOL_*` constants, and both rows in the dispatch table need `Requires::Write`. Their +`detail` is `{"tool": …}` — no id, no action — because passing either would let a caller's own +text shape a record; `settings_set` passes the requested paths only because the paths are the +request itself. The line is written at dispatch, before the handler, so a refused id still leaves +its `mcp.reports_action` line and an argument the schema refuses leaves none. ADR 0014's table is +extended with both names. + +**Cost:** an operator reading the file cannot tell which event was deleted or which report was +acted on; the correlation is by time and by the caller's own record. That is the deliberate +direction: the file is a record of calls, and its fields are the table's, not the caller's. + +### D6 — The absent-name example moves to `user_admin` + +Two cases are right today only because `delete_event` is the standing example of a tool that does +not exist (`an_unknown_tool_is_a_protocol_error` and `an_unregistered_tool_is_refused_before_the_scopes`), +and one assertion passes afterwards for the wrong reason if it is left alone +(`required_scope("delete_event")`). All three move to `user_admin`, slice 4's first tool, which no +slice has landed, and test files name tools through the exported `TOOL_*` constants so no literal +stands in for a registered name. + +**Cost:** the next slice that lands `user_admin` must move the example again, and the criterion is +a grep rather than a compile error, so the mistake is found by a case rather than by the type +checker. + +**And the grep is over `.rs` sources only.** Its pattern is an absolute absence of the literal +`"delete_event"` in the test sources, while the snapshot fixture under the same directory must +carry a `"name": "delete_event"` entry — data, not a case. A pattern that read the fixture as a +case would make the snapshot criterion and this one unsatisfiable together, so the criterion names +`--include=*.rs` and says why; the base reading is unchanged (three lines at `443cb985`, all in +`.rs` files).