whitelist: premium gate via pubkey_sources

Phase 8 of PLAN.md. Rather than a separate premium_gate filter, the
whitelist gains:

- `pubkey_sources`: [sources.<name>] pubkey lists whose active,
  unexpired members are accepted (after static pubkeys and ips).
- `unavailable` ("reject" default | "accept"): what to do when nothing
  matched and a listed source has never loaded (no fetch, no cache).
  Reject uses `unavailable_message` (default "blocked: membership list
  unavailable, try again shortly"); accept logs one warning per outage.

A list loaded from the disk cache counts as loaded. Without
pubkey_sources the filter behaves exactly as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-10-29 07:24:55 +00:00
co-authored by Claude Opus 5.5
parent 9ee6254697
commit 70a69aa114
2 changed files with 242 additions and 13 deletions
+8 -2
View File
@@ -155,9 +155,15 @@ The whitelist filter only allows notes to pass if it matches a particular pubkey
- `ips` *optional*: a list of ip addresses to let through
- `message` *optional*: the error message for notes that match neither. Default is: `blocked: pubkey/ip not on the whitelist`
- `message` *optional*: the error message for notes that match nothing. Default is: `blocked: pubkey/ip not on the whitelist`
Either criteria can match
- `pubkey_sources` *optional*: names of `[sources.<name>]` pubkey lists (see [Sources](#sources)) whose active, unexpired members are let through. With `["premium"]` this is the premium gate.
- `unavailable` *optional*: what to do with a note that matches nothing while one of `pubkey_sources` has never loaded (no successful fetch and no cache). `"reject"` (default) fails closed; `"accept"` fails open and logs a warning.
- `unavailable_message` *optional*: the message for that case under `"reject"`. Default is: `blocked: membership list unavailable, try again shortly`
Any criterion can match
### Blacklist
+234 -11
View File
@@ -1,37 +1,103 @@
use crate::sources::PubkeyRef;
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
use log::warn;
use serde::Deserialize;
/// What the whitelist does with a note it cannot place because one of its
/// `pubkey_sources` has never loaded (no fetch and no cache succeeded).
#[derive(Deserialize, Default, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Unavailable {
/// Fail closed: reject with `unavailable_message`.
#[default]
Reject,
/// Fail open: accept, and log a warning.
Accept,
}
/// Lets a note through only if its pubkey or source IP is allowed. With
/// `pubkey_sources` it is the premium gate: active members of any listed
/// source are allowed too.
#[derive(Deserialize, Default)]
pub struct Whitelist {
pub pubkeys: Option<Vec<String>>,
pub ips: Option<Vec<String>>,
/// Message returned on reject. Defaults to `blocked: pubkey/ip not on the whitelist`.
pub message: Option<String>,
/// `[sources.<name>]` pubkey lists whose active (unexpired) members are
/// allowed, e.g. `["premium"]`.
#[serde(default)]
pub pubkey_sources: Vec<PubkeyRef>,
/// Policy when a note matches nothing and a source has never loaded.
#[serde(default)]
pub unavailable: Unavailable,
/// Message for that case under `unavailable = "reject"`.
pub unavailable_message: Option<String>,
/// Whether the fail-open warning has been logged, so an outage logs once
/// rather than once per note.
#[serde(skip)]
warned_unavailable: bool,
}
impl NoteFilter for Whitelist {
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
let accept = || OutputMessage::new(msg.event.id.clone(), Action::Accept, None);
let reject = |text: &str| {
OutputMessage::new(msg.event.id.clone(), Action::Reject, Some(text.to_owned()))
};
if let Some(pubkeys) = &self.pubkeys {
if pubkeys.contains(&msg.event.pubkey) {
return OutputMessage::new(msg.event.id.clone(), Action::Accept, None);
return accept();
}
}
if let Some(ips) = &self.ips {
if ips.contains(&msg.source_info) {
return OutputMessage::new(msg.event.id.clone(), Action::Accept, None);
return accept();
}
}
OutputMessage::new(
msg.event.id.clone(),
Action::Reject,
Some(
self.message
.as_deref()
.unwrap_or("blocked: pubkey/ip not on the whitelist")
.to_owned(),
),
if self
.pubkey_sources
.iter()
.any(|source| source.is_active(&msg.event.pubkey))
{
return accept();
}
// Nothing matched. If a list we depend on never loaded we cannot tell
// a member from a stranger, so apply the configured policy instead of
// the normal rejection.
if let Some(missing) = self.pubkey_sources.iter().find(|s| !s.is_loaded()) {
match self.unavailable {
Unavailable::Reject => {
return reject(
self.unavailable_message
.as_deref()
.unwrap_or("blocked: membership list unavailable, try again shortly"),
);
}
Unavailable::Accept => {
if !self.warned_unavailable {
warn!(
"whitelist: source {} unavailable, accepting notes (unavailable = \"accept\")",
missing.name()
);
self.warned_unavailable = true;
}
return accept();
}
}
}
self.warned_unavailable = false;
reject(
self.message
.as_deref()
.unwrap_or("blocked: pubkey/ip not on the whitelist"),
)
}
@@ -39,3 +105,160 @@ impl NoteFilter for Whitelist {
"whitelist"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sources::{declare, pubkey_source, testing, SourceConfig};
use crate::Note;
use std::collections::HashMap;
fn msg(pubkey: &str, ip: &str) -> InputMessage {
InputMessage {
message_type: "new".to_string(),
event: Note {
id: "e".to_string(),
pubkey: pubkey.to_string(),
created_at: 0,
kind: 1,
tags: vec![],
content: "hi".to_string(),
sig: "sig".to_string(),
},
received_at: 0,
source_type: "IP4".to_string(),
source_info: ip.to_string(),
}
}
fn whitelist(toml_cfg: &str) -> Whitelist {
toml::from_str(toml_cfg).expect("valid whitelist config")
}
fn run(w: &mut Whitelist, pubkey: &str, ip: &str) -> OutputMessage {
w.filter_note(&msg(pubkey, ip))
}
#[test]
fn premium_pubkey_accepted() {
testing::pubkeys("wl_premium", Some(&[("member", None)]));
let mut w = whitelist("pubkey_sources = [\"wl_premium\"]");
assert_eq!(run(&mut w, "member", "1.1.1.1").action, Action::Accept);
}
#[test]
fn non_premium_rejected_with_message() {
testing::pubkeys("wl_nonmember", Some(&[("member", None)]));
let mut w = whitelist("pubkey_sources = [\"wl_nonmember\"]");
let out = run(&mut w, "stranger", "1.1.1.1");
assert_eq!(out.action, Action::Reject);
assert_eq!(
out.msg.as_deref(),
Some("blocked: pubkey/ip not on the whitelist")
);
let mut w =
whitelist("pubkey_sources = [\"wl_nonmember\"]\nmessage = \"premium members only\"");
let out = run(&mut w, "stranger", "1.1.1.1");
assert_eq!(out.msg.as_deref(), Some("premium members only"));
}
#[test]
fn expired_premium_rejected() {
testing::pubkeys("wl_expired", Some(&[("lapsed", Some(1))]));
let mut w = whitelist("pubkey_sources = [\"wl_expired\"]");
assert_eq!(run(&mut w, "lapsed", "1.1.1.1").action, Action::Reject);
}
#[test]
fn any_listed_source_admits() {
testing::pubkeys("wl_any_a", Some(&[("alice", None)]));
testing::pubkeys("wl_any_b", Some(&[("bob", None)]));
let mut w = whitelist("pubkey_sources = [\"wl_any_a\", \"wl_any_b\"]");
assert_eq!(run(&mut w, "alice", "1.1.1.1").action, Action::Accept);
assert_eq!(run(&mut w, "bob", "1.1.1.1").action, Action::Accept);
assert_eq!(run(&mut w, "carol", "1.1.1.1").action, Action::Reject);
}
#[test]
fn static_pubkey_still_accepted() {
testing::pubkeys("wl_static", Some(&[]));
let mut w = whitelist("pubkeys = [\"admin\"]\npubkey_sources = [\"wl_static\"]");
assert_eq!(run(&mut w, "admin", "1.1.1.1").action, Action::Accept);
}
#[test]
fn localhost_ip_still_accepted() {
testing::pubkeys("wl_localhost", None);
let mut w = whitelist("ips = [\"127.0.0.1\"]\npubkey_sources = [\"wl_localhost\"]");
assert_eq!(run(&mut w, "anyone", "127.0.0.1").action, Action::Accept);
}
#[test]
fn never_loaded_reject_policy() {
testing::pubkeys("wl_unloaded_reject", None);
let mut w = whitelist("pubkey_sources = [\"wl_unloaded_reject\"]");
let out = run(&mut w, "member", "1.1.1.1");
assert_eq!(out.action, Action::Reject);
assert_eq!(
out.msg.as_deref(),
Some("blocked: membership list unavailable, try again shortly")
);
let mut w = whitelist(
"pubkey_sources = [\"wl_unloaded_reject\"]\nunavailable_message = \"try later\"",
);
assert_eq!(
run(&mut w, "member", "1.1.1.1").msg.as_deref(),
Some("try later")
);
}
#[test]
fn never_loaded_accept_policy() {
testing::pubkeys("wl_unloaded_accept", None);
let mut w =
whitelist("pubkey_sources = [\"wl_unloaded_accept\"]\nunavailable = \"accept\"");
assert_eq!(run(&mut w, "anyone", "1.1.1.1").action, Action::Accept);
}
#[test]
fn loaded_from_cache_counts_as_loaded() {
let member = "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93";
let cache = std::env::temp_dir()
.join(format!("noteguard-wl-cache-{}", std::process::id()))
.to_string_lossy()
.into_owned();
std::fs::write(&cache, format!(r#"["{member}"]"#)).unwrap();
let config: SourceConfig = toml::from_str(&format!(
"url = \"/nonexistent/wl-source\"\nformat = \"pubkeys\"\ncache_path = \"{cache}\""
))
.unwrap();
declare(&HashMap::from([("wl_cached".to_string(), config)])).unwrap();
pubkey_source("wl_cached").unwrap().initial_load();
let mut w = whitelist("pubkey_sources = [\"wl_cached\"]");
assert_eq!(run(&mut w, member, "1.1.1.1").action, Action::Accept);
// A stranger gets the normal message, not the unavailable one.
assert_eq!(
run(&mut w, "stranger", "1.1.1.1").msg.as_deref(),
Some("blocked: pubkey/ip not on the whitelist")
);
}
#[test]
fn no_sources_behaves_as_today() {
let mut w = whitelist("pubkeys = [\"admin\"]\nips = [\"127.0.0.1\"]");
assert_eq!(run(&mut w, "admin", "9.9.9.9").action, Action::Accept);
assert_eq!(run(&mut w, "x", "127.0.0.1").action, Action::Accept);
assert_eq!(
run(&mut w, "x", "9.9.9.9").msg.as_deref(),
Some("blocked: pubkey/ip not on the whitelist")
);
}
#[test]
fn bad_unavailable_value_fails_load() {
assert!(toml::from_str::<Whitelist>("unavailable = \"maybe\"").is_err());
}
}