Files
noteguard/src/main.rs
T
William CasarinandClaude Opus 4.8 4265d3a019 nscript: experimental wasm note filter, on both the write and read paths
Add an experimental `nscript` filter that runs a user-supplied WASM guest,
behind the `nscript` cargo feature (wasmtime), on both the write path (should
this note be stored) and the read path (should this note be delivered to this
subscriber). This is the experimental part of the plugin work — the readPolicy
trait, engine and throttles in the preceding commits stand on their own without
it, and a build without the feature skips an `nscript` pipeline entry (fail
open) rather than failing.

The ABI is an accessor interface over an opaque note handle: the guest never
parses a note buffer, it calls imported `note_*` host functions
(note_pubkey/id/kind/created_at/content, note_targets_owner, is_following, log)
to read fields. The note's byte format is thus a host implementation detail —
today backed by the serde Note; later an ndb_note with an optional zero-copy raw
fast path. Owner-relative context (the scoped npub and its follows) lives on the
host so guests stay reusable, owner-agnostic logic.

Guests are bounded by wasm fuel and a memory cap per note, and noteguard fails
open on trap/exhaustion so a broken or runaway filter can't block writes, hang
the relay, or withhold a subscriber's own authorized feed.

On the read path the subscriber (the NIP-42 authed pubkey) is the script owner,
so a per-npub feed filter runs scoped to whoever is reading. Runtime::rescope
re-binds an already-compiled guest to a different owner and follow-set by cloning
the (internally reference-counted) engine/module/linker, so the guest is
JIT-compiled once per process and a subscription costs no compile or file read on
strfry's serving thread; a failed load is logged once rather than once per
subscription. The Verdict collapses on the read path to deliver (Accept) vs
withhold (anything else) — there is no shadow concept for reads. Only this filter
calls UnparsedNote::parse(); the throttles still never deserialize a Note.

Script/follow distribution is stubbed for this phase (configured statically via
`module`/`owner`/`follows` rather than sourced from signed submission events on
the relay); the point today is the ABI + runtime wiring.

Includes three example guests: follows-only (an inbox filter, <300 bytes with no
note parser linked in), an adversarial infinite-loop guest, and mute-word (an
owner-independent content mute, convenient for exercising the read path without
AUTH). Verified end-to-end on the write path: followed->accept,
stranger->reject, off-target->accept, and the spinner is stopped by fuel in
~15ms. And on the read path against strfry (branch config): content filtering
withholds exactly the muted events, a trapping guest fails open and delivers
all; plugin logs show reqOpen(+filter) -> req(+events) -> connClose.

Changelog-Added: Experimental nscript WASM note filter (behind the `nscript` feature), on both the write path and the readPolicy delivery path
Headway: headway:noteguard/chair-kick-reopen
Headway: headway:noteguard/gloom-lucky-budget
Agentium: agentium:exhaust-bus-combine

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-08 17:06:13 -07:00

436 lines
13 KiB
Rust

use noteguard::filters::{Blacklist, Content, Kinds, ProtectedEvents, RateLimit, Whitelist};
#[cfg(feature = "forwarder")]
use noteguard::filters::Forwarder;
#[cfg(feature = "nscript")]
use noteguard::filters::NScript;
use log::info;
use noteguard::{Action, InputMessage, NoteFilter, OutputMessage};
use serde::de::DeserializeOwned;
use serde::Deserialize;
use std::collections::HashMap;
use std::io;
#[derive(Deserialize)]
struct Config {
pipeline: Vec<String>,
filters: HashMap<String, toml::Value>,
}
type ConstructFilter = Box<fn(toml::Value) -> Result<Box<dyn NoteFilter>, toml::de::Error>>;
#[derive(Default)]
struct Noteguard {
registered_filters: HashMap<String, ConstructFilter>,
loaded_filters: Vec<Box<dyn NoteFilter>>,
}
impl Noteguard {
pub fn new() -> Self {
let mut noteguard = Noteguard::default();
noteguard.register_builtin_filters();
noteguard
}
pub fn register_filter<F: NoteFilter + 'static + Default + DeserializeOwned>(&mut self) {
self.registered_filters.insert(
F::name(&F::default()).to_string(),
Box::new(|filter_config| {
filter_config
.try_into()
.map(|filter: F| Box::new(filter) as Box<dyn NoteFilter>)
}),
);
}
/// All builtin filters are registered here, and are made available with
/// every new instance of [`Noteguard`]
fn register_builtin_filters(&mut self) {
self.register_filter::<RateLimit>();
self.register_filter::<Whitelist>();
self.register_filter::<Blacklist>();
self.register_filter::<ProtectedEvents>();
self.register_filter::<Kinds>();
self.register_filter::<Content>();
#[cfg(feature = "forwarder")]
self.register_filter::<Forwarder>();
#[cfg(feature = "nscript")]
self.register_filter::<NScript>();
}
/// Run the loaded filters. You must call `load_config` before calling this, otherwise
/// not filters will be run.
fn run(&mut self, input: InputMessage) -> OutputMessage {
let mut mout: Option<OutputMessage> = None;
let id = input.event.id.clone();
for filter in &mut self.loaded_filters {
let out = filter.filter_note(&input);
match out.action {
Action::Accept => {
mout = Some(out);
continue;
}
Action::Reject => {
return out;
}
Action::ShadowReject => {
return out;
}
}
}
mout.unwrap_or_else(|| OutputMessage::new(id, Action::Accept, None))
}
/// Initializes a noteguard config. If it finds any filter configurations
/// matching the registered filters, it loads those into our filter pipeline.
fn load_config(&mut self, config: &Config) -> Result<(), toml::de::Error> {
self.loaded_filters.clear();
for name in &config.pipeline {
let config_value = config
.filters
.get(name)
.unwrap_or_else(|| panic!("could not find filter configuration for {}", name));
if let Some(constructor) = self.registered_filters.get(name.as_str()) {
let filter = constructor(config_value.clone())?;
self.loaded_filters.push(filter);
} else {
panic!("Found config settings with no matching filter: {}", name);
}
}
Ok(())
}
}
#[cfg(feature = "forwarder")]
#[tokio::main]
async fn main() {
dispatch();
}
#[cfg(not(feature = "forwarder"))]
fn main() {
dispatch();
}
/// Route to the write-policy loop (default) or the read-policy loop
/// (`noteguard read`). strfry invokes the read plugin as a plain shell command,
/// e.g. `relay.readPolicy.plugin = "./noteguard read"`.
fn dispatch() {
env_logger::init();
match std::env::args().nth(1).as_deref() {
Some("read") => noteguard::readpolicy::run(),
_ => noteguard(),
}
}
fn serialize_output_message(msg: &OutputMessage) -> String {
serde_json::to_string(msg).expect("OutputMessage should always serialize correctly")
}
fn noteguard() {
info!("running noteguard");
let config_path = noteguard::config_path();
let mut noteguard = Noteguard::new();
let config: Config = {
let contents = std::fs::read_to_string(&config_path).expect("Failed to read config file");
toml::from_str(&contents).expect("Failed to parse config file")
};
noteguard
.load_config(&config)
.expect("Expected filter config to be loaded ok");
let stdin = io::stdin();
for line in stdin.lines() {
let line = match line {
Ok(line) => line,
Err(e) => {
eprintln!("Failed to get line: {}", e);
continue;
}
};
let input_message: InputMessage = match serde_json::from_str(&line) {
Ok(msg) => msg,
Err(e) => {
eprintln!("Failed to parse input: {}", e);
continue;
}
};
if input_message.message_type != "new" {
let out = OutputMessage::new(
input_message.event.id.clone(),
Action::Reject,
Some("invalid strfry write policy input".to_string()),
);
println!("{}", serialize_output_message(&out));
continue;
}
let out = noteguard.run(input_message);
let json = serialize_output_message(&out);
println!("{}", json);
}
}
#[cfg(test)]
mod tests {
use super::*;
use noteguard::{Action, Note};
// Helper function to create a mock InputMessage
fn create_mock_input_message(
event_id: &str,
message_type: &str,
source_info: &str,
) -> InputMessage {
InputMessage {
message_type: message_type.to_string(),
event: Note {
id: event_id.to_string(),
pubkey: "mock_pubkey".to_string(),
created_at: 0,
kind: 1,
tags: vec![vec!["-".to_string()]],
content: "mock_content".to_string(),
sig: "mock_signature".to_string(),
},
received_at: 0,
source_type: "mock_source".to_string(),
source_info: source_info.to_string(),
}
}
#[test]
fn test_register_builtin_filters() {
let noteguard = Noteguard::new();
assert!(noteguard.registered_filters.contains_key("ratelimit"));
assert!(noteguard.registered_filters.contains_key("whitelist"));
assert!(noteguard.registered_filters.contains_key("blacklist"));
assert!(noteguard
.registered_filters
.contains_key("protected_events"));
assert!(noteguard.registered_filters.contains_key("kinds"));
}
#[test]
fn test_load_config() {
let mut noteguard = Noteguard::new();
// Create a mock config with one filter (RateLimit)
let config: Config = toml::from_str(
r#"
pipeline = ["ratelimit"]
[filters.ratelimit]
posts_per_minute = 3
"#,
)
.expect("Failed to parse config");
assert!(noteguard.load_config(&config).is_ok());
assert_eq!(noteguard.loaded_filters.len(), 1);
}
#[test]
fn test_run_filters_accept() {
let mut noteguard = Noteguard::new();
// Create a mock config with one filter (RateLimit)
let config: Config = toml::from_str(
r#"
pipeline = ["ratelimit"]
[filters.ratelimit]
posts_per_minute = 3
"#,
)
.expect("Failed to parse config");
noteguard
.load_config(&config)
.expect("Failed to load config");
let input_message = create_mock_input_message("test_event_1", "new", "mock_source_info");
let output_message = noteguard.run(input_message);
assert_eq!(output_message.action, Action::Accept);
}
#[test]
fn test_run_filters_shadow_reject() {
let mut noteguard = Noteguard::new();
// Create a mock config with one filter (ProtectedEvents) which will shadow reject the input
let config: Config = toml::from_str(
r#"
pipeline = ["protected_events"]
[filters.protected_events]
"#,
)
.expect("Failed to parse config");
noteguard
.load_config(&config)
.expect("Failed to load config");
let input_message = create_mock_input_message("test_event_3", "new", "mock_source_info");
let output_message = noteguard.run(input_message);
assert_eq!(output_message.action, Action::Reject);
}
#[test]
fn test_whitelist_reject() {
let mut noteguard = Noteguard::new();
// Create a mock config with one filter (Whitelist) which will reject the input
let config: Config = toml::from_str(
r#"
pipeline = ["whitelist"]
[filters.whitelist]
pubkeys = ["something"]
"#,
)
.expect("Failed to parse config");
noteguard
.load_config(&config)
.expect("Failed to load config");
let input_message = create_mock_input_message("test_event_2", "new", "mock_source_info");
let output_message = noteguard.run(input_message);
assert_eq!(output_message.action, Action::Reject);
}
#[test]
fn test_blacklist_reject() {
let mut noteguard = Noteguard::new();
let config: Config = toml::from_str(
r#"
pipeline = ["blacklist"]
[filters.blacklist]
pubkeys = ["mock_pubkey"]
"#,
)
.expect("Failed to parse config");
noteguard
.load_config(&config)
.expect("Failed to load config");
let input_message = create_mock_input_message("test_event_3", "new", "mock_source_info");
let output_message = noteguard.run(input_message);
assert_eq!(output_message.action, Action::Reject);
assert_eq!(
output_message.msg.expect("Failed to get message"),
"blocked: pubkey/ip is blacklisted".to_string()
);
}
#[test]
fn test_blacklist_accept() {
let mut noteguard = Noteguard::new();
let config: Config = toml::from_str(
r#"
pipeline = ["blacklist"]
[filters.blacklist]
pubkeys = ["not_blacklisted"]
"#,
)
.expect("Failed to parse config");
noteguard
.load_config(&config)
.expect("Failed to load config");
let input_message = create_mock_input_message("test_event_4", "new", "mock_source_info");
let output_message = noteguard.run(input_message);
assert_eq!(output_message.action, Action::Accept);
}
#[test]
fn test_blacklist_cidr() {
let mut noteguard = Noteguard::new();
let config: Config = toml::from_str(
r#"
pipeline = ["blacklist"]
[filters.blacklist]
cidrs = ["127.0.0.1/24"]
"#,
)
.expect("Failed to parse config");
noteguard
.load_config(&config)
.expect("Failed to load config");
let test_cases = [
("127.0.0.1", true),
("127.0.0.2", true),
("128.0.0.1", false),
("127.1.0.1", false),
("127.0.1.1", false),
];
for (ip, should_reject) in test_cases.iter() {
let input_message = create_mock_input_message("event_id", "new", ip);
let output_message = noteguard.run(input_message);
if *should_reject {
assert_eq!(output_message.action, Action::Reject);
} else {
assert_eq!(output_message.action, Action::Accept);
}
}
}
#[test]
fn test_deserialize_input_message() {
let input_json = r#"
{
"type": "new",
"event": {
"id": "test_event_5",
"pubkey": "mock_pubkey",
"created_at": 0,
"kind": 1,
"tags": [],
"content": "mock_content",
"sig": "mock_signature"
},
"receivedAt": 0,
"sourceType": "mock_source",
"sourceInfo": "mock_source_info"
}
"#;
let input_message: InputMessage =
serde_json::from_str(input_json).expect("Failed to deserialize input message");
assert_eq!(input_message.event.id, "test_event_5");
assert_eq!(input_message.message_type, "new");
}
}