Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5a3e472df | ||
|
|
85f8e35e00 | ||
|
|
9f656006d8 | ||
|
|
0e082512bd | ||
|
|
05d428f1d3 | ||
|
|
fc5a3938b3 | ||
|
|
64f246e547 | ||
|
|
4b16308ff0 | ||
|
|
8d39922f81 | ||
|
|
6651dde5a4 | ||
|
|
d6c69fed9d | ||
|
|
4265d3a019 | ||
|
|
a9638232a8 | ||
|
|
cad9b83241 | ||
|
|
6ac89a1626 | ||
|
|
4d4d9d62d0 | ||
|
|
11de1ddfbb | ||
|
|
62c2aa547b | ||
|
|
c22f1f0a24 | ||
|
|
e6566e65f9 | ||
|
|
2184378f0d | ||
|
|
db9ef05d85 | ||
|
|
778c5a053b | ||
|
|
77c2a8906c | ||
|
|
3b73e9aa00 | ||
|
|
4d4c9981ef | ||
|
|
690e2b0a47 | ||
|
|
5ec7642342 | ||
|
|
0c21ea0f03 | ||
|
|
cae0393ed0 | ||
|
|
8e1bb0363f | ||
|
|
471a70bbfa | ||
|
|
399f238865 | ||
|
|
4704b3034f | ||
|
|
670b390096 |
Generated
+1524
-46
File diff suppressed because it is too large
Load Diff
+20
-2
@@ -5,15 +5,33 @@ edition = "2021"
|
||||
|
||||
[features]
|
||||
forwarder = ["tokio-tungstenite", "tokio", "futures-util"]
|
||||
# nscript: run user-submitted WASM note filters (Phase 0 spike)
|
||||
nscript = ["wasmtime"]
|
||||
# cloudflare: escalate BanTracker IP-bans to a Cloudflare WAF IP list (edge block)
|
||||
cloudflare = ["ureq"]
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
serde_json = { version = "1.0", features = ["raw_value"] }
|
||||
toml = "0.5"
|
||||
ipnetwork = "0.20.0"
|
||||
unicode-security = "0.1.2"
|
||||
|
||||
# shared-memory per-IP read-bandwidth buckets: one mmap'd MAP_SHARED file shared
|
||||
# by every `noteguard read` plugin process on the host (memmap2), timestamped
|
||||
# against the system-wide CLOCK_MONOTONIC (libc clock_gettime).
|
||||
memmap2 = "0.9"
|
||||
libc = "0.2"
|
||||
|
||||
# forwarder deps
|
||||
tokio-tungstenite = { version = "0.23.1", optional = true }
|
||||
tokio-tungstenite = { version = "0.23.1", optional = true, features = ["native-tls"] }
|
||||
tokio = { version = "1.38.0", features = ["macros", "time", "sync", "rt-multi-thread"], optional = true }
|
||||
futures-util = { version = "0.3.30", optional = true }
|
||||
log = "0.4.22"
|
||||
env_logger = "0.11.3"
|
||||
|
||||
# nscript deps
|
||||
wasmtime = { version = "48", optional = true, default-features = false, features = ["cranelift", "runtime", "std"] }
|
||||
|
||||
# cloudflare deps — blocking HTTP client for the edge-ban worker
|
||||
ureq = { version = "2", optional = true, features = ["json"] }
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
tags:
|
||||
find src -name '*.rs' | xargs ctags
|
||||
rusty-tags vi
|
||||
|
||||
build-linux:
|
||||
cargo build --target x86_64-unknown-linux-musl --release
|
||||
|
||||
.PHONY: tags
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
# noteguard
|
||||
|
||||
A high performance note filter plugin system for [strfry]
|
||||
@@ -14,11 +13,12 @@ You can add any new filter you want by implementing the `NoteFilter` trait and r
|
||||
The `pipeline` config specifies the order in which filters are run. When the first `reject` or `shadowReject` action is hit, then the pipeline stops and returns the rejection error.
|
||||
|
||||
```toml
|
||||
pipeline = ["protected_events", "kinds", "whitelist", "ratelimit"]
|
||||
pipeline = ["protected_events", "kinds", "whitelist", "ratelimit", "forwarder"]
|
||||
|
||||
[filters.ratelimit]
|
||||
posts_per_minute = 8
|
||||
whitelist = ["127.0.0.1"]
|
||||
message = "rate-limit: you note too much"
|
||||
|
||||
[filters.whitelist]
|
||||
pubkeys = ["16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93"]
|
||||
@@ -32,6 +32,10 @@ kinds = [30065, 1064]
|
||||
1064 = "blocked: files on nostr is dumb"
|
||||
|
||||
[filters.protected_events]
|
||||
|
||||
[filters.forwarder]
|
||||
relay = "ws://localhost:8080"
|
||||
queue_size = 2000
|
||||
```
|
||||
|
||||
## Installation
|
||||
@@ -88,6 +92,38 @@ Settings:
|
||||
|
||||
- `whitelist` *optional*: a list of IP4 or IP6 addresses that are allowed to bypass the ratelimit.
|
||||
|
||||
- `message` *optional*: the error message to return when connection is rate-limited. default is: `rate-limited: you are noting too much`
|
||||
|
||||
- `ban_after` *optional*: IP-ban persistent offenders. After this many *consecutive* rate-limit rejections from the same IP (a streak that any accepted post resets), every note from that IP is rejected until the ban expires. Omit to disable banning — the filter then only ever rate-limits.
|
||||
|
||||
- `ban_duration_secs` *optional*: how long an IP-ban lasts, in seconds. Default is `3600` (one hour).
|
||||
|
||||
- `ban_message` *optional*: the error message returned to a banned IP. Default is: `banned: too many rate-limit violations, try again later`
|
||||
|
||||
### Cloudflare edge-banning
|
||||
|
||||
*Requires the `cloudflare` build feature (`cargo build --features cloudflare`).*
|
||||
|
||||
Any IP-ban — from `ratelimit`'s consecutive streak **or** `content`'s cumulative one — can be escalated to the edge. When enabled, a banned IP is added to a Cloudflare WAF IP list for the ban's duration and removed when it expires, so offenders are dropped by Cloudflare before they ever reach the relay. It is a single shared worker, so one configuration covers every filter that bans.
|
||||
|
||||
One-time Cloudflare setup (noteguard does **not** do this for you): create an IP list and a WAF custom rule that blocks it, e.g. expression `(ip.src in $your_list)` with action *block*. noteguard only manages the list's membership.
|
||||
|
||||
Configure it with a top-level `[cloudflare]` table:
|
||||
|
||||
```toml
|
||||
[cloudflare]
|
||||
account_id = "<cloudflare account id>"
|
||||
list_id = "<ip list id>"
|
||||
# comment = "noteguard auto-ban" # optional; stamped on each list item
|
||||
# timeout_secs = 10 # optional; per-request HTTP timeout
|
||||
# api_base = "..." # optional; override the API base URL
|
||||
```
|
||||
|
||||
- The API token is read from the **`CLOUDFLARE_API_TOKEN`** environment variable (needs *Account → Account Filter Lists → Edit*), never from the config file. If the section is present but the env var is unset, edge-banning is logged as disabled and the relay keeps running with relay-local bans only.
|
||||
- Omit the `[cloudflare]` section (or build without the feature) to disable edge-banning entirely.
|
||||
|
||||
Caveats: strfry runs one plugin process per ingester thread, each with its own banner — Cloudflare de-duplicates list items by value, so redundant adds are harmless. If a process dies mid-ban its pending removal is lost and the IP lingers in the list until a later run (or a human) clears it; the per-item `comment` tags noteguard's entries so they are easy to find.
|
||||
|
||||
### Whitelist
|
||||
|
||||
* name: `whitelist`
|
||||
@@ -100,6 +136,18 @@ The whitelist filter only allows notes to pass if it matches a particular pubkey
|
||||
|
||||
Either criteria can match
|
||||
|
||||
### Blacklist
|
||||
|
||||
* name: `blacklist`
|
||||
|
||||
The blacklist filter blocks notes that match any pubkey, ip, or CIDR range:
|
||||
|
||||
- `pubkeys` *optional*: a list of hex public keys to block
|
||||
|
||||
- `ips` *optional*: a list of IP addresses to block
|
||||
|
||||
- `cidrs` *optional*: a list of CIDR ranges to block
|
||||
|
||||
### Kinds
|
||||
|
||||
* name: `kinds`
|
||||
@@ -135,12 +183,228 @@ There are no config options, but an empty config entry is still needed:
|
||||
|
||||
* name: `forwarder`
|
||||
|
||||
You need to compile with the `forwarder` feature to enable this filter:
|
||||
|
||||
```sh
|
||||
$ cargo build --features forwarder --release
|
||||
```
|
||||
|
||||
The forwarder filter allows you to forward notes to another relay. Notes will
|
||||
be queued if the connection goes down (up to the `queue_size` buffer limit)
|
||||
|
||||
- `relay` - the relay to forward notes to, eg: `ws://localhost:8080`
|
||||
|
||||
- `queue_size` *optional* - size of the note queue, this is used to buffer notes if the connection goes down
|
||||
- `queue_size` *optional* - size of the note queue, this is used to buffer notes if the connection goes down. Default is 1000.
|
||||
|
||||
### NScript (experimental)
|
||||
|
||||
* name: `nscript`
|
||||
|
||||
Runs a user-supplied **WASM** module as a note filter. Instead of compiling
|
||||
filters into noteguard, the logic lives in a sandboxed wasm guest that reads the
|
||||
note through an *accessor ABI* — a set of imported host functions
|
||||
(`note_pubkey`, `note_kind`, `note_targets_owner`, `is_following`, …) — rather
|
||||
than parsing a note buffer itself. The note's byte format is therefore an
|
||||
implementation detail of the host, and guests stay tiny (the example below is
|
||||
under 300 bytes: no note parser is linked into it).
|
||||
|
||||
The intent is programmable, per-npub server-side filtering (e.g. inbox / mention
|
||||
spam control), eventually submitted to the relay as a signed event. This is a
|
||||
**Phase 0 spike**: the guest is loaded from a local path and the owner context
|
||||
comes from config.
|
||||
|
||||
Build with the `nscript` feature:
|
||||
|
||||
```sh
|
||||
$ cargo build --features nscript
|
||||
```
|
||||
|
||||
Config:
|
||||
|
||||
- `module` — path to the compiled guest `.wasm`
|
||||
- `owner` *optional* — hex pubkey the script is scoped to (its "inbox owner")
|
||||
- `follows` *optional* — hex pubkeys the owner follows (backs `is_following`)
|
||||
- `message` *optional* — message returned to the client on reject
|
||||
|
||||
```toml
|
||||
[filters.nscript]
|
||||
module = "./follows_only.wasm"
|
||||
owner = "1111…1111"
|
||||
follows = ["2222…2222"]
|
||||
message = "blocked: not in owner's follows"
|
||||
```
|
||||
|
||||
Guests are bounded by wasm **fuel** and a **memory cap** per note, and noteguard
|
||||
**fails open** (accepts) if a guest traps or exhausts its budget, so a broken or
|
||||
runaway filter can't block writes or hang the relay.
|
||||
|
||||
An example guest (`follows-only`, an inbox filter that rejects notes to the owner
|
||||
from non-followed authors) lives in [`nscript-guests/`](nscript-guests). Build it
|
||||
with:
|
||||
|
||||
```sh
|
||||
$ cd nscript-guests/follows-only
|
||||
$ cargo build --release --target wasm32-unknown-unknown
|
||||
```
|
||||
|
||||
## Read-policy (readPolicy) mode
|
||||
|
||||
Everything above is the **write-side** plugin: it decides what gets *stored* (a
|
||||
reject deletes the event for everyone). strfry also has a **read-side**
|
||||
(`readPolicy`) plugin hook that decides, *per subscription*, which already-stored
|
||||
events are *delivered* to that particular subscriber — the right hook for
|
||||
personal/inbox feed filtering and per-connection read throttling. Withholding an
|
||||
event never touches storage and never affects any other subscriber.
|
||||
|
||||
Run noteguard in read mode with the `read` subcommand and point strfry's
|
||||
`relay.readPolicy.plugin` at it:
|
||||
|
||||
```
|
||||
readPolicy {
|
||||
plugin = "./noteguard read"
|
||||
}
|
||||
```
|
||||
|
||||
The subscription's subscriber (the NIP-42 `authed` pubkey) and client IP are
|
||||
cached at `reqOpen` and handed to every filter, so a filter can scope its
|
||||
decisions to whoever is reading. Like strfry itself, the read loop **fails
|
||||
open**: a filter that errors, an unparseable message, or a misconfigured
|
||||
pipeline entry delivers rather than withholds.
|
||||
|
||||
Like the write side, the read side is a **composable filter pipeline**: it reads
|
||||
a `[readpolicy]` table from the same config file as the write side
|
||||
(`noteguard.toml`, or the file named by `$NOTEGUARD_CONFIG`) with an ordered
|
||||
`pipeline` of read-filter names plus a per-filter `[readpolicy.filters.X]`
|
||||
config table — the read-side analogue of the write-side `pipeline` /
|
||||
`[filters.X]`. An empty (or absent) pipeline delivers everything (every
|
||||
subscription is passthrough). Filters run in order per event.
|
||||
|
||||
```toml
|
||||
[readpolicy]
|
||||
# compose the read filters, in order. Empty/absent => deliver all.
|
||||
pipeline = ["max_events_per_conn", "read_bandwidth", "nscript"]
|
||||
|
||||
# connection-level throttle: max events delivered per connection.
|
||||
[readpolicy.filters.max_events_per_conn]
|
||||
max = 5000
|
||||
|
||||
# read-bandwidth throttle: max BYTES of events delivered per minute, keyed per
|
||||
# client IP. Reconnecting with a fresh connId from the same IP does NOT reset the
|
||||
# budget — the read-side analogue of the write-side `ratelimit` filter, metering
|
||||
# the exact wire size of each delivered event via an Instant token bucket
|
||||
# (tokens = bytes). Once an IP's per-minute byte budget is spent, further events
|
||||
# in the batch are withheld.
|
||||
[readpolicy.filters.read_bandwidth]
|
||||
bytes_per_minute = 5000000
|
||||
# cross-process enforcement is ON by default: leave shared_state_path unset and
|
||||
# every read process attaches to /dev/shm/noteguard-read-bandwidth. Set it to ""
|
||||
# to opt out to per-process buckets, or to another tmpfs path to override.
|
||||
# shared_state_path = "/dev/shm/noteguard-read-bandwidth"
|
||||
# exempt entries: an entry matches a connection's client IP OR its authed pubkey
|
||||
# hex (optional). A whitelisted connection is never metered and takes the
|
||||
# passthrough fast path.
|
||||
whitelist = ["127.0.0.1", "0000…0000"]
|
||||
|
||||
# guest wasm applied to subscriptions (owner = the authed subscriber). Requires
|
||||
# the `nscript` build feature; the pipeline entry is skipped (fail open) in a
|
||||
# build without it.
|
||||
[readpolicy.filters.nscript]
|
||||
module = "./mute_word.wasm"
|
||||
# STUB for follow-set distribution: owner-hex -> hex pubkeys they follow.
|
||||
# Backs the guest's is_following accessor until scripts/follows are sourced
|
||||
# from signed on-relay submissions.
|
||||
[readpolicy.filters.nscript.follows]
|
||||
# "1111…1111" = ["2222…2222"]
|
||||
```
|
||||
|
||||
Each filter is a [`ReadFilter`](src/read_filter.rs) — a lifecycle-aware,
|
||||
stateful analogue of the write-side [`NoteFilter`](src/note_filter.rs). It can
|
||||
allocate per-subscription / per-connection state at `reqOpen` and free it at
|
||||
`reqClose`/`connClose`, and returns one of **deliver**, **skip** (withhold this
|
||||
event), or **stop** (withhold this event and the rest of the batch) per event —
|
||||
so the throttles can bound a batch once a budget runs out. Adding a new read
|
||||
behavior is now a matter of implementing the trait and registering it, exactly
|
||||
like the write side.
|
||||
|
||||
**Passthrough fast path:** a subscription for which *no* filter needs per-event
|
||||
work answers `reqOpen` with `{"action":"accept","passthrough":true}`. strfry then
|
||||
skips all per-event marshaling for that subscription and delivers it via its
|
||||
zero-copy fast path, never sending `req` batches (it still sends
|
||||
`reqClose`/`connClose`). Each filter declares whether it needs events for a given
|
||||
subscription, and the engine ANDs those: an empty pipeline is always
|
||||
passthrough; a configured throttle keeps the subscription non-passthrough
|
||||
(strfry must keep sending events for the counter/byte-meter to bound delivery);
|
||||
a bandwidth-whitelisted connection is passthrough (it is never metered); and a
|
||||
`nscript` filter is non-passthrough only when it actually loaded a guest.
|
||||
Emitting the field is forward-compatible: a strfry without passthrough support
|
||||
simply ignores it.
|
||||
|
||||
**Per-IP bandwidth keying needs the client IP:** `read_bandwidth` meters per
|
||||
client IP so a reconnect can't reset the budget. `req` batches carry
|
||||
no IP, so noteguard caches the IP from the `reqOpen` message (added by newer
|
||||
strfry builds, alongside `connId`/`authed`) under its `connId`. Against an older
|
||||
strfry that doesn't send `ip`, metering degrades gracefully to per-connection
|
||||
(logged once per connection as a warning) — a reconnect then gets a fresh budget.
|
||||
|
||||
**Per-thread scoping and shared memory:** strfry runs *one plugin process per
|
||||
read-serving thread* (`relay.numThreads.reqWorker` / `reqMonitor`), each a
|
||||
separate `noteguard read` process. A connection is pinned to one thread
|
||||
(`connId % numThreads`), so a naive per-process bucket only survives a reconnect
|
||||
that lands on the *same* thread — an IP's reconnects fan across up to `numThreads`
|
||||
processes, making the effective per-IP budget up to `numThreads ×
|
||||
read_bandwidth.bytes_per_minute`.
|
||||
|
||||
To enforce **one** authoritative budget per IP while keeping every read thread,
|
||||
every `noteguard read` process on the host `mmap`s the same `tmpfs` file — a
|
||||
fixed open-addressing IP→bucket table guarded by per-slot spinlocks — so an IP's
|
||||
budget is a single shared bucket regardless of which process serves a given
|
||||
connection. **This is the default:** with `read_bandwidth.shared_state_path`
|
||||
unset, every process attaches to `/dev/shm/noteguard-read-bandwidth`
|
||||
automatically, so per-IP enforcement holds across processes out of the box — you
|
||||
don't need to configure anything. The table sizes to `max_ips` distinct IPs
|
||||
(default 65536, no eviction — buckets must survive a reconnect) and *fails open*
|
||||
(delivers, unmetered) if it fills, if a slot lock can't be taken, or if the
|
||||
`mmap` can't be created. It lives on `tmpfs`, so it survives strfry restarts and
|
||||
resets on reboot. Set `shared_state_path` to another `tmpfs` path to override the
|
||||
location, or to `""` to **opt out** to the old per-process behavior (accurate
|
||||
only within a single process, so the effective per-IP limit becomes
|
||||
`numThreads × bytes_per_minute` — for hosts that can't use `tmpfs`). Only
|
||||
`read_bandwidth` needs this; `max_events_per_conn` is keyed by `connId`, which is
|
||||
already pinned to one process, so its counter is authoritative as-is. (The
|
||||
write-side `ratelimit` filter has the same per-process scoping and is unaffected
|
||||
by this key.)
|
||||
|
||||
### NScript read filter (experimental)
|
||||
|
||||
* name: `nscript`
|
||||
|
||||
The read path can drive the same nscript WASM runtime as the write-side
|
||||
[`nscript`](#nscript-experimental) filter, so it needs the `nscript` feature
|
||||
(`cargo build --release --features nscript`); without it the pipeline entry is
|
||||
logged and skipped (fail open). The subscriber (the NIP-42 `authed` pubkey) is
|
||||
the script **owner**, so a per-npub feed filter runs scoped to whoever is
|
||||
reading. The guest is compiled once per process and re-scoped per subscriber —
|
||||
no recompile per subscription. The `Verdict` collapses on the read path to
|
||||
**deliver** (`Accept`) vs **withhold** (anything else); there is no "shadow"
|
||||
concept for reads. It fails open: a missing/failed module or a trapping guest
|
||||
delivers everything.
|
||||
|
||||
An unauthenticated subscription (no `authed`) still runs the guest, but with no
|
||||
owner: an owner-scoped filter like `follows-only` then no-ops and delivers
|
||||
everything, while an owner-independent filter still applies. The
|
||||
[`mute-word`](nscript-guests/mute-word) example guest (withholds kind-1 notes
|
||||
containing a muted word) is owner-independent, which makes it convenient for
|
||||
exercising the read path without AUTH:
|
||||
|
||||
```sh
|
||||
$ cd nscript-guests/mute-word
|
||||
$ cargo build --release --target wasm32-unknown-unknown
|
||||
```
|
||||
|
||||
Script/follow **distribution is stubbed** for this phase (configured statically
|
||||
via `module` and the `follows` map rather than sourced from signed submission
|
||||
events on the relay); the point of the read mode today is the protocol + runtime
|
||||
wiring.
|
||||
|
||||
|
||||
## Testing
|
||||
@@ -150,7 +414,7 @@ You can test your filters like so:
|
||||
```sh
|
||||
$ cargo build
|
||||
$ <test/inputs ./target/debug/noteguard
|
||||
$ ./test/delay | ./target/debug/noteguard
|
||||
$ ./test/delayed | ./target/debug/noteguard
|
||||
```
|
||||
|
||||
[strfry]: https://github.com/hoytech/strfry
|
||||
|
||||
+107
-2
@@ -1,9 +1,56 @@
|
||||
|
||||
pipeline = ["protected_events", "kinds", "whitelist", "ratelimit"]
|
||||
pipeline = ["protected_events", "kinds", "content", "whitelist", "ratelimit"]
|
||||
|
||||
[filters.ratelimit]
|
||||
posts_per_minute = 8
|
||||
whitelist = ["127.0.0.1"]
|
||||
message = "rate-limited: you note too much"
|
||||
# IP-ban persistent offenders: after this many *consecutive* rate-limit
|
||||
# rejections from the same IP (a streak broken by any accepted post), reject
|
||||
# everything from that IP for `ban_duration_secs`. Omit `ban_after` to disable
|
||||
# banning entirely (the filter then only ever rate-limits).
|
||||
ban_after = 10
|
||||
ban_duration_secs = 3600 # one hour
|
||||
ban_message = "banned: too many rate-limit violations, try again later"
|
||||
|
||||
# Substring blocklist. Matching is homoglyph- and case-insensitive: both the
|
||||
# note content and each term are folded to their UTS #39 confusables skeleton
|
||||
# and lowercased before comparison, so Cyrillic/look-alike spoofs like
|
||||
# "Dаmus Аirdrop" (Cyrillic а/А) are caught by the plain "Damus Airdrop" entry.
|
||||
[filters.content]
|
||||
filters = [
|
||||
"https://cdn.nostr.build/i/some-spammy-or-abusive-image-image.png",
|
||||
"Damus Airdrop",
|
||||
]
|
||||
# IP-ban repeat offenders (same knobs as `filters.ratelimit`). Content
|
||||
# violations accrue *cumulatively* per IP — unlike ratelimit's consecutive
|
||||
# streak, a clean note does not reset the count — and once they cross
|
||||
# `ban_after`, every note from that IP is silently shadow-rejected for
|
||||
# `ban_duration_secs`. Omit `ban_after` to disable banning (match-only, as
|
||||
# before). `ban_message` is unused here since the ban is a stealth shadow-reject.
|
||||
ban_after = 5
|
||||
ban_duration_secs = 3600 # one hour
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cloudflare edge-banning (optional; requires the `cloudflare` build feature)
|
||||
#
|
||||
# When present, every BanTracker ban — from `filters.ratelimit` OR
|
||||
# `filters.content` — is *also* pushed to a Cloudflare WAF IP list for the ban's
|
||||
# duration, then removed when it expires. A blocked IP is then dropped at
|
||||
# Cloudflare's edge before it ever reaches the relay.
|
||||
#
|
||||
# One-time setup on your side: create an IP list and a WAF custom rule that
|
||||
# blocks it, e.g. expression `(ip.src in $<your_list>)` with action "block".
|
||||
# noteguard only manages the list's membership, not the rule.
|
||||
#
|
||||
# The API token is read from the CLOUDFLARE_API_TOKEN environment variable (it
|
||||
# needs Account Filter Lists: Edit), never from this file. Omit this whole
|
||||
# section to disable edge-banning; bans then stay relay-local as before.
|
||||
# [cloudflare]
|
||||
# account_id = "<cloudflare account id>"
|
||||
# list_id = "<ip list id>"
|
||||
# comment = "noteguard auto-ban" # optional; stamped on each list item
|
||||
# timeout_secs = 10 # optional; per-request HTTP timeout
|
||||
# api_base = "https://api.cloudflare.com/client/v4" # optional override
|
||||
|
||||
[filters.whitelist]
|
||||
pubkeys = ["16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93"]
|
||||
@@ -19,3 +66,61 @@ kinds = [30065, 1064, 34550, 4550]
|
||||
4550 = "blocked: please use a dedicated relay for moderated communities"
|
||||
|
||||
[filters.protected_events]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Read policy — `noteguard read`
|
||||
#
|
||||
# Everything above is the write side: what gets *stored*. This section is the
|
||||
# read side: which already-stored events are *delivered* to a given subscriber.
|
||||
# Withholding an event never touches storage and never affects any other
|
||||
# subscriber. strfry runs it as a separate process against this same file:
|
||||
#
|
||||
# readPolicy { plugin = "./noteguard read" }
|
||||
# ---------------------------------------------------------------------------
|
||||
[readpolicy]
|
||||
# Read filters to compose, in order. Empty (the default) delivers everything,
|
||||
# and every subscription takes strfry's zero-copy passthrough fast path. The
|
||||
# filter tables below are inert until their name is listed here.
|
||||
pipeline = []
|
||||
# pipeline = ["max_events_per_conn", "read_bandwidth", "nscript"]
|
||||
|
||||
# Per-connection delivery cap: withhold once this connection has been delivered
|
||||
# `max` events, counted across all of its subscriptions and freed on disconnect.
|
||||
[readpolicy.filters.max_events_per_conn]
|
||||
max = 5000
|
||||
|
||||
# Read-bandwidth throttle: cap the BYTES of events delivered per minute, keyed
|
||||
# per client IP so reconnecting with a fresh connId does not reset the budget.
|
||||
# The read-side analogue of `filters.ratelimit` above.
|
||||
[readpolicy.filters.read_bandwidth]
|
||||
bytes_per_minute = 5000000
|
||||
# Shared-memory buckets: strfry runs one plugin process per read-serving thread,
|
||||
# so per-process buckets would make the effective per-IP limit up to
|
||||
# `relay.numThreads.reqWorker + reqMonitor` times `bytes_per_minute`. To enforce
|
||||
# ONE authoritative per-IP bucket, every process mmaps a single tmpfs file (see
|
||||
# the README). This is now the DEFAULT: leave `shared_state_path` unset and each
|
||||
# process attaches to /dev/shm/noteguard-read-bandwidth automatically — no config
|
||||
# needed for normal use. Fails open (delivers) if the file can't be mapped or the
|
||||
# table fills.
|
||||
# shared_state_path = "/dev/shm/noteguard-read-bandwidth" # the default path; set to override
|
||||
# shared_state_path = "" # OPT OUT: per-process buckets — DISABLES cross-process
|
||||
# # enforcement (for hosts that can't use tmpfs)
|
||||
# max_ips = 65536 # distinct IPs the shared table holds before it fails open
|
||||
# Exempt entries; each matches a connection's client IP OR its authed pubkey
|
||||
# hex. A whitelisted connection is never metered, so this filter asks for no
|
||||
# per-event work for it (the subscription is then passthrough unless another
|
||||
# filter in the pipeline still needs events).
|
||||
whitelist = ["127.0.0.1"]
|
||||
|
||||
# Guest wasm run per subscription, scoped to the subscriber (owner = the NIP-42
|
||||
# authed pubkey), so a per-npub feed filter runs scoped to whoever is reading.
|
||||
# Requires the `nscript` build feature; without it this pipeline entry is logged
|
||||
# and skipped (fail open).
|
||||
[readpolicy.filters.nscript]
|
||||
module = "./mute_word.wasm"
|
||||
|
||||
# STUB for follow-set distribution: owner-hex -> the hex pubkeys they follow,
|
||||
# backing the guest's `is_following` accessor, until scripts and follows are
|
||||
# sourced from signed on-relay submissions.
|
||||
[readpolicy.filters.nscript.follows]
|
||||
# "1111…1111" = ["2222…2222"]
|
||||
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "follows-only"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,16 @@
|
||||
# Standalone crate (its own workspace) so it is not pulled into noteguard's build.
|
||||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "follows-only"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Example nscript guest: a follows-only inbox filter.
|
||||
//!
|
||||
//! Rejects notes addressed (p-tagged) to the scoped owner unless the author is
|
||||
//! someone the owner follows. Notes that don't target the owner are accepted
|
||||
//! untouched.
|
||||
//!
|
||||
//! Note how there is no note parser compiled into this module: it reads the note
|
||||
//! purely through the host accessor ABI. Owner-relative context (who the owner
|
||||
//! is, and their follow set) lives on the host, so this module is reusable logic
|
||||
//! independent of any particular npub.
|
||||
|
||||
#![no_std]
|
||||
|
||||
use core::panic::PanicInfo;
|
||||
|
||||
// ---- accessor ABI (imported from the host) ----
|
||||
#[link(wasm_import_module = "env")]
|
||||
extern "C" {
|
||||
/// Writes the 32-byte author pubkey into `out_ptr`; returns bytes written.
|
||||
fn note_pubkey(out_ptr: *mut u8) -> i32;
|
||||
/// 1 if the note p-tags the scoped owner, else 0.
|
||||
fn note_targets_owner() -> i32;
|
||||
/// 1 if the 32-byte pubkey at `pk_ptr` is in the owner's follow set.
|
||||
fn is_following(pk_ptr: *const u8) -> i32;
|
||||
}
|
||||
|
||||
const ACCEPT: i32 = 0;
|
||||
const REJECT: i32 = 1;
|
||||
|
||||
/// The host calls this once per note; the current note is implicit.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn filter_note() -> i32 {
|
||||
unsafe {
|
||||
// Only govern notes addressed to our owner; leave everything else alone.
|
||||
if note_targets_owner() == 0 {
|
||||
return ACCEPT;
|
||||
}
|
||||
|
||||
let mut author = [0u8; 32];
|
||||
note_pubkey(author.as_mut_ptr());
|
||||
|
||||
if is_following(author.as_ptr()) == 1 {
|
||||
ACCEPT
|
||||
} else {
|
||||
REJECT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_: &PanicInfo) -> ! {
|
||||
loop {}
|
||||
}
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "loop-forever"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,14 @@
|
||||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "loop-forever"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Adversarial nscript guest: never returns. Must be stopped by host fuel.
|
||||
#![no_std]
|
||||
use core::panic::PanicInfo;
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn filter_note() -> i32 {
|
||||
let mut x: u64 = 0;
|
||||
loop {
|
||||
// volatile-ish spin so the optimizer can't fold it away
|
||||
x = x.wrapping_add(1);
|
||||
unsafe { core::ptr::read_volatile(&x); }
|
||||
}
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_: &PanicInfo) -> ! { loop {} }
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "mute-word"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,16 @@
|
||||
# Standalone crate (its own workspace) so it is not pulled into noteguard's build.
|
||||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "mute-word"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Example nscript guest: an owner-independent muted-word read filter.
|
||||
//!
|
||||
//! Withholds kind-1 notes whose content contains the muted word "spam";
|
||||
//! everything else is delivered. Unlike `follows-only`, this guest reads no
|
||||
//! owner context, so it applies identically to every subscriber (authenticated
|
||||
//! or not) — which makes it convenient for exercising the read-side
|
||||
//! deliver/withhold path without NIP-42 AUTH.
|
||||
//!
|
||||
//! As with the other guests, there is no note parser compiled in: the content
|
||||
//! is read through the host accessor ABI.
|
||||
|
||||
#![no_std]
|
||||
|
||||
use core::panic::PanicInfo;
|
||||
|
||||
#[link(wasm_import_module = "env")]
|
||||
extern "C" {
|
||||
/// The note's kind.
|
||||
fn note_kind() -> i64;
|
||||
/// Copies up to `cap` bytes of the note content into `out_ptr`; returns the
|
||||
/// content's true length (which may exceed `cap`).
|
||||
fn note_content(out_ptr: *mut u8, cap: i32) -> i32;
|
||||
}
|
||||
|
||||
const ACCEPT: i32 = 0;
|
||||
const REJECT: i32 = 1;
|
||||
|
||||
/// The muted word. A note delivering it is withheld.
|
||||
const MUTED: &[u8] = b"spam";
|
||||
|
||||
/// Scratch buffer for the note content. Content longer than this is truncated
|
||||
/// for the scan (a muted word past the cutoff won't match — acceptable for a
|
||||
/// spike; a real filter would stream or raise the cap).
|
||||
const CAP: usize = 4096;
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn filter_note() -> i32 {
|
||||
unsafe {
|
||||
// Only govern kind-1 (text notes); leave everything else alone.
|
||||
if note_kind() != 1 {
|
||||
return ACCEPT;
|
||||
}
|
||||
|
||||
let mut buf = [0u8; CAP];
|
||||
let true_len = note_content(buf.as_mut_ptr(), CAP as i32);
|
||||
let n = if true_len < 0 {
|
||||
0
|
||||
} else {
|
||||
(true_len as usize).min(CAP)
|
||||
};
|
||||
|
||||
if contains(&buf[..n], MUTED) {
|
||||
REJECT
|
||||
} else {
|
||||
ACCEPT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Naive substring search (no_std, no allocator).
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
if needle.is_empty() || needle.len() > haystack.len() {
|
||||
return needle.is_empty();
|
||||
}
|
||||
let mut i = 0;
|
||||
while i + needle.len() <= haystack.len() {
|
||||
if &haystack[i..i + needle.len()] == needle {
|
||||
return true;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_: &PanicInfo) -> ! {
|
||||
loop {}
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
//! Shared Cloudflare edge-ban integration for the write-path [`BanTracker`].
|
||||
//!
|
||||
//! When a filter's local ban trips (ratelimit's consecutive streak or content's
|
||||
//! cumulative one — both funnel through [`BanTracker::strike`](crate::filters)),
|
||||
//! we also add the offender's IP to a Cloudflare **WAF IP list**, and remove it
|
||||
//! again when the ban expires. The operator wires that list into a zone WAF
|
||||
//! custom rule once (`ip.src in $your_list` → *block*); noteguard only manages
|
||||
//! the list's *membership*, so a banned IP is dropped at Cloudflare's edge before
|
||||
//! it ever reaches the relay.
|
||||
//!
|
||||
//! The banner is a single process-global background worker shared by every
|
||||
//! `BanTracker` (both the ratelimit and content filters escalate to the same
|
||||
//! list), configured once from the top-level `[cloudflare]` table plus the
|
||||
//! `CLOUDFLARE_API_TOKEN` env var. It is entirely opt-in: with no `[cloudflare]`
|
||||
//! section (or the feature compiled out) [`edge_ban`] is a no-op and noteguard
|
||||
//! behaves exactly as before.
|
||||
//!
|
||||
//! ## Why a background worker and a timer
|
||||
//!
|
||||
//! Two things force the design:
|
||||
//!
|
||||
//! * **HTTP must not block the note path.** strfry feeds events line-by-line;
|
||||
//! a ban is rare but an API round-trip is slow, so bans are handed to a
|
||||
//! background thread over a channel and the filter returns immediately.
|
||||
//! * **Expiry can't be driven by the note path.** Once an IP is blocked at the
|
||||
//! edge it never reaches noteguard again, so nothing on the ingest side can
|
||||
//! notice the local ban elapsing. The worker therefore schedules each removal
|
||||
//! on a timer of its own.
|
||||
//!
|
||||
//! ## Caveats
|
||||
//!
|
||||
//! * strfry runs one plugin process per ingester thread, each with its own
|
||||
//! worker; several may add the same IP. Cloudflare's list de-duplicates by
|
||||
//! value, so the redundant adds are harmless, and each worker removes on its
|
||||
//! own timer.
|
||||
//! * If a process dies mid-ban its pending removal is lost and the IP lingers in
|
||||
//! the list until a later run (or a human) clears it. The per-item `comment`
|
||||
//! tags noteguard's entries so they're easy to find.
|
||||
|
||||
use log::{info, warn};
|
||||
use serde::Deserialize;
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::{BinaryHeap, HashMap};
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Cloudflare API base, overridable via config for tests / self-hosted gateways.
|
||||
fn default_api_base() -> String {
|
||||
"https://api.cloudflare.com/client/v4".to_string()
|
||||
}
|
||||
|
||||
/// Marker embedded in each list item's comment, followed by the ban's wall-clock
|
||||
/// expiry (unix seconds). This makes the Cloudflare list self-describing: on
|
||||
/// startup [`BanWorker::reconcile`] re-reads these to recover removals that an
|
||||
/// earlier process added but never got to delete (see the module docs). The
|
||||
/// marker also scopes reconciliation to *our* items, so a shared list's other
|
||||
/// entries are never touched.
|
||||
const BAN_MARKER: &str = "noteguard-ban;until=";
|
||||
|
||||
/// Seconds since the unix epoch (saturating to 0 on the impossible pre-epoch
|
||||
/// clock), used for the wall-clock expiry stamped into item comments. The
|
||||
/// worker's in-process timer uses [`Instant`] instead; only the persisted stamp
|
||||
/// needs to be wall-clock so it survives a restart.
|
||||
fn now_unix() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Parse the expiry out of a list item's comment, or `None` if it isn't one of
|
||||
/// noteguard's items.
|
||||
fn parse_until(comment: &str) -> Option<u64> {
|
||||
let rest = comment.split(BAN_MARKER).nth(1)?;
|
||||
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
|
||||
digits.parse().ok()
|
||||
}
|
||||
|
||||
/// The `[cloudflare]` config table. The API token is *not* here — it comes from
|
||||
/// the `CLOUDFLARE_API_TOKEN` environment variable so the secret stays out of
|
||||
/// the config file.
|
||||
#[derive(Deserialize, Clone)]
|
||||
pub struct CloudflareConfig {
|
||||
/// Cloudflare account that owns the IP list.
|
||||
pub account_id: String,
|
||||
/// Id of the WAF IP list to manage membership of.
|
||||
pub list_id: String,
|
||||
/// API base URL. Defaults to the public Cloudflare API.
|
||||
#[serde(default)]
|
||||
pub api_base: Option<String>,
|
||||
/// Comment stamped on each list item, so noteguard's entries are identifiable.
|
||||
#[serde(default)]
|
||||
pub comment: Option<String>,
|
||||
/// Per-request HTTP timeout in seconds. Defaults to 10.
|
||||
#[serde(default)]
|
||||
pub timeout_secs: Option<u64>,
|
||||
}
|
||||
|
||||
/// A request for the background worker: edge-ban `ip` for `duration`.
|
||||
struct BanCommand {
|
||||
ip: String,
|
||||
duration: Duration,
|
||||
}
|
||||
|
||||
/// The Cloudflare list operations the worker needs. Abstracted behind a trait so
|
||||
/// the worker's scheduling/dedup logic can be unit-tested without real HTTP.
|
||||
trait CfApi: Send {
|
||||
/// Append `ip` to the list with its `until_unix` expiry stamped into the
|
||||
/// comment (Cloudflare de-duplicates by value).
|
||||
fn add(&self, ip: &str, until_unix: u64);
|
||||
/// Resolve `ip`'s list-item id and delete it.
|
||||
fn remove(&self, ip: &str);
|
||||
/// Every noteguard-tagged item currently in the list, as `(ip, until_unix)`,
|
||||
/// for startup reconciliation.
|
||||
fn list_bans(&self) -> Vec<(String, u64)>;
|
||||
}
|
||||
|
||||
/// Live Cloudflare Lists API client (`ureq`, blocking).
|
||||
#[cfg(feature = "cloudflare")]
|
||||
struct CloudflareApi {
|
||||
agent: ureq::Agent,
|
||||
token: String,
|
||||
account_id: String,
|
||||
list_id: String,
|
||||
api_base: String,
|
||||
comment: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "cloudflare")]
|
||||
impl CloudflareApi {
|
||||
fn items_url(&self) -> String {
|
||||
format!(
|
||||
"{}/accounts/{}/rules/lists/{}/items",
|
||||
self.api_base, self.account_id, self.list_id
|
||||
)
|
||||
}
|
||||
|
||||
fn bearer(&self) -> String {
|
||||
format!("Bearer {}", self.token)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "cloudflare")]
|
||||
impl CfApi for CloudflareApi {
|
||||
fn add(&self, ip: &str, until_unix: u64) {
|
||||
// POST a one-element batch; the Lists API is async and returns an
|
||||
// operation_id, but for a single IP we fire-and-forget — membership
|
||||
// settles within seconds and the local ban covers the gap. The expiry is
|
||||
// stamped into the comment so a later process can reconcile it.
|
||||
let comment = format!("{} {BAN_MARKER}{until_unix}", self.comment);
|
||||
let body = serde_json::json!([{ "ip": ip, "comment": comment }]);
|
||||
match self
|
||||
.agent
|
||||
.post(&self.items_url())
|
||||
.set("Authorization", &self.bearer())
|
||||
.send_json(body)
|
||||
{
|
||||
Ok(_) => info!("cloudflare: queued edge-ban add for {ip}"),
|
||||
Err(e) => warn!("cloudflare: failed to add {ip} to list: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_bans(&self) -> Vec<(String, u64)> {
|
||||
let mut out = Vec::new();
|
||||
let mut cursor: Option<String> = None;
|
||||
// Follow Cloudflare's pagination cursors so a large list is fully
|
||||
// reconciled rather than silently truncated to the first page.
|
||||
loop {
|
||||
let mut req = self
|
||||
.agent
|
||||
.get(&self.items_url())
|
||||
.set("Authorization", &self.bearer());
|
||||
if let Some(c) = &cursor {
|
||||
req = req.query("cursor", c);
|
||||
}
|
||||
let resp = match req.call() {
|
||||
Ok(resp) => resp,
|
||||
Err(e) => {
|
||||
warn!("cloudflare: failed to list items for reconcile: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
let json: serde_json::Value = match resp.into_json() {
|
||||
Ok(json) => json,
|
||||
Err(e) => {
|
||||
warn!("cloudflare: bad list-items response during reconcile: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
if let Some(items) = json["result"].as_array() {
|
||||
for it in items {
|
||||
let (Some(ip), Some(comment)) = (it["ip"].as_str(), it["comment"].as_str())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Some(until) = parse_until(comment) {
|
||||
out.push((ip.to_owned(), until));
|
||||
}
|
||||
}
|
||||
}
|
||||
match json["result_info"]["cursors"]["after"].as_str() {
|
||||
Some(next) if !next.is_empty() => cursor = Some(next.to_owned()),
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn remove(&self, ip: &str) {
|
||||
// Deletion is by item id, so resolve it first. `search` is a substring
|
||||
// match, hence the exact-ip filter on the returned items.
|
||||
let resp = match self
|
||||
.agent
|
||||
.get(&self.items_url())
|
||||
.query("search", ip)
|
||||
.set("Authorization", &self.bearer())
|
||||
.call()
|
||||
{
|
||||
Ok(resp) => resp,
|
||||
Err(e) => {
|
||||
warn!("cloudflare: failed to look up list item for {ip}: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let json: serde_json::Value = match resp.into_json() {
|
||||
Ok(json) => json,
|
||||
Err(e) => {
|
||||
warn!("cloudflare: bad list-items response for {ip}: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let item_id = json["result"]
|
||||
.as_array()
|
||||
.and_then(|items| items.iter().find(|it| it["ip"].as_str() == Some(ip)))
|
||||
.and_then(|it| it["id"].as_str().map(str::to_owned));
|
||||
|
||||
let Some(item_id) = item_id else {
|
||||
warn!("cloudflare: no list item for {ip}; nothing to remove");
|
||||
return;
|
||||
};
|
||||
|
||||
let body = serde_json::json!({ "items": [ { "id": item_id } ] });
|
||||
match self
|
||||
.agent
|
||||
.delete(&self.items_url())
|
||||
.set("Authorization", &self.bearer())
|
||||
.send_json(body)
|
||||
{
|
||||
Ok(_) => info!("cloudflare: queued edge-ban removal for {ip}"),
|
||||
Err(e) => warn!("cloudflare: failed to remove {ip} from list: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Background worker: owns the API client and the set of currently edge-banned
|
||||
/// IPs, and schedules each removal on its own expiry timer.
|
||||
struct BanWorker<A: CfApi> {
|
||||
api: A,
|
||||
/// ip -> the deadline its ban currently expires at.
|
||||
active: HashMap<String, Instant>,
|
||||
/// Min-heap (via `Reverse`) of `(deadline, ip)` driving removals. May hold
|
||||
/// stale entries superseded by an extension; [`sweep`](Self::sweep) skips
|
||||
/// any whose deadline no longer matches `active`.
|
||||
expiries: BinaryHeap<Reverse<(Instant, String)>>,
|
||||
}
|
||||
|
||||
impl<A: CfApi> BanWorker<A> {
|
||||
fn new(api: A) -> Self {
|
||||
BanWorker {
|
||||
api,
|
||||
active: HashMap::new(),
|
||||
expiries: BinaryHeap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record `ip`'s removal deadline in the schedule. Does not touch Cloudflare
|
||||
/// — callers decide whether a list `add` is also needed.
|
||||
fn track(&mut self, ip: String, deadline: Instant) {
|
||||
self.active.insert(ip.clone(), deadline);
|
||||
self.expiries.push(Reverse((deadline, ip)));
|
||||
}
|
||||
|
||||
/// Record a ban for `ip` expiring at `deadline` (wall-clock `until_unix`,
|
||||
/// stamped into the list item). Adds to the Cloudflare list only on the first
|
||||
/// ban for an IP; a later ban merely extends the deadline (a shorter one is
|
||||
/// ignored so a ban is never cut short). An extension updates only the local
|
||||
/// timer, not the persisted stamp, so after a restart an extended ban falls
|
||||
/// back to its original expiry — acceptable for a rare edge.
|
||||
fn on_ban(&mut self, ip: String, deadline: Instant, until_unix: u64) {
|
||||
match self.active.get(&ip) {
|
||||
Some(¤t) if current >= deadline => {} // already banned at least this long
|
||||
Some(_) => self.track(ip, deadline), // extend; already in the list
|
||||
None => {
|
||||
self.track(ip.clone(), deadline);
|
||||
self.api.add(&ip, until_unix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recover state from the Cloudflare list at startup: anything already past
|
||||
/// its stamped expiry is deleted now (these are the removals a prior process
|
||||
/// added but never got to run), and anything still live is re-scheduled on
|
||||
/// the worker's timer without re-adding it. `now_unix` is the current
|
||||
/// wall-clock time in unix seconds.
|
||||
fn reconcile(&mut self, now_unix: u64) {
|
||||
for (ip, until_unix) in self.api.list_bans() {
|
||||
if until_unix <= now_unix {
|
||||
self.api.remove(&ip);
|
||||
} else {
|
||||
let remaining = Duration::from_secs(until_unix - now_unix);
|
||||
self.track(ip, Instant::now() + remaining);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove from the list every ban whose deadline has passed as of `now`.
|
||||
fn sweep(&mut self, now: Instant) {
|
||||
while let Some(Reverse((deadline, _))) = self.expiries.peek() {
|
||||
if *deadline > now {
|
||||
break;
|
||||
}
|
||||
let Reverse((deadline, ip)) = self.expiries.pop().expect("peeked");
|
||||
// Act only if this entry is the live deadline for the IP; an entry
|
||||
// superseded by an extension has a different `active` deadline.
|
||||
if self.active.get(&ip) == Some(&deadline) {
|
||||
self.api.remove(&ip);
|
||||
self.active.remove(&ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The soonest scheduled removal, if any — how long the run loop may block.
|
||||
fn next_deadline(&self) -> Option<Instant> {
|
||||
self.expiries.peek().map(|Reverse((d, _))| *d)
|
||||
}
|
||||
|
||||
/// Drive the worker: recover any pending removals left by a prior process,
|
||||
/// then block until the next command or the next removal is due, whichever
|
||||
/// comes first, and apply it. Exits when the sender is dropped.
|
||||
fn run(mut self, rx: Receiver<BanCommand>) {
|
||||
self.reconcile(now_unix());
|
||||
self.sweep(Instant::now());
|
||||
loop {
|
||||
let received = match self.next_deadline() {
|
||||
Some(deadline) => rx.recv_timeout(deadline.saturating_duration_since(Instant::now())),
|
||||
None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected),
|
||||
};
|
||||
match received {
|
||||
Ok(cmd) => {
|
||||
let until = now_unix().saturating_add(cmd.duration.as_secs());
|
||||
self.on_ban(cmd.ip, Instant::now() + cmd.duration, until);
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
self.sweep(Instant::now());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The process-global banner. `None` once initialized without a usable config
|
||||
/// (e.g. missing token), so [`edge_ban`] stays a no-op in that case.
|
||||
static BANNER: OnceLock<Option<Sender<BanCommand>>> = OnceLock::new();
|
||||
|
||||
/// Initialize the shared edge-banner from `[cloudflare]` config. Call once at
|
||||
/// startup. A missing `CLOUDFLARE_API_TOKEN` disables edge-banning (logged, not
|
||||
/// fatal — the relay still runs with relay-local bans).
|
||||
#[cfg(feature = "cloudflare")]
|
||||
pub fn init(config: CloudflareConfig) {
|
||||
let _ = BANNER.set(spawn(config));
|
||||
}
|
||||
|
||||
#[cfg(feature = "cloudflare")]
|
||||
fn spawn(config: CloudflareConfig) -> Option<Sender<BanCommand>> {
|
||||
let token = match std::env::var("CLOUDFLARE_API_TOKEN") {
|
||||
Ok(t) if !t.is_empty() => t,
|
||||
_ => {
|
||||
warn!(
|
||||
"cloudflare: [cloudflare] configured but CLOUDFLARE_API_TOKEN is unset; \
|
||||
edge-banning disabled"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let list_id = config.list_id.clone();
|
||||
let api = CloudflareApi {
|
||||
agent: ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(config.timeout_secs.unwrap_or(10)))
|
||||
.build(),
|
||||
token,
|
||||
account_id: config.account_id,
|
||||
list_id: config.list_id,
|
||||
api_base: config.api_base.unwrap_or_else(default_api_base),
|
||||
comment: config.comment.unwrap_or_else(|| "noteguard auto-ban".to_string()),
|
||||
};
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("cloudflare-banner".to_string())
|
||||
.spawn(move || BanWorker::new(api).run(rx))
|
||||
.expect("spawn cloudflare-banner thread");
|
||||
|
||||
info!("cloudflare: edge-banning enabled (list {list_id})");
|
||||
Some(tx)
|
||||
}
|
||||
|
||||
/// Escalate a local ban to the edge: add `ip` to the Cloudflare list for
|
||||
/// `duration`. A no-op unless [`init`] configured a live banner. Never blocks —
|
||||
/// the request is handed to the background worker.
|
||||
pub fn edge_ban(ip: &str, duration: Duration) {
|
||||
if let Some(Some(tx)) = BANNER.get() {
|
||||
if tx
|
||||
.send(BanCommand {
|
||||
ip: ip.to_owned(),
|
||||
duration,
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
warn!("cloudflare: banner worker is gone; dropping edge-ban for {ip}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Records `(op, ip)` calls instead of hitting the network. `existing` is the
|
||||
/// canned list the worker sees during [`reconcile`](BanWorker::reconcile).
|
||||
#[derive(Clone, Default)]
|
||||
struct MockApi {
|
||||
calls: Arc<Mutex<Vec<(String, String)>>>,
|
||||
existing: Arc<Mutex<Vec<(String, u64)>>>,
|
||||
}
|
||||
|
||||
impl MockApi {
|
||||
fn calls(&self) -> Vec<(String, String)> {
|
||||
self.calls.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl CfApi for MockApi {
|
||||
fn add(&self, ip: &str, _until_unix: u64) {
|
||||
self.calls.lock().unwrap().push(("add".into(), ip.into()));
|
||||
}
|
||||
fn remove(&self, ip: &str) {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(("remove".into(), ip.into()));
|
||||
}
|
||||
fn list_bans(&self) -> Vec<(String, u64)> {
|
||||
self.existing.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_until_out_of_comment() {
|
||||
assert_eq!(
|
||||
parse_until(&format!("noteguard auto-ban {BAN_MARKER}1757000000")),
|
||||
Some(1_757_000_000)
|
||||
);
|
||||
// A trailing human suffix after the digits is tolerated.
|
||||
assert_eq!(parse_until(&format!("{BAN_MARKER}42 (spam)")), Some(42));
|
||||
// Items that aren't ours are ignored.
|
||||
assert_eq!(parse_until("manually added by ops"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_parses_with_token_out_of_band() {
|
||||
let cfg: CloudflareConfig = toml::from_str(
|
||||
"account_id = \"acct\"\nlist_id = \"lst\"\ncomment = \"banned by noteguard\"\n",
|
||||
)
|
||||
.expect("valid cloudflare config");
|
||||
assert_eq!(cfg.account_id, "acct");
|
||||
assert_eq!(cfg.list_id, "lst");
|
||||
assert_eq!(cfg.comment.as_deref(), Some("banned by noteguard"));
|
||||
assert!(cfg.api_base.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adds_once_and_removes_on_expiry() {
|
||||
let api = MockApi::default();
|
||||
let mut w = BanWorker::new(api.clone());
|
||||
let t0 = Instant::now();
|
||||
let deadline = t0 + Duration::from_secs(60);
|
||||
|
||||
w.on_ban("1.2.3.4".into(), deadline, 0);
|
||||
// A second ban for the same IP within the window must not re-add it.
|
||||
w.on_ban("1.2.3.4".into(), deadline, 0);
|
||||
w.sweep(t0 + Duration::from_secs(1)); // not yet expired
|
||||
assert_eq!(api.calls(), vec![("add".into(), "1.2.3.4".into())]);
|
||||
|
||||
// Once the deadline passes, the IP is removed exactly once.
|
||||
w.sweep(t0 + Duration::from_secs(61));
|
||||
assert_eq!(
|
||||
api.calls(),
|
||||
vec![
|
||||
("add".into(), "1.2.3.4".into()),
|
||||
("remove".into(), "1.2.3.4".into()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extending_a_ban_defers_removal_and_never_double_removes() {
|
||||
let api = MockApi::default();
|
||||
let mut w = BanWorker::new(api.clone());
|
||||
let t0 = Instant::now();
|
||||
|
||||
w.on_ban("9.9.9.9".into(), t0 + Duration::from_secs(60), 0);
|
||||
// Re-ban with a later deadline before the first elapses: extend it.
|
||||
w.on_ban("9.9.9.9".into(), t0 + Duration::from_secs(120), 0);
|
||||
|
||||
// At the original deadline the (now stale) entry must NOT trigger a removal.
|
||||
w.sweep(t0 + Duration::from_secs(61));
|
||||
assert_eq!(api.calls(), vec![("add".into(), "9.9.9.9".into())]);
|
||||
|
||||
// Only the extended deadline removes it, and only once.
|
||||
w.sweep(t0 + Duration::from_secs(121));
|
||||
assert_eq!(
|
||||
api.calls(),
|
||||
vec![
|
||||
("add".into(), "9.9.9.9".into()),
|
||||
("remove".into(), "9.9.9.9".into()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_ips_are_tracked_independently() {
|
||||
let api = MockApi::default();
|
||||
let mut w = BanWorker::new(api.clone());
|
||||
let t0 = Instant::now();
|
||||
|
||||
w.on_ban("1.1.1.1".into(), t0 + Duration::from_secs(30), 0);
|
||||
w.on_ban("2.2.2.2".into(), t0 + Duration::from_secs(90), 0);
|
||||
|
||||
w.sweep(t0 + Duration::from_secs(31)); // only the first expired
|
||||
assert_eq!(
|
||||
api.calls(),
|
||||
vec![
|
||||
("add".into(), "1.1.1.1".into()),
|
||||
("add".into(), "2.2.2.2".into()),
|
||||
("remove".into(), "1.1.1.1".into()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_removes_stale_and_reschedules_live_without_readding() {
|
||||
let api = MockApi::default();
|
||||
// Simulate the list left behind by a prior process: one ban already
|
||||
// past its expiry, one still live.
|
||||
*api.existing.lock().unwrap() = vec![
|
||||
("5.5.5.5".into(), 1_000), // expired as of now_unix = 2_000
|
||||
("6.6.6.6".into(), 3_000), // still 1_000s to go
|
||||
];
|
||||
let mut w = BanWorker::new(api.clone());
|
||||
|
||||
w.reconcile(2_000);
|
||||
// The stale ban's lost removal is recovered immediately; the live ban is
|
||||
// neither re-added (it's already in the list) nor removed yet.
|
||||
assert_eq!(api.calls(), vec![("remove".into(), "5.5.5.5".into())]);
|
||||
|
||||
// The live ban is scheduled, so once its (rescheduled) deadline passes it
|
||||
// is removed — and never re-added.
|
||||
w.sweep(Instant::now() + Duration::from_secs(2_000));
|
||||
assert_eq!(
|
||||
api.calls(),
|
||||
vec![
|
||||
("remove".into(), "5.5.5.5".into()),
|
||||
("remove".into(), "6.6.6.6".into()),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
//! Reusable per-IP strike counter + temporary IP-ban, shared by write-path
|
||||
//! filters that want to escalate repeat offenders into a short block.
|
||||
//!
|
||||
//! A filter embeds a [`BanTracker`] with `#[serde(flatten)]`, so its
|
||||
//! `ban_after` / `ban_duration_secs` / `ban_message` knobs live at the filter's
|
||||
//! own config table level. The tracker keeps the state; the *filter* decides
|
||||
//! what a "strike" is (a rate-limit hit, a content match, …) and what action to
|
||||
//! return while banned (a visible `Reject`, a stealth `ShadowReject`, …).
|
||||
//!
|
||||
//! Two streak policies fall out of which methods a filter calls:
|
||||
//!
|
||||
//! * **Consecutive** (e.g. `ratelimit`): call [`reset`](BanTracker::reset) on
|
||||
//! every clean event, so only an unbroken run of violations bans.
|
||||
//! * **Cumulative** (e.g. `content`): never call `reset`, so violations accrue
|
||||
//! across a session until they cross the threshold.
|
||||
//!
|
||||
//! When `ban_after` is unset the tracker is inert and stores no per-IP state, so
|
||||
//! a filter that leaves banning unconfigured behaves exactly as it did before.
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Default ban length once an IP crosses the threshold: one hour.
|
||||
const DEFAULT_BAN_DURATION_SECS: u64 = 3600;
|
||||
|
||||
/// The `ban_*` knobs, deserialized flat into the embedding filter's config.
|
||||
#[derive(Deserialize, Default)]
|
||||
struct BanConfig {
|
||||
/// IP-ban an offender after this many strikes. `None` disables banning.
|
||||
ban_after: Option<i32>,
|
||||
/// How long a ban lasts, in seconds. Defaults to [`DEFAULT_BAN_DURATION_SECS`].
|
||||
ban_duration_secs: Option<u64>,
|
||||
/// Message returned to a banned IP (filters that shadow-reject may ignore it).
|
||||
ban_message: Option<String>,
|
||||
}
|
||||
|
||||
struct BanState {
|
||||
strikes: i32,
|
||||
banned_until: Option<Instant>,
|
||||
}
|
||||
|
||||
/// Per-IP strike tracking plus the active-ban set. See the [module docs](self).
|
||||
#[derive(Default)]
|
||||
pub struct BanTracker {
|
||||
config: BanConfig,
|
||||
ips: HashMap<String, BanState>,
|
||||
}
|
||||
|
||||
// Deserialized via the flattened `BanConfig`; the state map always starts empty.
|
||||
impl<'de> Deserialize<'de> for BanTracker {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Ok(BanTracker {
|
||||
config: BanConfig::deserialize(deserializer)?,
|
||||
ips: HashMap::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BanTracker {
|
||||
/// The message handed to a banned IP, or a generic fallback.
|
||||
pub fn message(&self) -> &str {
|
||||
self.config
|
||||
.ban_message
|
||||
.as_deref()
|
||||
.unwrap_or("banned: too many violations, try again later")
|
||||
}
|
||||
|
||||
/// Whether `ip` is under an active ban. An expired ban is cleared here, along
|
||||
/// with its strike streak, so the next event starts fresh.
|
||||
pub fn is_banned(&mut self, ip: &str, now: Instant) -> bool {
|
||||
let Some(state) = self.ips.get_mut(ip) else {
|
||||
return false;
|
||||
};
|
||||
match state.banned_until {
|
||||
Some(until) if now < until => true,
|
||||
Some(_) => {
|
||||
state.banned_until = None;
|
||||
state.strikes = 0;
|
||||
false
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a violation for `ip`. Returns `true` if this strike crossed
|
||||
/// `ban_after` and the IP is now banned. A no-op returning `false` when
|
||||
/// banning is disabled, so callers keep zero per-IP state in that case.
|
||||
pub fn strike(&mut self, ip: &str, now: Instant) -> bool {
|
||||
let Some(ban_after) = self.config.ban_after else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let state = self.ips.entry(ip.to_owned()).or_insert(BanState {
|
||||
strikes: 0,
|
||||
banned_until: None,
|
||||
});
|
||||
state.strikes += 1;
|
||||
|
||||
if state.strikes >= ban_after {
|
||||
let secs = self
|
||||
.config
|
||||
.ban_duration_secs
|
||||
.unwrap_or(DEFAULT_BAN_DURATION_SECS);
|
||||
state.banned_until = Some(now + Duration::from_secs(secs));
|
||||
// Escalate to the edge if a Cloudflare banner is configured. This is
|
||||
// the single choke point every write-path filter's ban flows through,
|
||||
// so both ratelimit and content get edge-banning for free. No-op
|
||||
// unless the `cloudflare` feature is built and `[cloudflare]` is set.
|
||||
#[cfg(feature = "cloudflare")]
|
||||
crate::cloudflare::edge_ban(ip, Duration::from_secs(secs));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear `ip`'s strike streak after a clean event (the "consecutive" policy).
|
||||
/// Filters with cumulative semantics simply never call this.
|
||||
pub fn reset(&mut self, ip: &str) {
|
||||
if let Some(state) = self.ips.get_mut(ip) {
|
||||
state.strikes = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use ipnetwork::IpNetwork;
|
||||
use serde::Deserialize;
|
||||
use std::net::IpAddr;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct BlacklistConfig {
|
||||
pub pubkeys: Option<Vec<String>>,
|
||||
pub ips: Option<Vec<String>>,
|
||||
pub cidrs: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Blacklist {
|
||||
pubkeys: Option<Vec<String>>,
|
||||
ips: Option<Vec<String>>,
|
||||
cidrs: Option<Vec<IpNetwork>>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Blacklist {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let config = BlacklistConfig::deserialize(deserializer)?;
|
||||
Ok(Blacklist {
|
||||
pubkeys: config.pubkeys,
|
||||
ips: config.ips,
|
||||
cidrs: config.cidrs.map(|cidrs| {
|
||||
cidrs
|
||||
.into_iter()
|
||||
.filter_map(|s| IpNetwork::from_str(&s).ok())
|
||||
.collect()
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Blacklist {
|
||||
fn is_ip_blocked(&self, ip: &str) -> bool {
|
||||
if let Some(ips) = &self.ips {
|
||||
if ips.contains(&ip.to_string()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(addr) = IpAddr::from_str(ip) {
|
||||
if let Some(cidrs) = &self.cidrs {
|
||||
if cidrs.iter().any(|network| network.contains(addr)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl NoteFilter for Blacklist {
|
||||
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
|
||||
let reject_message = "blocked: pubkey/ip is blacklisted".to_string();
|
||||
|
||||
if let Some(pubkeys) = &self.pubkeys {
|
||||
if pubkeys.contains(&msg.event.pubkey) {
|
||||
return OutputMessage::new(
|
||||
msg.event.id.clone(),
|
||||
Action::Reject,
|
||||
Some(reject_message),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if self.is_ip_blocked(&msg.source_info) {
|
||||
return OutputMessage::new(msg.event.id.clone(), Action::Reject, Some(reject_message));
|
||||
}
|
||||
|
||||
OutputMessage::new(msg.event.id.clone(), Action::Accept, None)
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"blacklist"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
use crate::filters::ban::BanTracker;
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::Deserialize;
|
||||
use std::time::Instant;
|
||||
use unicode_security::skeleton;
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct Content {
|
||||
filters: Vec<String>,
|
||||
|
||||
/// Confusables-normalized, case-folded copies of `filters`, built lazily on
|
||||
/// first use. Matching against these catches homoglyph spoofs — e.g. Cyrillic
|
||||
/// `а`/`А` (U+0430/U+0410) standing in for Latin `a`/`A` in "Damus Airdrop"
|
||||
/// spam — that a raw byte-wise `contains` check silently misses.
|
||||
#[serde(skip)]
|
||||
normalized: Option<Vec<String>>,
|
||||
|
||||
/// IP-ban repeat offenders. Content violations accrue *cumulatively* per IP
|
||||
/// (a matching note never resets the count); once they cross `ban_after`
|
||||
/// every note from that IP is shadow-rejected until the ban expires. See
|
||||
/// [`BanTracker`]. Flattened so `ban_after` etc. sit at this filter's level.
|
||||
#[serde(flatten)]
|
||||
ban: BanTracker,
|
||||
}
|
||||
|
||||
/// Fold a string to its UTS #39 confusables skeleton, case-folded, so that
|
||||
/// visually-identical strings built from different codepoints compare equal.
|
||||
/// Case is folded both before and after skeletonizing: the confusable prototypes
|
||||
/// are not case-stable (uppercase `А` and lowercase `а` skeletonize differently),
|
||||
/// so lowercasing up front lines the inputs up before the skeleton is taken.
|
||||
fn normalize(s: &str) -> String {
|
||||
skeleton(&s.to_lowercase()).collect::<String>().to_lowercase()
|
||||
}
|
||||
|
||||
impl NoteFilter for Content {
|
||||
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
|
||||
let now = Instant::now();
|
||||
|
||||
// A banned IP has everything silently dropped, not just matching notes —
|
||||
// shadow-rejected to keep the ban invisible to the offender, like a
|
||||
// content match itself.
|
||||
if self.ban.is_banned(&msg.source_info, now) {
|
||||
return OutputMessage::new(msg.event.id.clone(), Action::ShadowReject, None);
|
||||
}
|
||||
|
||||
let matched = {
|
||||
let normalized = self
|
||||
.normalized
|
||||
.get_or_insert_with(|| self.filters.iter().map(|f| normalize(f)).collect());
|
||||
let content = normalize(&msg.event.content);
|
||||
normalized.iter().any(|filter| content.contains(filter))
|
||||
};
|
||||
|
||||
if matched {
|
||||
// Count the violation (may trip a ban for next time); either way this
|
||||
// note is shadow-rejected.
|
||||
self.ban.strike(&msg.source_info, now);
|
||||
return OutputMessage::new(msg.event.id.clone(), Action::ShadowReject, None);
|
||||
}
|
||||
|
||||
OutputMessage::new(msg.event.id.clone(), Action::Accept, None)
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"content"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Note;
|
||||
|
||||
fn msg(id: &str, ip: &str, content: &str) -> InputMessage {
|
||||
InputMessage {
|
||||
message_type: "new".to_string(),
|
||||
event: Note {
|
||||
id: id.to_string(),
|
||||
pubkey: "pk".to_string(),
|
||||
created_at: 0,
|
||||
kind: 1,
|
||||
tags: vec![],
|
||||
content: content.to_string(),
|
||||
sig: "sig".to_string(),
|
||||
},
|
||||
received_at: 0,
|
||||
source_type: "IP4".to_string(),
|
||||
source_info: ip.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn content(toml_cfg: &str) -> Content {
|
||||
toml::from_str(toml_cfg).expect("valid content config")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_shadow_reject_without_banning() {
|
||||
let mut c = content("filters = [\"spam\"]\n");
|
||||
assert_eq!(
|
||||
c.filter_note(&msg("e1", "1.2.3.4", "buy spam now")).action,
|
||||
Action::ShadowReject
|
||||
);
|
||||
// No ban configured, so a clean note from the same IP still passes.
|
||||
assert_eq!(
|
||||
c.filter_note(&msg("e2", "1.2.3.4", "hello")).action,
|
||||
Action::Accept
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bans_after_cumulative_violations() {
|
||||
let mut c = content("filters = [\"spam\"]\nban_after = 3\n");
|
||||
|
||||
// Clean notes interleaved with spam must NOT reset the streak.
|
||||
assert_eq!(
|
||||
c.filter_note(&msg("e1", "9.9.9.9", "spam")).action,
|
||||
Action::ShadowReject
|
||||
);
|
||||
assert_eq!(
|
||||
c.filter_note(&msg("e2", "9.9.9.9", "hello")).action,
|
||||
Action::Accept
|
||||
);
|
||||
assert_eq!(
|
||||
c.filter_note(&msg("e3", "9.9.9.9", "spam")).action,
|
||||
Action::ShadowReject
|
||||
);
|
||||
// Third violation trips the ban.
|
||||
assert_eq!(
|
||||
c.filter_note(&msg("e4", "9.9.9.9", "spam")).action,
|
||||
Action::ShadowReject
|
||||
);
|
||||
|
||||
// Now banned: even a perfectly clean note is silently dropped.
|
||||
assert_eq!(
|
||||
c.filter_note(&msg("e5", "9.9.9.9", "totally fine")).action,
|
||||
Action::ShadowReject
|
||||
);
|
||||
// A different IP is unaffected.
|
||||
assert_eq!(
|
||||
c.filter_note(&msg("e6", "8.8.8.8", "totally fine")).action,
|
||||
Action::Accept
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
use serde::Deserialize;
|
||||
use crate::{Note, Action, NoteFilter, InputMessage, OutputMessage};
|
||||
use crate::{Action, InputMessage, Note, NoteFilter, OutputMessage};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use tokio::sync::mpsc::{self, Sender, Receiver};
|
||||
use log::{debug, error, info};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use tokio::sync::mpsc::{self, Receiver, Sender};
|
||||
use tokio::time::{sleep, timeout, Duration};
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::WebSocketStream;
|
||||
use tokio::time::{sleep, timeout, Duration};
|
||||
use serde_json::json;
|
||||
use log::{error, info, debug};
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
pub struct Forwarder {
|
||||
@@ -21,7 +21,9 @@ pub struct Forwarder {
|
||||
channel: Option<Sender<Note>>,
|
||||
}
|
||||
|
||||
async fn client_reconnect(relay: &str) -> WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>> {
|
||||
async fn client_reconnect(
|
||||
relay: &str,
|
||||
) -> WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>> {
|
||||
loop {
|
||||
match connect_async(relay).await {
|
||||
Err(e) => {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
mod ban;
|
||||
mod blacklist;
|
||||
mod content;
|
||||
mod kinds;
|
||||
mod protected_events;
|
||||
mod ratelimit;
|
||||
@@ -6,6 +9,11 @@ mod whitelist;
|
||||
#[cfg(feature = "forwarder")]
|
||||
mod forwarder;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
mod nscript;
|
||||
|
||||
pub use blacklist::Blacklist;
|
||||
pub use content::Content;
|
||||
pub use kinds::Kinds;
|
||||
pub use protected_events::ProtectedEvents;
|
||||
pub use ratelimit::RateLimit;
|
||||
@@ -13,3 +21,6 @@ pub use whitelist::Whitelist;
|
||||
|
||||
#[cfg(feature = "forwarder")]
|
||||
pub use forwarder::Forwarder;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
pub use nscript::NScript;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
use crate::nscript::{Runtime, Verdict};
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Runs a user-supplied WASM guest as a note filter via the accessor ABI.
|
||||
///
|
||||
/// For the Phase 0 spike the guest is loaded from a local path and the owner
|
||||
/// context comes from config; a later phase sources both from a signed
|
||||
/// submission event on the relay.
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct NScript {
|
||||
/// Path to the compiled guest `.wasm`.
|
||||
module: String,
|
||||
|
||||
/// Hex pubkey the script is scoped to (its "inbox owner").
|
||||
#[serde(default)]
|
||||
owner: Option<String>,
|
||||
|
||||
/// Hex pubkeys the owner follows (backs `is_following`).
|
||||
#[serde(default)]
|
||||
follows: Vec<String>,
|
||||
|
||||
/// Message returned to the client on reject.
|
||||
#[serde(default)]
|
||||
message: Option<String>,
|
||||
|
||||
/// Compiled runtime, built lazily on first note.
|
||||
#[serde(skip)]
|
||||
runtime: Option<Runtime>,
|
||||
}
|
||||
|
||||
impl NoteFilter for NScript {
|
||||
fn name(&self) -> &'static str {
|
||||
"nscript"
|
||||
}
|
||||
|
||||
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
|
||||
let id = msg.event.id.clone();
|
||||
|
||||
if self.runtime.is_none() {
|
||||
match Runtime::load(&self.module, &self.owner, &self.follows) {
|
||||
Ok(rt) => self.runtime = Some(rt),
|
||||
Err(e) => {
|
||||
// Fail open: a broken filter shouldn't block all writes.
|
||||
log::error!("nscript: failed to load {}: {}", self.module, e);
|
||||
return OutputMessage::new(id, Action::Accept, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let rt = self.runtime.as_ref().expect("runtime just loaded");
|
||||
match rt.run(&msg.event) {
|
||||
Ok(Verdict::Accept) => OutputMessage::new(id, Action::Accept, None),
|
||||
Ok(Verdict::Reject) => OutputMessage::new(id, Action::Reject, self.message.clone()),
|
||||
Ok(Verdict::ShadowReject) => OutputMessage::new(id, Action::ShadowReject, None),
|
||||
Err(e) => {
|
||||
// Fail open on guest trap / resource exhaustion.
|
||||
log::error!("nscript: guest error: {}", e);
|
||||
OutputMessage::new(id, Action::Accept, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+134
-3
@@ -1,3 +1,4 @@
|
||||
use crate::filters::ban::BanTracker;
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
@@ -12,6 +13,13 @@ pub struct Tokens {
|
||||
pub struct RateLimit {
|
||||
pub posts_per_minute: i32,
|
||||
pub whitelist: Option<Vec<String>>,
|
||||
pub message: Option<String>,
|
||||
|
||||
/// IP-ban persistent offenders. `ban_after` *consecutive* rate-limit
|
||||
/// rejections (a streak any accepted post resets) trips a ban; see
|
||||
/// [`BanTracker`]. Flattened so `ban_after` etc. sit at this filter's level.
|
||||
#[serde(flatten)]
|
||||
pub ban: BanTracker,
|
||||
|
||||
#[serde(skip)]
|
||||
pub sources: HashMap<String, Tokens>,
|
||||
@@ -29,11 +37,23 @@ impl NoteFilter for RateLimit {
|
||||
}
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
|
||||
// Enforce an active IP-ban before touching the token bucket, so a banned
|
||||
// IP cannot refill or reset anything by continuing to hammer us.
|
||||
if self.ban.is_banned(&msg.source_info, now) {
|
||||
return OutputMessage::new(
|
||||
msg.event.id.clone(),
|
||||
Action::Reject,
|
||||
Some(self.ban.message().to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
if !self.sources.contains_key(&msg.source_info) {
|
||||
self.sources.insert(
|
||||
msg.source_info.to_owned(),
|
||||
Tokens {
|
||||
last_post: Instant::now(),
|
||||
last_post: now,
|
||||
tokens: self.posts_per_minute,
|
||||
},
|
||||
);
|
||||
@@ -41,7 +61,6 @@ impl NoteFilter for RateLimit {
|
||||
}
|
||||
|
||||
let entry = self.sources.get_mut(&msg.source_info).expect("impossiburu");
|
||||
let now = Instant::now();
|
||||
let mut diff = now - entry.last_post;
|
||||
|
||||
let min = Duration::from_secs(60);
|
||||
@@ -62,14 +81,126 @@ impl NoteFilter for RateLimit {
|
||||
}
|
||||
|
||||
if entry.tokens == 0 {
|
||||
// Persistent offender: escalate a streak of rate-limit hits into an
|
||||
// IP-ban once it crosses the configured threshold.
|
||||
if self.ban.strike(&msg.source_info, now) {
|
||||
return OutputMessage::new(
|
||||
msg.event.id.clone(),
|
||||
Action::Reject,
|
||||
Some(self.ban.message().to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
let message = self
|
||||
.message
|
||||
.as_deref()
|
||||
.unwrap_or("rate-limited: you are noting too much");
|
||||
|
||||
return OutputMessage::new(
|
||||
msg.event.id.clone(),
|
||||
Action::Reject,
|
||||
Some("rate-limited: you are noting too much".to_string()),
|
||||
Some(message.to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
entry.last_post = now;
|
||||
// A successful post breaks the rate-limit streak.
|
||||
self.ban.reset(&msg.source_info);
|
||||
OutputMessage::new(msg.event.id.clone(), Action::Accept, None)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Note;
|
||||
|
||||
fn msg(id: &str, ip: &str) -> InputMessage {
|
||||
InputMessage {
|
||||
message_type: "new".to_string(),
|
||||
event: Note {
|
||||
id: id.to_string(),
|
||||
pubkey: "pk".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 ratelimit(toml_cfg: &str) -> RateLimit {
|
||||
toml::from_str(toml_cfg).expect("valid ratelimit config")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bans_after_consecutive_strikes() {
|
||||
let mut rl = ratelimit("posts_per_minute = 1\nban_after = 3\n");
|
||||
|
||||
// First post seeds the bucket and is accepted.
|
||||
assert_eq!(rl.filter_note(&msg("e1", "1.2.3.4")).action, Action::Accept);
|
||||
|
||||
// The next three back-to-back posts are all rate-limited. The third one
|
||||
// trips `ban_after` and flips into a ban.
|
||||
let r2 = rl.filter_note(&msg("e2", "1.2.3.4"));
|
||||
let r3 = rl.filter_note(&msg("e3", "1.2.3.4"));
|
||||
let r4 = rl.filter_note(&msg("e4", "1.2.3.4"));
|
||||
assert_eq!(r2.action, Action::Reject);
|
||||
assert!(!r2.msg.unwrap().contains("banned"));
|
||||
assert_eq!(r3.action, Action::Reject);
|
||||
assert_eq!(r4.action, Action::Reject);
|
||||
assert!(r4.msg.unwrap().contains("banned"));
|
||||
|
||||
// Once banned, further posts are rejected as banned regardless.
|
||||
let r5 = rl.filter_note(&msg("e5", "1.2.3.4"));
|
||||
assert_eq!(r5.action, Action::Reject);
|
||||
assert!(r5.msg.unwrap().contains("banned"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_ban_when_unconfigured() {
|
||||
let mut rl = ratelimit("posts_per_minute = 1\n");
|
||||
|
||||
assert_eq!(rl.filter_note(&msg("e1", "1.2.3.4")).action, Action::Accept);
|
||||
// Without `ban_after`, persistent hammering only ever rate-limits.
|
||||
for i in 0..10 {
|
||||
let r = rl.filter_note(&msg(&format!("e{i}"), "1.2.3.4"));
|
||||
assert_eq!(r.action, Action::Reject);
|
||||
assert!(!r.msg.unwrap().contains("banned"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitelisted_ip_is_never_banned() {
|
||||
let mut rl = ratelimit("posts_per_minute = 1\nban_after = 2\nwhitelist = [\"1.2.3.4\"]\n");
|
||||
|
||||
for i in 0..10 {
|
||||
let r = rl.filter_note(&msg(&format!("e{i}"), "1.2.3.4"));
|
||||
assert_eq!(r.action, Action::Accept);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_successful_post_resets_the_streak() {
|
||||
let mut rl = ratelimit("posts_per_minute = 2\nban_after = 2\n");
|
||||
|
||||
// Seed + drain, then one rate-limit rejection (strike 1).
|
||||
assert_eq!(rl.filter_note(&msg("e1", "5.6.7.8")).action, Action::Accept);
|
||||
assert_eq!(rl.filter_note(&msg("e2", "5.6.7.8")).action, Action::Accept);
|
||||
assert_eq!(rl.filter_note(&msg("e3", "5.6.7.8")).action, Action::Reject);
|
||||
|
||||
// Refill the bucket so the next post is accepted, resetting the streak.
|
||||
rl.sources.get_mut("5.6.7.8").unwrap().last_post = Instant::now() - Duration::from_secs(120);
|
||||
assert_eq!(rl.filter_note(&msg("e4", "5.6.7.8")).action, Action::Accept);
|
||||
|
||||
// A fresh streak now needs the full `ban_after` again — the next lone
|
||||
// rejection must NOT ban.
|
||||
let r = rl.filter_note(&msg("e5", "5.6.7.8"));
|
||||
assert_eq!(r.action, Action::Reject);
|
||||
assert!(!r.msg.unwrap().contains("banned"));
|
||||
}
|
||||
}
|
||||
|
||||
+18
@@ -1,6 +1,24 @@
|
||||
pub mod filters;
|
||||
mod messages;
|
||||
mod note_filter;
|
||||
mod read_filter;
|
||||
pub mod readfilters;
|
||||
pub mod readmsg;
|
||||
pub mod readpolicy;
|
||||
|
||||
#[cfg(feature = "cloudflare")]
|
||||
pub mod cloudflare;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
pub mod nscript;
|
||||
|
||||
pub use messages::{Action, InputMessage, OutputMessage};
|
||||
pub use note_filter::{Note, NoteFilter};
|
||||
pub use read_filter::{Admission, ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
|
||||
/// Path to the config file, from `$NOTEGUARD_CONFIG` or defaulting to
|
||||
/// `noteguard.toml`. Shared by the write loop and the read loop so both halves
|
||||
/// of the same deployment always read the same file.
|
||||
pub fn config_path() -> String {
|
||||
std::env::var("NOTEGUARD_CONFIG").unwrap_or_else(|_| "noteguard.toml".to_string())
|
||||
}
|
||||
|
||||
+592
-43
@@ -1,19 +1,29 @@
|
||||
use noteguard::filters::{Kinds, ProtectedEvents, RateLimit, Whitelist};
|
||||
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::{self, BufRead, Read, Write};
|
||||
use log::info;
|
||||
use std::io;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Config {
|
||||
pipeline: Vec<String>,
|
||||
filters: HashMap<String, toml::Value>,
|
||||
|
||||
/// Shared Cloudflare edge-ban config, consumed once at startup to arm the
|
||||
/// process-global banner every `BanTracker` escalates to. Ignored when the
|
||||
/// `cloudflare` feature is not built.
|
||||
#[cfg(feature = "cloudflare")]
|
||||
#[serde(default)]
|
||||
cloudflare: Option<noteguard::cloudflare::CloudflareConfig>,
|
||||
}
|
||||
|
||||
type ConstructFilter = Box<fn(toml::Value) -> Result<Box<dyn NoteFilter>, toml::de::Error>>;
|
||||
@@ -47,11 +57,16 @@ impl 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
|
||||
@@ -105,26 +120,254 @@ impl Noteguard {
|
||||
#[cfg(feature = "forwarder")]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
noteguard();
|
||||
dispatch();
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "forwarder"))]
|
||||
fn main() {
|
||||
noteguard();
|
||||
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(),
|
||||
Some("dump-buckets") => dump_buckets(),
|
||||
_ => noteguard(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `noteguard dump-buckets [--json] [--capacity BYTES] [--sort tokens|age|key]
|
||||
/// [--reverse] [PATH]` — a read-only operator peek into the shared per-IP
|
||||
/// read-bandwidth byte-bucket table (see [`noteguard::readfilters::dump`]).
|
||||
/// Prints one row per OCCUPIED slot — the key (client IP), bytes remaining, and
|
||||
/// how long ago the slot last refilled — sorted most-throttled first by default
|
||||
/// (`--sort`/`--reverse` to reorder). With `--capacity` it also shows each
|
||||
/// bucket refilled to now and how full that leaves it. Never mutates the file.
|
||||
fn dump_buckets() {
|
||||
use std::io::Write;
|
||||
|
||||
// One minute in nanoseconds — the refill window, mirrored from the shm
|
||||
// module so `--capacity` can project a bucket's balance to now.
|
||||
const MINUTE_NS: f64 = 60.0 * 1_000_000_000.0;
|
||||
|
||||
// Parse: an optional `--json`, `--capacity BYTES`, `--sort KEY`, `--reverse`,
|
||||
// and an optional trailing PATH (defaults to the tmpfs file the filter uses).
|
||||
let mut json = false;
|
||||
let mut capacity: Option<f64> = None;
|
||||
let mut sort = "tokens".to_string();
|
||||
let mut reverse = false;
|
||||
let mut path: Option<String> = None;
|
||||
let mut args = std::env::args().skip(2);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--json" => json = true,
|
||||
"--reverse" => reverse = true,
|
||||
"--capacity" => {
|
||||
capacity = match args.next().and_then(|v| v.parse::<f64>().ok()) {
|
||||
Some(c) if c > 0.0 => Some(c),
|
||||
_ => {
|
||||
eprintln!("dump-buckets: --capacity needs a positive number of bytes");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
}
|
||||
"--sort" => {
|
||||
sort = match args.next().as_deref() {
|
||||
Some(k @ ("tokens" | "age" | "key")) => k.to_string(),
|
||||
_ => {
|
||||
eprintln!("dump-buckets: --sort needs one of: tokens, age, key");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
}
|
||||
"-h" | "--help" => {
|
||||
println!(
|
||||
"usage: noteguard dump-buckets [--json] [--capacity BYTES] \
|
||||
[--sort tokens|age|key] [--reverse] [PATH]"
|
||||
);
|
||||
println!(
|
||||
" inspect the shared read-bandwidth byte buckets (default {})",
|
||||
noteguard::readfilters::DEFAULT_PATH
|
||||
);
|
||||
println!(
|
||||
" --sort tokens bytes remaining, fewest first (default; most-throttled)"
|
||||
);
|
||||
println!(" --sort age last-refill age, most-recently-active first");
|
||||
println!(" --sort key client IP/key, lexical");
|
||||
println!(" --reverse flip the sort direction");
|
||||
return;
|
||||
}
|
||||
other if other.starts_with('-') => {
|
||||
eprintln!("dump-buckets: unknown flag {other}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
other => {
|
||||
if path.replace(other.to_string()).is_some() {
|
||||
eprintln!("dump-buckets: only one PATH may be given");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let path = path.unwrap_or_else(|| noteguard::readfilters::DEFAULT_PATH.to_string());
|
||||
|
||||
let dump = match noteguard::readfilters::dump(&path) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("dump-buckets: cannot read {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
// Age in nanoseconds against the clock `dump` captured; negative means a
|
||||
// last_refill in the future (stale across a reboot — the monotonic clock
|
||||
// reset), which the read filter treats as fully stale (a full bucket).
|
||||
let age_ns =
|
||||
|e: ¬eguard::readfilters::BucketEntry| dump.now_ns as i128 - e.last_refill_ns as i128;
|
||||
|
||||
// Project a bucket's balance to now (same shape as the filter's refill:
|
||||
// elapsed/60 of a minute's capacity, clamped to a minute and capped; a
|
||||
// future timestamp resets to full). Only meaningful with a known capacity.
|
||||
let refilled = |e: ¬eguard::readfilters::BucketEntry, cap: f64| -> f64 {
|
||||
let age = age_ns(e);
|
||||
if age < 0 {
|
||||
return cap;
|
||||
}
|
||||
let elapsed = (age as f64).min(MINUTE_NS);
|
||||
(e.tokens + (elapsed / MINUTE_NS) * cap).min(cap)
|
||||
};
|
||||
|
||||
// Sort per `--sort`. Each key's default direction is the one an operator
|
||||
// usually wants at the top; `--reverse` flips it. `tokens` (the default)
|
||||
// ascends so the most-throttled IP leads; `age` ascends so the freshest
|
||||
// (most-recently-active) leads; `key` is plain lexical.
|
||||
let mut entries = dump.entries;
|
||||
entries.sort_by(|a, b| {
|
||||
let ord = match sort.as_str() {
|
||||
"age" => age_ns(a).cmp(&age_ns(b)),
|
||||
"key" => a.key.cmp(&b.key),
|
||||
// "tokens" (default): fewest bytes remaining first.
|
||||
_ => a
|
||||
.tokens
|
||||
.partial_cmp(&b.tokens)
|
||||
.unwrap_or(std::cmp::Ordering::Equal),
|
||||
};
|
||||
if reverse {
|
||||
ord.reverse()
|
||||
} else {
|
||||
ord
|
||||
}
|
||||
});
|
||||
|
||||
if json {
|
||||
// Hand-roll the JSON so we don't need a Serialize impl on the shm types.
|
||||
let mut items = Vec::with_capacity(entries.len());
|
||||
for e in &entries {
|
||||
let mut obj = serde_json::json!({
|
||||
"key": e.key,
|
||||
"tokens": e.tokens,
|
||||
"last_refill_ns": e.last_refill_ns,
|
||||
"age_seconds": age_ns(e) as f64 / 1e9,
|
||||
});
|
||||
if let Some(cap) = capacity {
|
||||
let r = refilled(e, cap);
|
||||
obj["refilled_tokens"] = serde_json::json!(r);
|
||||
obj["percent_full"] = serde_json::json!(r / cap * 100.0);
|
||||
}
|
||||
items.push(obj);
|
||||
}
|
||||
let out = serde_json::json!({
|
||||
"path": path,
|
||||
"slot_count": dump.slot_count,
|
||||
"occupied": entries.len(),
|
||||
"now_ns": dump.now_ns,
|
||||
"capacity": capacity,
|
||||
"buckets": items,
|
||||
});
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&out).expect("dump JSON serializes")
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Text output. Buffer to stdout so a huge table isn't line-flushed.
|
||||
let stdout = io::stdout();
|
||||
let mut out = io::BufWriter::new(stdout.lock());
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}: slot_count={} occupied={}",
|
||||
path,
|
||||
dump.slot_count,
|
||||
entries.len()
|
||||
);
|
||||
if let Some(cap) = capacity {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{:<46} {:>16} {:>10} {:>16} {:>7}",
|
||||
"KEY", "BYTES_REMAINING", "AGE", "REFILLED_NOW", "%FULL"
|
||||
);
|
||||
for e in &entries {
|
||||
let r = refilled(e, cap);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{:<46} {:>16.0} {:>10} {:>16.0} {:>6.1}%",
|
||||
e.key,
|
||||
e.tokens,
|
||||
fmt_age(age_ns(e)),
|
||||
r,
|
||||
r / cap * 100.0,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{:<46} {:>16} {:>10}",
|
||||
"KEY", "BYTES_REMAINING", "AGE"
|
||||
);
|
||||
for e in &entries {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{:<46} {:>16.0} {:>10}",
|
||||
e.key,
|
||||
e.tokens,
|
||||
fmt_age(age_ns(e)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a bucket age (nanoseconds; may be negative if stale across a reboot)
|
||||
/// as a short human string like `4.2s` or `stale`.
|
||||
fn fmt_age(age_ns: i128) -> String {
|
||||
if age_ns < 0 {
|
||||
return "stale".to_string();
|
||||
}
|
||||
let secs = age_ns as f64 / 1e9;
|
||||
if secs < 60.0 {
|
||||
format!("{secs:.1}s")
|
||||
} else {
|
||||
format!("{:.1}m", secs / 60.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_output_message(msg: &OutputMessage) -> String {
|
||||
serde_json::to_string(msg).expect("OutputMessage should always serialize correctly")
|
||||
}
|
||||
|
||||
fn noteguard() {
|
||||
env_logger::init();
|
||||
info!("running noteguard");
|
||||
|
||||
let config_path = "noteguard.toml";
|
||||
let config_path = noteguard::config_path();
|
||||
let mut noteguard = Noteguard::new();
|
||||
|
||||
let config: Config = {
|
||||
let mut file = std::fs::File::open(config_path).expect("Failed to open config file");
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents)
|
||||
.expect("Failed to read config file");
|
||||
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")
|
||||
};
|
||||
|
||||
@@ -132,42 +375,348 @@ fn noteguard() {
|
||||
.load_config(&config)
|
||||
.expect("Expected filter config to be loaded ok");
|
||||
|
||||
// Arm the shared Cloudflare edge-banner before processing notes, so the very
|
||||
// first ban can escalate to the edge.
|
||||
#[cfg(feature = "cloudflare")]
|
||||
if let Some(cf) = config.cloudflare.clone() {
|
||||
noteguard::cloudflare::init(cf);
|
||||
}
|
||||
|
||||
let stdin = io::stdin();
|
||||
let stdout = io::stdout();
|
||||
let handle = stdout.lock();
|
||||
let mut writer = io::BufWriter::new(handle);
|
||||
|
||||
for line in stdin.lock().lines() {
|
||||
match line {
|
||||
Ok(input) => {
|
||||
let input_message: InputMessage = match serde_json::from_str(&input) {
|
||||
Ok(msg) => msg,
|
||||
Err(e) => {
|
||||
eprintln!("Failed to parse input: {}", e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if input_message.message_type != "new" {
|
||||
eprintln!("Unexpected request type");
|
||||
continue;
|
||||
}
|
||||
|
||||
let output_message = noteguard.run(input_message);
|
||||
|
||||
match serde_json::to_string(&output_message) {
|
||||
Ok(json) => {
|
||||
writeln!(writer, "{}", json).unwrap();
|
||||
writer.flush().unwrap();
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Failed to serialize output: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
for line in stdin.lines() {
|
||||
let line = match line {
|
||||
Ok(line) => line,
|
||||
Err(e) => {
|
||||
eprintln!("Failed to read line: {}", 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to build a mock "new" message carrying arbitrary note content.
|
||||
fn create_mock_content_message(content: &str) -> InputMessage {
|
||||
let mut msg = create_mock_input_message("content_event", "new", "mock_source_info");
|
||||
msg.event.content = content.to_string();
|
||||
msg
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_content_filter_homoglyph() {
|
||||
let mut noteguard = Noteguard::new();
|
||||
|
||||
let config: Config = toml::from_str(
|
||||
r#"
|
||||
pipeline = ["content"]
|
||||
[filters.content]
|
||||
filters = ["Damus Airdrop"]
|
||||
"#,
|
||||
)
|
||||
.expect("Failed to parse config");
|
||||
|
||||
noteguard
|
||||
.load_config(&config)
|
||||
.expect("Failed to load config");
|
||||
|
||||
// "Dаmus Аirdrop" — the 'а'/'А' are Cyrillic (U+0430/U+0410) homoglyphs,
|
||||
// the actual bytes seen in airdrop-scam spam. A raw substring check would
|
||||
// miss this; the confusables skeleton folds it back to "Damus Airdrop".
|
||||
let spam = "\u{1F680} D\u{0430}mus \u{0410}irdrop is open \u{00B7} \
|
||||
Check your claim https://tinyurl.com/damuslive/";
|
||||
assert_eq!(
|
||||
noteguard.run(create_mock_content_message(spam)).action,
|
||||
Action::ShadowReject
|
||||
);
|
||||
|
||||
// Plain ASCII match and a case variant both still get caught.
|
||||
assert_eq!(
|
||||
noteguard
|
||||
.run(create_mock_content_message("free Damus Airdrop here"))
|
||||
.action,
|
||||
Action::ShadowReject
|
||||
);
|
||||
assert_eq!(
|
||||
noteguard
|
||||
.run(create_mock_content_message("DAMUS AIRDROP!!!"))
|
||||
.action,
|
||||
Action::ShadowReject
|
||||
);
|
||||
|
||||
// An unrelated note is accepted.
|
||||
assert_eq!(
|
||||
noteguard
|
||||
.run(create_mock_content_message("gm nostr, lovely morning"))
|
||||
.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");
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ pub struct InputMessage {
|
||||
pub source_info: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Action {
|
||||
Accept,
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
use crate::{InputMessage, OutputMessage};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone)]
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
pub struct Note {
|
||||
pub id: String,
|
||||
pub pubkey: String,
|
||||
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
//! Phase 0 spike of the nscript wasm filter runtime.
|
||||
//!
|
||||
//! The ABI is an *accessor interface* over an opaque note handle: the guest
|
||||
//! never parses a note buffer, it calls imported `note_*` host functions to read
|
||||
//! fields. The note's byte format is therefore an implementation detail — today
|
||||
//! we back the accessors with the serde [`Note`]; later this becomes an
|
||||
//! `ndb_note` (with an optional `note_raw` zero-copy fast path). Owner-relative
|
||||
//! context (which npub the script is scoped to, and their follows) lives on the
|
||||
//! host, so guests stay reusable, owner-agnostic logic.
|
||||
|
||||
use crate::Note;
|
||||
use std::collections::HashSet;
|
||||
use wasmtime::{
|
||||
AsContext, AsContextMut, Caller, Config, Engine, Extern, Linker, Memory, Module, Store,
|
||||
StoreLimits, StoreLimitsBuilder,
|
||||
};
|
||||
|
||||
/// Guest action codes returned from `filter_note`.
|
||||
const ACT_REJECT: i32 = 1;
|
||||
const ACT_SHADOW_REJECT: i32 = 2;
|
||||
|
||||
/// CPU budget (wasm fuel units) per note. Bounds runaway guests deterministically.
|
||||
const DEFAULT_FUEL: u64 = 50_000_000;
|
||||
|
||||
/// Max guest linear memory (bytes).
|
||||
const MAX_MEMORY: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// The verdict a guest returns for a note.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Accept,
|
||||
Reject,
|
||||
ShadowReject,
|
||||
}
|
||||
|
||||
/// Per-invocation host state exposed to the accessor functions.
|
||||
struct HostState {
|
||||
note: Note,
|
||||
owner: Option<[u8; 32]>,
|
||||
follows: HashSet<[u8; 32]>,
|
||||
limits: StoreLimits,
|
||||
}
|
||||
|
||||
/// A compiled nscript module plus the owner context it runs under.
|
||||
pub struct Runtime {
|
||||
engine: Engine,
|
||||
module: Module,
|
||||
linker: Linker<HostState>,
|
||||
owner: Option<[u8; 32]>,
|
||||
follows: HashSet<[u8; 32]>,
|
||||
fuel: u64,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
/// Compile the guest at `path` and wire up the accessor ABI.
|
||||
///
|
||||
/// `owner` is the hex pubkey the script is scoped to and `follows` are hex
|
||||
/// pubkeys that owner follows (backing for `note_targets_owner` and
|
||||
/// `is_following`).
|
||||
pub fn load(path: &str, owner: &Option<String>, follows: &[String]) -> Result<Self, String> {
|
||||
let mut config = Config::new();
|
||||
config.consume_fuel(true);
|
||||
let engine = Engine::new(&config).map_err(|e| e.to_string())?;
|
||||
let module = Module::from_file(&engine, path).map_err(|e| e.to_string())?;
|
||||
|
||||
let mut linker = Linker::new(&engine);
|
||||
register_host_functions(&mut linker).map_err(|e| e.to_string())?;
|
||||
|
||||
let owner = owner.as_deref().and_then(hex32);
|
||||
let follows = follows.iter().filter_map(|h| hex32(h)).collect();
|
||||
|
||||
Ok(Runtime {
|
||||
engine,
|
||||
module,
|
||||
linker,
|
||||
owner,
|
||||
follows,
|
||||
fuel: DEFAULT_FUEL,
|
||||
})
|
||||
}
|
||||
|
||||
/// Re-scope this already-compiled guest to a different owner, without
|
||||
/// recompiling. `engine`, `module` and `linker` are owner-independent and
|
||||
/// internally reference-counted, so cloning them is cheap — a per-subscriber
|
||||
/// runtime costs no JIT compile or file read.
|
||||
pub fn rescope(&self, owner: &Option<String>, follows: &[String]) -> Self {
|
||||
Runtime {
|
||||
engine: self.engine.clone(),
|
||||
module: self.module.clone(),
|
||||
linker: self.linker.clone(),
|
||||
owner: owner.as_deref().and_then(hex32),
|
||||
follows: follows.iter().filter_map(|h| hex32(h)).collect(),
|
||||
fuel: self.fuel,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the guest filter against `note`, returning its verdict.
|
||||
///
|
||||
/// A fresh [`Store`] is created per note (the compiled module is reused), so
|
||||
/// guests get no state between invocations. Fuel and a memory cap bound the
|
||||
/// resources a single call may consume.
|
||||
pub fn run(&self, note: &Note) -> Result<Verdict, String> {
|
||||
let state = HostState {
|
||||
note: note.clone(),
|
||||
owner: self.owner,
|
||||
follows: self.follows.clone(),
|
||||
limits: StoreLimitsBuilder::new().memory_size(MAX_MEMORY).build(),
|
||||
};
|
||||
let mut store = Store::new(&self.engine, state);
|
||||
store.limiter(|s| &mut s.limits);
|
||||
store.set_fuel(self.fuel).map_err(|e| e.to_string())?;
|
||||
|
||||
let instance = self
|
||||
.linker
|
||||
.instantiate(&mut store, &self.module)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let func = instance
|
||||
.get_typed_func::<(), i32>(&mut store, "filter_note")
|
||||
.map_err(|e| e.to_string())?;
|
||||
let code = func.call(&mut store, ()).map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(match code {
|
||||
ACT_REJECT => Verdict::Reject,
|
||||
ACT_SHADOW_REJECT => Verdict::ShadowReject,
|
||||
_ => Verdict::Accept,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Register the accessor ABI on the linker under the `env` module.
|
||||
///
|
||||
/// Low-level accessors (`note_pubkey`, `note_id`, `note_kind`, `note_created_at`,
|
||||
/// `note_content`) expose raw note fields; higher-level owner-relative
|
||||
/// capabilities (`note_targets_owner`, `is_following`) keep owner context on the
|
||||
/// host. Variable-length reads use the `(out_ptr, cap) -> true_len` convention.
|
||||
fn register_host_functions(linker: &mut Linker<HostState>) -> Result<(), wasmtime::Error> {
|
||||
// note_pubkey(out_ptr) -> 32 : raw author pubkey bytes (0 on error)
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_pubkey",
|
||||
|mut caller: Caller<'_, HostState>, out: i32| -> i32 {
|
||||
let pk = match hex32(&caller.data().note.pubkey) {
|
||||
Some(p) => p,
|
||||
None => return 0,
|
||||
};
|
||||
write_bytes(&mut caller, out, &pk)
|
||||
},
|
||||
)?;
|
||||
|
||||
// note_id(out_ptr) -> 32 : raw event id bytes (0 on error)
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_id",
|
||||
|mut caller: Caller<'_, HostState>, out: i32| -> i32 {
|
||||
let id = match hex32(&caller.data().note.id) {
|
||||
Some(p) => p,
|
||||
None => return 0,
|
||||
};
|
||||
write_bytes(&mut caller, out, &id)
|
||||
},
|
||||
)?;
|
||||
|
||||
// note_kind() -> kind
|
||||
linker.func_wrap("env", "note_kind", |caller: Caller<'_, HostState>| -> i64 {
|
||||
caller.data().note.kind
|
||||
})?;
|
||||
|
||||
// note_created_at() -> unix seconds
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_created_at",
|
||||
|caller: Caller<'_, HostState>| -> i64 { caller.data().note.created_at },
|
||||
)?;
|
||||
|
||||
// note_content(out_ptr, cap) -> true_len : utf8 content, truncated to cap
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_content",
|
||||
|mut caller: Caller<'_, HostState>, out: i32, cap: i32| -> i32 {
|
||||
let content = caller.data().note.content.clone();
|
||||
let bytes = content.as_bytes();
|
||||
let n = bytes.len().min(cap.max(0) as usize);
|
||||
write_bytes(&mut caller, out, &bytes[..n]);
|
||||
bytes.len() as i32
|
||||
},
|
||||
)?;
|
||||
|
||||
// note_targets_owner() -> bool : does the note p-tag the scoped owner?
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_targets_owner",
|
||||
|caller: Caller<'_, HostState>| -> i32 {
|
||||
let owner = match caller.data().owner {
|
||||
Some(o) => o,
|
||||
None => return 0,
|
||||
};
|
||||
let hit =
|
||||
caller.data().note.tags.iter().any(|t| {
|
||||
t.len() >= 2 && t[0] == "p" && hex32(&t[1]).map_or(false, |p| p == owner)
|
||||
});
|
||||
hit as i32
|
||||
},
|
||||
)?;
|
||||
|
||||
// is_following(pk_ptr) -> bool : is this 32-byte pubkey in the owner's follows?
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"is_following",
|
||||
|mut caller: Caller<'_, HostState>, pk_ptr: i32| -> i32 {
|
||||
let target = match read_array::<32>(&mut caller, pk_ptr) {
|
||||
Some(b) => b,
|
||||
None => return 0,
|
||||
};
|
||||
caller.data().follows.contains(&target) as i32
|
||||
},
|
||||
)?;
|
||||
|
||||
// log(ptr, len) : debug logging from the guest
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"log",
|
||||
|mut caller: Caller<'_, HostState>, ptr: i32, len: i32| {
|
||||
if let Some(s) = read_str(&mut caller, ptr, len) {
|
||||
log::info!("nscript: {}", s);
|
||||
}
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve the guest's exported linear memory.
|
||||
fn memory(caller: &mut Caller<'_, HostState>) -> Option<Memory> {
|
||||
match caller.get_export("memory") {
|
||||
Some(Extern::Memory(m)) => Some(m),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `data` into guest memory at `ptr`, returning the number of bytes
|
||||
/// written (0 on failure).
|
||||
fn write_bytes(caller: &mut Caller<'_, HostState>, ptr: i32, data: &[u8]) -> i32 {
|
||||
let mem = match memory(caller) {
|
||||
Some(m) => m,
|
||||
None => return 0,
|
||||
};
|
||||
match mem.write(caller.as_context_mut(), ptr as usize, data) {
|
||||
Ok(()) => data.len() as i32,
|
||||
Err(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a fixed-size array from guest memory at `ptr`.
|
||||
fn read_array<const N: usize>(caller: &mut Caller<'_, HostState>, ptr: i32) -> Option<[u8; N]> {
|
||||
let mem = memory(caller)?;
|
||||
let mut buf = [0u8; N];
|
||||
mem.read(caller.as_context(), ptr as usize, &mut buf).ok()?;
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
/// Read a utf8 string of `len` bytes from guest memory at `ptr`.
|
||||
fn read_str(caller: &mut Caller<'_, HostState>, ptr: i32, len: i32) -> Option<String> {
|
||||
let mem = memory(caller)?;
|
||||
let mut buf = vec![0u8; len.max(0) as usize];
|
||||
mem.read(caller.as_context(), ptr as usize, &mut buf).ok()?;
|
||||
String::from_utf8(buf).ok()
|
||||
}
|
||||
|
||||
/// Decode a single hex nibble.
|
||||
fn hex_val(c: u8) -> Option<u8> {
|
||||
match c {
|
||||
b'0'..=b'9' => Some(c - b'0'),
|
||||
b'a'..=b'f' => Some(c - b'a' + 10),
|
||||
b'A'..=b'F' => Some(c - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a 64-char hex string into a 32-byte array.
|
||||
fn hex32(s: &str) -> Option<[u8; 32]> {
|
||||
let b = s.as_bytes();
|
||||
if b.len() != 64 {
|
||||
return None;
|
||||
}
|
||||
let mut out = [0u8; 32];
|
||||
for (i, byte) in out.iter_mut().enumerate() {
|
||||
*byte = (hex_val(b[2 * i])? << 4) | hex_val(b[2 * i + 1])?;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Read-side (readPolicy) filter trait — the deliverability-path analogue of
|
||||
//! [`NoteFilter`](crate::NoteFilter).
|
||||
//!
|
||||
//! Where a [`NoteFilter`] decides whether an incoming event is *stored*, a
|
||||
//! [`ReadFilter`] decides, per subscription, which already-stored events are
|
||||
//! *delivered* to a particular subscriber. The read path needs richer semantics
|
||||
//! than the pure `fn(event) -> action` write path, so the trait carries:
|
||||
//!
|
||||
//! * **Lifecycle hooks** — [`req_open`](ReadFilter::req_open) (admission +
|
||||
//! passthrough opt-out), [`req_close`](ReadFilter::req_close),
|
||||
//! [`conn_close`](ReadFilter::conn_close) — so a filter can allocate per-sub /
|
||||
//! per-conn state and free it deterministically.
|
||||
//! * **Stateful, order-dependent batch filtering** — filters keep cross-event
|
||||
//! state (a per-IP byte bucket, a per-conn counter) and use
|
||||
//! [`EventVerdict::Stop`] to withhold the *rest* of a batch once a budget is
|
||||
//! exhausted, not just an independent per-event boolean.
|
||||
//! * **A check / commit split** — [`filter_event`](ReadFilter::filter_event) is
|
||||
//! a *check* that must not consume budget; the engine calls
|
||||
//! [`on_delivered`](ReadFilter::on_delivered) exactly once, and only when
|
||||
//! *every* filter delivered the event, so counters/buckets advance only for
|
||||
//! events that actually reach the client (see the module docs on
|
||||
//! [`crate::readpolicy`]).
|
||||
//! * **Shared per-connection context** — the engine caches the client IP +
|
||||
//! authed pubkey at `reqOpen` (a `req` batch carries no IP) and hands every
|
||||
//! hook a [`ConnContext`].
|
||||
//!
|
||||
//! **Fail-open** is a per-filter contract: a filter that errors or whose guest
|
||||
//! traps must return [`EventVerdict::Deliver`] rather than withhold a
|
||||
//! subscriber's own authorized feed. This matches strfry's stance and the engine
|
||||
//! (which no-responds on unparseable input so strfry times out and delivers).
|
||||
|
||||
use crate::readmsg::UnparsedNote;
|
||||
use serde_json::Value;
|
||||
|
||||
/// Per-`(connId, subId)` context handed to every [`ReadFilter`] hook.
|
||||
///
|
||||
/// The IP and authed pubkey are cached by the engine at `reqOpen` (a `req` batch
|
||||
/// carries no IP), so a per-IP filter can meter on `req` without re-deriving
|
||||
/// them. Borrowed, never owned — a filter that needs to retain identity keys its
|
||||
/// own state by them.
|
||||
pub struct ConnContext<'a> {
|
||||
pub conn_id: u64,
|
||||
pub sub_id: &'a str,
|
||||
/// The rendered client IP, if strfry sent one (newer builds). `None` against
|
||||
/// older strfry, which sends no IP on `reqOpen`.
|
||||
pub ip: Option<&'a str>,
|
||||
/// The NIP-42 authed pubkey hex, if the connection did AUTH.
|
||||
pub authed: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// A read filter's per-event decision.
|
||||
///
|
||||
/// The three variants map onto the batch loop's control flow: `Deliver`
|
||||
/// continues to the next filter, `Skip` withholds just this event, and `Stop`
|
||||
/// withholds this event *and the entire remainder of the batch* (the "budget
|
||||
/// exhausted, `break`" semantics the throttles rely on).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EventVerdict {
|
||||
/// Deliver this event as far as this filter is concerned; continue the
|
||||
/// pipeline.
|
||||
Deliver,
|
||||
/// Withhold this event but keep processing the rest of the batch (e.g. a
|
||||
/// guest reject).
|
||||
Skip,
|
||||
/// Withhold this event and every subsequent event in the batch (e.g. a
|
||||
/// count/bandwidth budget just ran out).
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// A filter's `reqOpen` admission decision.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Admission {
|
||||
/// Admit the subscription.
|
||||
Accept,
|
||||
/// Refuse the whole subscription, with an optional client message and retry
|
||||
/// hint (milliseconds).
|
||||
Reject {
|
||||
msg: Option<String>,
|
||||
retry_ms: Option<u64>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What a filter reports at `reqOpen`: whether to admit the subscription and
|
||||
/// whether it needs to see per-event `req` batches for it.
|
||||
///
|
||||
/// The engine ANDs `!needs_events` across all filters to decide passthrough: a
|
||||
/// subscription is passthrough (strfry skips per-event marshaling) only if *no*
|
||||
/// filter needs per-event work. `needs_events` is evaluated per subscription, so
|
||||
/// it may depend on per-sub state established in `req_open` (e.g. whether a guest
|
||||
/// actually loaded, or whether this connection is bandwidth-whitelisted).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OpenDecision {
|
||||
pub admission: Admission,
|
||||
pub needs_events: bool,
|
||||
}
|
||||
|
||||
impl OpenDecision {
|
||||
/// Admit and declare no per-event work (passthrough-friendly). The default.
|
||||
pub fn passthrough() -> Self {
|
||||
OpenDecision {
|
||||
admission: Admission::Accept,
|
||||
needs_events: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Admit but declare this filter needs to see `req` batches (disables
|
||||
/// passthrough for the subscription).
|
||||
pub fn needs_events() -> Self {
|
||||
OpenDecision {
|
||||
admission: Admission::Accept,
|
||||
needs_events: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse the whole subscription.
|
||||
pub fn reject(msg: Option<String>, retry_ms: Option<u64>) -> Self {
|
||||
OpenDecision {
|
||||
admission: Admission::Reject { msg, retry_ms },
|
||||
needs_events: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A composable read-policy filter. See the [module docs](self) for the
|
||||
/// semantics (lifecycle, check/commit, fail-open).
|
||||
pub trait ReadFilter {
|
||||
/// The `[readpolicy].pipeline` key this filter is registered under.
|
||||
fn name(&self) -> &'static str;
|
||||
|
||||
/// A subscription started serving. Allocate any per-sub state, and report
|
||||
/// admission + whether this filter needs per-event batches (passthrough).
|
||||
/// `filter` is the subscription's cached filter JSON, present only here.
|
||||
///
|
||||
/// Defaults to admit + passthrough-friendly.
|
||||
fn req_open(&mut self, _ctx: &ConnContext, _filter: Option<&Value>) -> OpenDecision {
|
||||
OpenDecision::passthrough()
|
||||
}
|
||||
|
||||
/// Decide one event. This is a **check only**: it must not consume budget —
|
||||
/// commit that in [`on_delivered`](Self::on_delivered), which the engine
|
||||
/// calls iff every filter delivered the event. This keeps a partial pipeline
|
||||
/// run (a later filter's `Stop`) from corrupting this filter's budget.
|
||||
///
|
||||
/// Only called for non-passthrough subscriptions. To honour the fail-open
|
||||
/// contract, return [`EventVerdict::Deliver`] on internal error.
|
||||
///
|
||||
/// Defaults to [`EventVerdict::Deliver`].
|
||||
fn filter_event(&mut self, _ctx: &ConnContext, _ev: &UnparsedNote) -> EventVerdict {
|
||||
EventVerdict::Deliver
|
||||
}
|
||||
|
||||
/// Called, in pipeline order, after an event was delivered by *every* filter.
|
||||
/// The place to consume budget / bump counters exactly once. Defaults to a
|
||||
/// no-op (stateless filters need nothing here).
|
||||
fn on_delivered(&mut self, _ctx: &ConnContext, _ev: &UnparsedNote) {}
|
||||
|
||||
/// A subscription went away — free its per-sub state.
|
||||
fn req_close(&mut self, _conn_id: u64, _sub_id: &str) {}
|
||||
|
||||
/// A connection went away — free its per-conn state. (Note: per-IP state that
|
||||
/// must survive a reconnect is deliberately *not* freed here.)
|
||||
fn conn_close(&mut self, _conn_id: u64) {}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
use crate::read_filter::{ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
use crate::readfilters::shm::SharedByteBuckets;
|
||||
use crate::readmsg::UnparsedNote;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Nominal event size (bytes) assumed at `reqOpen`, where the next event's real
|
||||
/// wire size is unknown. Used both to decide whether the IP's bucket can afford
|
||||
/// "roughly one event" (and so whether to reject the subscription outright) and
|
||||
/// to estimate the retry hint. A middling nostr event is a few hundred bytes;
|
||||
/// the real per-event charge on `req` still meters each event's exact size. The
|
||||
/// threshold is clamped to the bucket capacity below, so a fresh (full) bucket
|
||||
/// always affords it and only a drained IP trips the reject.
|
||||
const NOMINAL_EVENT_SIZE: u64 = 512;
|
||||
|
||||
/// The shared-memory path used when `shared_state_path` is left unset — the
|
||||
/// default that gives cross-process enforcement out of the box. A conventional
|
||||
/// `tmpfs` location so every `noteguard read` process on the host attaches to
|
||||
/// ONE authoritative per-IP table without the operator having to configure
|
||||
/// anything. Set the field to `""` to opt back out to a private per-process map.
|
||||
/// (Same path as [`shm::DEFAULT_PATH`](crate::readfilters::shm::DEFAULT_PATH),
|
||||
/// which the `dump-buckets` operator tool falls back to.)
|
||||
const DEFAULT_SHARED_STATE_PATH: &str = crate::readfilters::shm::DEFAULT_PATH;
|
||||
|
||||
/// Default table capacity: distinct IPs before the table fills and fails open.
|
||||
/// ~65k slots × ~80 bytes ≈ 5 MB on tmpfs.
|
||||
fn default_max_ips() -> u32 {
|
||||
65536
|
||||
}
|
||||
|
||||
/// Where the per-IP byte buckets live for this process.
|
||||
#[derive(Default)]
|
||||
enum Store {
|
||||
/// Not yet built (built lazily on first `reqOpen`, since construction can't
|
||||
/// do I/O).
|
||||
#[default]
|
||||
Uninit,
|
||||
/// The shared file's `mmap`/init failed: this process meters nothing and
|
||||
/// fails open (delivers). Distinct from a working anonymous map, which is
|
||||
/// the intentional per-process opt-out (`shared_state_path = ""`).
|
||||
Failed,
|
||||
/// A working per-IP byte-bucket table: the shared file (the default), or a
|
||||
/// private anonymous map when the operator opted out with an empty path.
|
||||
Map(SharedByteBuckets),
|
||||
}
|
||||
|
||||
/// Read-bandwidth throttle: cap the *bytes* of events delivered per minute,
|
||||
/// keyed per client IP so reconnecting with a fresh `connId` from the same IP
|
||||
/// does not reset the budget. The read-side analogue of the write-side
|
||||
/// `ratelimit` filter, metering the exact wire byte size of each delivered event
|
||||
/// via a per-IP byte bucket.
|
||||
///
|
||||
/// ## Cross-process enforcement
|
||||
///
|
||||
/// strfry runs one `noteguard read` process per read-serving thread, each with
|
||||
/// its own memory, so an IP's reconnects fan across up to `numThreads`
|
||||
/// processes — making a naive per-process bucket enforce `bytes_per_minute × N`.
|
||||
/// To enforce ONE authoritative budget per IP while keeping N processes, the
|
||||
/// buckets live in a shared `mmap`'d table
|
||||
/// ([`SharedByteBuckets`](crate::readfilters::shm)) named by `shared_state_path`.
|
||||
/// This shared-memory enforcement is the DEFAULT: with `shared_state_path`
|
||||
/// unset every process attaches to [`DEFAULT_SHARED_STATE_PATH`], so the per-IP
|
||||
/// budget is authoritative out of the box. Setting it to `""` opts back out to
|
||||
/// a private per-process map (the old behavior — accurate only within one
|
||||
/// process). A configured path that fails to attach fails open (delivers,
|
||||
/// unmetered).
|
||||
///
|
||||
/// Once an IP's bucket can't cover the next event, the rest of the batch is
|
||||
/// withheld ([`EventVerdict::Stop`]). A whitelisted connection is exempt
|
||||
/// entirely — and, since it then does no per-event work, is reported as
|
||||
/// passthrough at `reqOpen`.
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct ReadBandwidth {
|
||||
/// Max bytes of events delivered per minute, per IP (bucket capacity).
|
||||
pub bytes_per_minute: u64,
|
||||
|
||||
/// Entries exempt from the throttle: an entry matches a connection's client
|
||||
/// IP **or** its authed pubkey hex.
|
||||
#[serde(default)]
|
||||
pub whitelist: Vec<String>,
|
||||
|
||||
/// Path to the shared-memory file holding the per-IP buckets, shared by every
|
||||
/// `noteguard read` process on the host (all must agree on the path and
|
||||
/// `max_ips`). Three cases:
|
||||
///
|
||||
/// - **Unset (`None`)** — the DEFAULT: attach to [`DEFAULT_SHARED_STATE_PATH`]
|
||||
/// so the per-IP budget is enforced across every read process out of the
|
||||
/// box. This is what you want; you shouldn't need to set it.
|
||||
/// - **Empty (`""`)** — opt out to a private per-process map, accurate only
|
||||
/// within one process (the pre-shared-memory behavior). This DISABLES
|
||||
/// cross-process enforcement, so the effective per-IP limit becomes
|
||||
/// `bytes_per_minute × numThreads`. For hosts that can't use `tmpfs`, or
|
||||
/// tests that want a fresh isolated bucket.
|
||||
/// - **A non-empty path** — attach to that file instead of the default (e.g.
|
||||
/// a different `tmpfs` location).
|
||||
///
|
||||
/// A configured (or defaulted) path that fails to attach fails open
|
||||
/// (delivers, unmetered).
|
||||
#[serde(default)]
|
||||
pub shared_state_path: Option<String>,
|
||||
|
||||
/// Table capacity: distinct IPs held before the table fills and new IPs fail
|
||||
/// open (there is no eviction — buckets must survive reconnect). Rounded up
|
||||
/// to a power of two.
|
||||
#[serde(default = "default_max_ips")]
|
||||
pub max_ips: u32,
|
||||
|
||||
/// The per-IP byte buckets for this process. Built lazily on first use.
|
||||
#[serde(skip)]
|
||||
store: Store,
|
||||
|
||||
/// `connId` -> the bucket key to charge, resolved once at `reqOpen` (a
|
||||
/// connection's IP, whitelist status and authed pubkey are fixed for its
|
||||
/// life). `None` means exempt — whitelisted, so never metered. Freed at
|
||||
/// `connClose`; the buckets themselves are not.
|
||||
#[serde(skip)]
|
||||
conn_keys: HashMap<u64, Option<String>>,
|
||||
}
|
||||
|
||||
impl ReadBandwidth {
|
||||
/// Whether this connection is exempt: a whitelist entry matching its client
|
||||
/// IP or authed pubkey.
|
||||
fn whitelisted(&self, ctx: &ConnContext) -> bool {
|
||||
if self.whitelist.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let hit = |v: Option<&str>| v.is_some_and(|v| self.whitelist.iter().any(|e| e == v));
|
||||
hit(ctx.ip) || hit(ctx.authed)
|
||||
}
|
||||
|
||||
/// The bucket key to charge this connection against: `None` if it is
|
||||
/// whitelisted, else its client IP, or a per-connection fallback when strfry
|
||||
/// sent no IP (old strfry — metering then degrades to per-connection and
|
||||
/// resets on reconnect).
|
||||
fn resolve_key(&self, ctx: &ConnContext) -> Option<String> {
|
||||
if self.whitelisted(ctx) {
|
||||
return None;
|
||||
}
|
||||
Some(match ctx.ip {
|
||||
Some(ip) => ip.to_string(),
|
||||
None => {
|
||||
log::warn!(
|
||||
"readpolicy: no client IP for conn={} (old strfry?); metering \
|
||||
bandwidth per-connection (resets on reconnect)",
|
||||
ctx.conn_id
|
||||
);
|
||||
format!("conn:{}", ctx.conn_id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Build the byte-bucket store on first use (construction can't do I/O).
|
||||
/// `shared_state_path` unset defaults to the shared file at
|
||||
/// [`DEFAULT_SHARED_STATE_PATH`] (cross-process enforcement, the default); an
|
||||
/// explicit empty string opts out to a private per-process map; an explicit
|
||||
/// non-empty path opens that file. A shared file that fails to attach records
|
||||
/// [`Store::Failed`] so the filter fails open (delivers, unmetered).
|
||||
fn ensure_store(&mut self) {
|
||||
if !matches!(self.store, Store::Uninit) {
|
||||
return;
|
||||
}
|
||||
// Unset => the default shared path (enforce across processes). An explicit
|
||||
// "" is the opt-out to a private per-process map. Any other string is that
|
||||
// path verbatim.
|
||||
let path = match self.shared_state_path.as_deref() {
|
||||
None => Some(DEFAULT_SHARED_STATE_PATH.to_string()),
|
||||
Some("") => None,
|
||||
Some(p) => Some(p.to_string()),
|
||||
};
|
||||
self.store = match path {
|
||||
None => match SharedByteBuckets::anonymous(self.max_ips) {
|
||||
Ok(m) => {
|
||||
log::info!(
|
||||
"read_bandwidth: shared_state_path=\"\"; per-process byte buckets \
|
||||
({} slots) — cross-process enforcement is OFF",
|
||||
m.slot_count()
|
||||
);
|
||||
Store::Map(m)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"read_bandwidth: could not allocate byte buckets ({e}); failing open"
|
||||
);
|
||||
Store::Failed
|
||||
}
|
||||
},
|
||||
Some(path) => match SharedByteBuckets::open(&path, self.max_ips) {
|
||||
Ok(m) => {
|
||||
log::info!(
|
||||
"read_bandwidth: shared byte buckets at {} ({} slots) — \
|
||||
cross-process enforcement is ON",
|
||||
path,
|
||||
m.slot_count()
|
||||
);
|
||||
Store::Map(m)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"read_bandwidth: shared byte-bucket init failed at {} ({}); \
|
||||
FAILING OPEN (delivering unmetered)",
|
||||
path,
|
||||
e
|
||||
);
|
||||
Store::Failed
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/// The working byte-bucket table, or `None` if metering is unavailable
|
||||
/// (a failed shared init) — in which case the filter fails open.
|
||||
fn map(&self) -> Option<&SharedByteBuckets> {
|
||||
match &self.store {
|
||||
Store::Map(m) => Some(m),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ReadFilter for ReadBandwidth {
|
||||
fn name(&self) -> &'static str {
|
||||
"read_bandwidth"
|
||||
}
|
||||
|
||||
fn req_open(&mut self, ctx: &ConnContext, _filter: Option<&serde_json::Value>) -> OpenDecision {
|
||||
// Build the shared store on first use, then resolve identity once per
|
||||
// connection, so the per-event path is a single `connId` lookup with no
|
||||
// allocation, no whitelist rescan, and (against an old strfry) one
|
||||
// missing-IP warning rather than a flood.
|
||||
self.ensure_store();
|
||||
let key = self.resolve_key(ctx);
|
||||
let cap = self.bytes_per_minute as f64;
|
||||
|
||||
// Peek the IP's (refilled) bucket to decide admission before serving a
|
||||
// single event. An already-drained IP is rejected outright so the client
|
||||
// gets a NIP-01 CLOSED + retry hint (real backpressure) instead of a
|
||||
// silent empty/truncated feed — the reconnect/churn abuse case. While
|
||||
// there is still budget we admit and meter per-event on `req` as before.
|
||||
//
|
||||
// A `None` from the map (fail open) or a failed store leaves this None,
|
||||
// so we admit.
|
||||
let mut reject_retry_ms: Option<u64> = None;
|
||||
if let (Some(key), Some(map)) = (&key, self.map()) {
|
||||
if let Some(tokens) = map.tokens_after_refill(key.as_bytes(), cap) {
|
||||
// Nominal event size clamped to capacity: a fresh (full) bucket
|
||||
// always affords it, so only a drained IP trips the reject.
|
||||
let nominal = (NOMINAL_EVENT_SIZE as f64).min(cap);
|
||||
if tokens < nominal {
|
||||
// retry_ms: time to refill one nominal event at
|
||||
// bytes_per_minute. An estimate — the next event's real size
|
||||
// is unknown at reqOpen (documented on NOMINAL_EVENT_SIZE).
|
||||
reject_retry_ms = Some(((nominal / cap) * 60_000.0).ceil() as u64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Metering happens only for a keyed connection with a working map; a
|
||||
// whitelisted conn (no key) or a failed store does no per-event work.
|
||||
let meters = key.is_some() && self.map().is_some();
|
||||
self.conn_keys.insert(ctx.conn_id, key);
|
||||
|
||||
if let Some(retry_ms) = reject_retry_ms {
|
||||
return OpenDecision::reject(
|
||||
Some(format!(
|
||||
"read bandwidth budget exhausted ({} bytes/min per IP)",
|
||||
self.bytes_per_minute
|
||||
)),
|
||||
Some(retry_ms),
|
||||
);
|
||||
}
|
||||
|
||||
// A connection we won't meter does no per-event work and can take the
|
||||
// passthrough fast path (whitelisted, or the store failed open).
|
||||
// Everyone else needs `req` batches so we can meter bytes.
|
||||
if meters {
|
||||
OpenDecision::needs_events()
|
||||
} else {
|
||||
OpenDecision::passthrough()
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_event(&mut self, ctx: &ConnContext, ev: &UnparsedNote) -> EventVerdict {
|
||||
// Check only: refill and test affordability, but DON'T spend — the
|
||||
// event isn't delivered until every later filter also delivers, so the
|
||||
// byte is charged in `on_delivered`.
|
||||
//
|
||||
// A missing entry means whitelisted, or a `req` for a subscription we
|
||||
// never saw open; a missing/failed map means fail open: deliver either
|
||||
// way.
|
||||
let cap = self.bytes_per_minute as f64;
|
||||
let Some(Some(key)) = self.conn_keys.get(&ctx.conn_id) else {
|
||||
return EventVerdict::Deliver;
|
||||
};
|
||||
let Some(map) = self.map() else {
|
||||
return EventVerdict::Deliver;
|
||||
};
|
||||
|
||||
// Refill (elapsed/60 of a minute's bytes, capped at capacity) then test
|
||||
// affordability. `None` (fail open) delivers.
|
||||
match map.tokens_after_refill(key.as_bytes(), cap) {
|
||||
Some(tokens) if tokens < ev.size() as f64 => EventVerdict::Stop,
|
||||
_ => EventVerdict::Deliver,
|
||||
}
|
||||
}
|
||||
|
||||
fn on_delivered(&mut self, ctx: &ConnContext, ev: &UnparsedNote) {
|
||||
// The bucket was resolved (and refilled) in `filter_event` for this same
|
||||
// event; charge the delivered event's exact wire size. Best-effort: a
|
||||
// fail-open acquire just skips the charge.
|
||||
let cap = self.bytes_per_minute as f64;
|
||||
let Some(Some(key)) = self.conn_keys.get(&ctx.conn_id) else {
|
||||
return;
|
||||
};
|
||||
let Some(map) = self.map() else {
|
||||
return;
|
||||
};
|
||||
map.spend(key.as_bytes(), cap, ev.size() as f64);
|
||||
}
|
||||
|
||||
fn conn_close(&mut self, conn_id: u64) {
|
||||
// Only the resolved key is per-connection. NB: no bucket eviction —
|
||||
// buckets are keyed by IP and must survive a reconnect, else the per-IP
|
||||
// budget resets.
|
||||
self.conn_keys.remove(&conn_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use crate::read_filter::{ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
use crate::readmsg::UnparsedNote;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Per-connection delivery cap: withhold once a connection has been delivered
|
||||
/// `max` events across the life of the connection (across all its
|
||||
/// subscriptions).
|
||||
///
|
||||
/// The counter is keyed by `connId`, so it is shared by every subscription on a
|
||||
/// connection and reset only when the connection closes. Once the cap is hit the
|
||||
/// rest of the batch — and every future batch — is withheld
|
||||
/// ([`EventVerdict::Stop`]).
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct MaxEventsPerConn {
|
||||
/// Max events delivered per `connId` over the connection's life.
|
||||
pub max: u64,
|
||||
|
||||
/// `connId` -> events delivered so far. Committed in `on_delivered`, so it
|
||||
/// only counts events delivered by the *whole* pipeline.
|
||||
#[serde(skip)]
|
||||
pub delivered: HashMap<u64, u64>,
|
||||
}
|
||||
|
||||
impl ReadFilter for MaxEventsPerConn {
|
||||
fn name(&self) -> &'static str {
|
||||
"max_events_per_conn"
|
||||
}
|
||||
|
||||
fn req_open(
|
||||
&mut self,
|
||||
ctx: &ConnContext,
|
||||
_filter: Option<&serde_json::Value>,
|
||||
) -> OpenDecision {
|
||||
// If this connection has already been delivered its lifetime cap, reject
|
||||
// the new subscription outright so the client gets a NIP-01 CLOSED
|
||||
// instead of an admitted sub that would silently deliver nothing.
|
||||
//
|
||||
// No retry_ms: the cap is a per-connId LIFETIME limit with no refill, so
|
||||
// retrying on the SAME connId is futile — a reconnect gets a fresh connId
|
||||
// (and a fresh counter), so the client's own reconnect *is* the retry. A
|
||||
// millisecond hint would be a lie here.
|
||||
let already = *self.delivered.get(&ctx.conn_id).unwrap_or(&0);
|
||||
if already >= self.max {
|
||||
return OpenDecision::reject(
|
||||
Some(format!(
|
||||
"per-connection event cap reached ({} events); reconnect for a fresh budget",
|
||||
self.max
|
||||
)),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
// Otherwise a configured cap always needs to see events, so strfry must
|
||||
// keep sending `req` batches for the counter to bound delivery.
|
||||
OpenDecision::needs_events()
|
||||
}
|
||||
|
||||
fn filter_event(&mut self, ctx: &ConnContext, _ev: &UnparsedNote) -> EventVerdict {
|
||||
// Check only: once the connection is at its cap, withhold this event and
|
||||
// the rest of the batch. The counter advances in `on_delivered`.
|
||||
let already = *self.delivered.get(&ctx.conn_id).unwrap_or(&0);
|
||||
if already >= self.max {
|
||||
EventVerdict::Stop
|
||||
} else {
|
||||
EventVerdict::Deliver
|
||||
}
|
||||
}
|
||||
|
||||
fn on_delivered(&mut self, ctx: &ConnContext, _ev: &UnparsedNote) {
|
||||
*self.delivered.entry(ctx.conn_id).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
fn conn_close(&mut self, conn_id: u64) {
|
||||
self.delivered.remove(&conn_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Built-in [`ReadFilter`](crate::ReadFilter) implementations, composed by the
|
||||
//! `[readpolicy].pipeline` config. The read-side counterpart to
|
||||
//! [`crate::filters`].
|
||||
|
||||
mod bandwidth;
|
||||
mod max_events;
|
||||
mod shm;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
mod nscript;
|
||||
|
||||
pub use bandwidth::ReadBandwidth;
|
||||
pub use max_events::MaxEventsPerConn;
|
||||
pub use shm::{dump, BucketEntry, Dump, DEFAULT_PATH};
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
pub use nscript::NScriptRead;
|
||||
@@ -0,0 +1,143 @@
|
||||
use crate::nscript::{Runtime, Verdict};
|
||||
use crate::read_filter::{ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
use crate::readmsg::UnparsedNote;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Runs a user-supplied WASM guest as a per-subscription deliverability filter,
|
||||
/// scoped to the subscriber (the NIP-42 `authed` pubkey = the script owner).
|
||||
///
|
||||
/// The guest is compiled once per process and re-scoped (no recompile) to each
|
||||
/// subscriber at `req_open`. The [`Verdict`] collapses on the read path to
|
||||
/// deliver (`Accept`) vs withhold (anything else) — there is no shadow concept
|
||||
/// for reads. Fails open: a missing/failed module or a trapping guest delivers.
|
||||
///
|
||||
/// The `module` + `follows` fields stub out the eventual script-distribution
|
||||
/// system: today the guest and its owner's follow-set are configured statically;
|
||||
/// later they come from a signed submission event on the relay.
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct NScriptRead {
|
||||
/// Path to the compiled guest `.wasm`, applied to every subscription (owner =
|
||||
/// the authed subscriber). If unset, deliver everything.
|
||||
pub module: Option<String>,
|
||||
|
||||
/// STUB for follow-set distribution: owner-hex -> the hex pubkeys that owner
|
||||
/// follows (backs the guest's `is_following` accessor).
|
||||
#[serde(default)]
|
||||
pub follows: HashMap<String, Vec<String>>,
|
||||
|
||||
/// The compiled guest, built once on the first `req_open` and re-scoped per
|
||||
/// subscriber. Stays `None` when no module is configured or the load failed
|
||||
/// (fail open — deliver all); `load_attempted` keeps us from retrying a
|
||||
/// broken module (and re-logging) on every subscription.
|
||||
#[serde(skip)]
|
||||
compiled: Option<Runtime>,
|
||||
#[serde(skip)]
|
||||
load_attempted: bool,
|
||||
|
||||
/// `connId` -> `subId` -> that subscriber's scoped guest. Only subscriptions
|
||||
/// that actually have a guest get an entry; everything else delivers all.
|
||||
#[serde(skip)]
|
||||
runtimes: HashMap<u64, HashMap<String, Runtime>>,
|
||||
}
|
||||
|
||||
impl NScriptRead {
|
||||
/// The compiled guest, compiling it on first use. Returns `None` — meaning
|
||||
/// deliver-all — when no module is configured or the load failed (fail
|
||||
/// open); the failure is logged once, not once per subscription.
|
||||
fn compiled(&mut self) -> Option<&Runtime> {
|
||||
if !self.load_attempted {
|
||||
self.load_attempted = true;
|
||||
if let Some(module) = &self.module {
|
||||
// Compiled owner-less; `rescope` binds each subscriber's owner
|
||||
// and follow-set without recompiling.
|
||||
match Runtime::load(module, &None, &[]) {
|
||||
Ok(rt) => self.compiled = Some(rt),
|
||||
Err(e) => log::error!(
|
||||
"readpolicy: failed to load {} (delivering all): {}",
|
||||
module,
|
||||
e
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.compiled.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl ReadFilter for NScriptRead {
|
||||
fn name(&self) -> &'static str {
|
||||
"nscript"
|
||||
}
|
||||
|
||||
/// An unauthenticated subscription (`authed` == `None`) still runs the
|
||||
/// guest, but with no owner: an owner-scoped filter (like `follows-only`)
|
||||
/// then no-ops and delivers everything, while an owner-independent filter
|
||||
/// (e.g. content muting) still applies.
|
||||
fn req_open(&mut self, ctx: &ConnContext, _filter: Option<&serde_json::Value>) -> OpenDecision {
|
||||
let owner = ctx.authed.map(str::to_string);
|
||||
let follows = ctx
|
||||
.authed
|
||||
.and_then(|owner| self.follows.get(owner))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
// Only a subscription that actually has a guest does per-event work; a
|
||||
// deliver-all sub (no module / failed load) can take passthrough.
|
||||
let Some(runtime) = self.compiled().map(|rt| rt.rescope(&owner, &follows)) else {
|
||||
return OpenDecision::passthrough();
|
||||
};
|
||||
|
||||
self.runtimes
|
||||
.entry(ctx.conn_id)
|
||||
.or_default()
|
||||
.insert(ctx.sub_id.to_string(), runtime);
|
||||
OpenDecision::needs_events()
|
||||
}
|
||||
|
||||
fn filter_event(&mut self, ctx: &ConnContext, ev: &UnparsedNote) -> EventVerdict {
|
||||
// No runtime (no module / failed load / never opened): deliver.
|
||||
let Some(rt) = self
|
||||
.runtimes
|
||||
.get(&ctx.conn_id)
|
||||
.and_then(|subs| subs.get(ctx.sub_id))
|
||||
else {
|
||||
return EventVerdict::Deliver;
|
||||
};
|
||||
|
||||
// Only the guest path pays for a full parse.
|
||||
let note = match ev.parse() {
|
||||
Ok(note) => note,
|
||||
// Fail open on a malformed event, matching strfry's stance.
|
||||
Err(e) => {
|
||||
log::error!("readpolicy: unparseable event (delivering): {}", e);
|
||||
return EventVerdict::Deliver;
|
||||
}
|
||||
};
|
||||
|
||||
match rt.run(¬e) {
|
||||
Ok(Verdict::Accept) => EventVerdict::Deliver,
|
||||
// Reject / ShadowReject both collapse to withhold-this-event on the
|
||||
// read path — there is no shadow concept for deliverability.
|
||||
Ok(_) => EventVerdict::Skip,
|
||||
Err(e) => {
|
||||
// Fail open on guest trap / resource exhaustion.
|
||||
log::error!("readpolicy: guest error (delivering): {}", e);
|
||||
EventVerdict::Deliver
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn req_close(&mut self, conn_id: u64, sub_id: &str) {
|
||||
if let Some(subs) = self.runtimes.get_mut(&conn_id) {
|
||||
subs.remove(sub_id);
|
||||
if subs.is_empty() {
|
||||
self.runtimes.remove(&conn_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn conn_close(&mut self, conn_id: u64) {
|
||||
self.runtimes.remove(&conn_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,805 @@
|
||||
//! Shared-memory per-IP byte buckets, backing [`ReadBandwidth`](super::ReadBandwidth).
|
||||
//!
|
||||
//! ## Why
|
||||
//!
|
||||
//! strfry constructs its `PluginReadPolicy` as a **per-thread local**, lazily
|
||||
//! spawning one `./noteguard read` child process per read-serving thread
|
||||
//! (`reqWorker` + `reqMonitor`). With N such threads an IP's connections — spread
|
||||
//! across processes by reconnects (dispatch is `connId % numThreads`) — hit N
|
||||
//! independent in-memory buckets, so the effective per-IP budget is
|
||||
//! `bytes_per_minute × N`. To enforce ONE authoritative budget per IP while
|
||||
//! keeping N parallel processes, all `noteguard read` processes on a host share a
|
||||
//! single [`ByteBucket`]-table through one `mmap`'d `MAP_SHARED` file.
|
||||
//!
|
||||
//! ## Layout (a `repr(C)` header + a fixed open-addressing slot table)
|
||||
//!
|
||||
//! ```text
|
||||
//! Header @0 : magic u64 | version u32 | slot_count u32 | init_state AtomicU32 | pad
|
||||
//! Slot[i] : lock AtomicU32 | state u32 | key_len u32 | pad | key [u8; KEY_LEN]
|
||||
//! | tokens u64 (f64 bits) | last_refill u64 (monotonic ns)
|
||||
//! ```
|
||||
//!
|
||||
//! The table is keyed by the client IP text (or a `conn:<id>` fallback), hashed
|
||||
//! with a **fixed** FNV-1a — never the std `RandomState`, whose per-process seed
|
||||
//! would send the same IP to different slots in different processes and defeat
|
||||
//! the whole point. Slots are found by linear probing from the hashed home slot.
|
||||
//!
|
||||
//! ## Concurrency
|
||||
//!
|
||||
//! Each slot carries its own spinlock (`AtomicU32`, `Acquire`/`Release`). All of
|
||||
//! a slot's body — `tokens`, `last_refill`, `key`, `state` — is read and written
|
||||
//! only while that lock is held; the lock's acquire/release fences publish those
|
||||
//! plain (non-atomic) accesses across processes, the standard shared-memory-IPC
|
||||
//! pattern (sound on one host + one architecture with coherent caches). Because
|
||||
//! the empty-slot check happens *while holding the slot's lock*, two processes
|
||||
//! inserting the same key serialize on the first-empty slot and cannot
|
||||
//! double-insert; and since entries are **never evicted**, probe chains never
|
||||
//! break, so a key's insertion slot is deterministic.
|
||||
//!
|
||||
//! ## Fail-open
|
||||
//!
|
||||
//! Matching the [`ReadFilter`](crate::ReadFilter) contract, every operation
|
||||
//! returns `None` (→ the caller delivers) rather than block or withhold when it
|
||||
//! cannot proceed: a slot lock it cannot acquire within a bound, a full table, an
|
||||
//! over-long key, or (at construction) a failed `mmap`/init. A throttle that
|
||||
//! breaks must never silence a subscriber's own authorized feed.
|
||||
//!
|
||||
//! ## Lifetime / staleness
|
||||
//!
|
||||
//! The default path lives on `tmpfs` (`/dev/shm`), so the table survives strfry
|
||||
//! *restarts* (the buckets, and `CLOCK_MONOTONIC`, persist across a plugin
|
||||
//! process dying and respawning — the "reconcile on restart" property, for free)
|
||||
//! but is cleared on *reboot*. As belt-and-suspenders for a non-tmpfs path
|
||||
//! carried across a reboot (where `CLOCK_MONOTONIC` resets and a stored
|
||||
//! `last_refill` would sit in the future), [`SlotGuard::refill`] treats a
|
||||
//! future timestamp as fully stale and resets the slot to a full bucket.
|
||||
|
||||
use memmap2::{MmapMut, MmapOptions};
|
||||
use std::fs::OpenOptions;
|
||||
use std::io;
|
||||
use std::ptr::{addr_of, addr_of_mut};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
/// File magic: `"NGRDBW"` + version bytes, little-endian. Bumped with `VERSION`
|
||||
/// when the on-disk layout changes so an attaching process rejects a stale file.
|
||||
const MAGIC: u64 = u64::from_le_bytes(*b"NGRDBW\x00\x01");
|
||||
/// On-disk layout version. Attaching to a file with a different version fails
|
||||
/// (→ fail open), rather than misinterpreting its bytes.
|
||||
const VERSION: u32 = 1;
|
||||
|
||||
/// The conventional shared-memory path for the read-bandwidth buckets, on
|
||||
/// `tmpfs`. The default the `read_bandwidth` filter documents and the
|
||||
/// [`dump`] operator tool falls back to when given no explicit path.
|
||||
pub const DEFAULT_PATH: &str = "/dev/shm/noteguard-read-bandwidth";
|
||||
|
||||
/// Fixed key capacity: an IPv6 textual address is at most 45 bytes
|
||||
/// (`INET6_ADDRSTRLEN`-ish), and the `conn:<id>` fallback is at most ~25, so 48
|
||||
/// covers every key. A longer key fails open.
|
||||
const KEY_LEN: usize = 48;
|
||||
|
||||
// Slot `state`.
|
||||
const EMPTY: u32 = 0;
|
||||
const OCCUPIED: u32 = 1;
|
||||
|
||||
// Header `init_state` — the one-time init handshake.
|
||||
const UNINIT: u32 = 0;
|
||||
const INITIALIZING: u32 = 1;
|
||||
const READY: u32 = 2;
|
||||
|
||||
/// Bounded spins before a slot-lock acquire gives up and fails open. Critical
|
||||
/// sections are a few memory ops (nanoseconds), so this only ever trips on a
|
||||
/// process that died holding the lock — in which case failing open is correct.
|
||||
const SPIN_LIMIT: u32 = 100_000;
|
||||
/// Bounded spins waiting for another process to finish one-time init.
|
||||
const INIT_SPIN_LIMIT: u64 = 10_000_000;
|
||||
|
||||
/// One minute in nanoseconds — the refill window (and the clamp on elapsed time).
|
||||
const MINUTE_NS: u64 = 60 * 1_000_000_000;
|
||||
|
||||
/// Shared header. `repr(C)` so every process agrees on the layout.
|
||||
#[repr(C)]
|
||||
struct Header {
|
||||
magic: u64,
|
||||
version: u32,
|
||||
slot_count: u32,
|
||||
init_state: AtomicU32,
|
||||
_pad: u32,
|
||||
}
|
||||
|
||||
/// One bucket slot. `repr(C, align(8))` so `tokens`/`last_refill` are naturally
|
||||
/// aligned and the array packs deterministically across processes.
|
||||
#[repr(C, align(8))]
|
||||
struct Slot {
|
||||
/// Per-slot spinlock: 0 = free, 1 = held. First field, so its address is the
|
||||
/// slot's address.
|
||||
lock: AtomicU32,
|
||||
/// `EMPTY` or `OCCUPIED`. Written under `lock`.
|
||||
state: u32,
|
||||
/// Bytes of `key` in use. Written under `lock`.
|
||||
key_len: u32,
|
||||
_pad: u32,
|
||||
/// The client IP text (or `conn:<id>` fallback). Written once under `lock`,
|
||||
/// immutable thereafter (no eviction).
|
||||
key: [u8; KEY_LEN],
|
||||
/// Bucket balance in bytes, stored as `f64::to_bits`. Under `lock`.
|
||||
tokens: u64,
|
||||
/// Last refill, `CLOCK_MONOTONIC` nanoseconds. Under `lock`.
|
||||
last_refill: u64,
|
||||
}
|
||||
|
||||
const HEADER_SIZE: usize = std::mem::size_of::<Header>();
|
||||
const SLOT_SIZE: usize = std::mem::size_of::<Slot>();
|
||||
|
||||
/// System-wide monotonic time in nanoseconds. `CLOCK_MONOTONIC` is boot-relative
|
||||
/// on Linux and so comparable across every process on the host — unlike
|
||||
/// [`std::time::Instant`], which is process-relative and cannot live in shared
|
||||
/// memory.
|
||||
fn monotonic_ns() -> u64 {
|
||||
// SAFETY: `clock_gettime` fills the provided `timespec`; CLOCK_MONOTONIC is
|
||||
// always available on Linux.
|
||||
let mut ts = libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: 0,
|
||||
};
|
||||
unsafe {
|
||||
libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
|
||||
}
|
||||
(ts.tv_sec as u64)
|
||||
.wrapping_mul(1_000_000_000)
|
||||
.wrapping_add(ts.tv_nsec as u64)
|
||||
}
|
||||
|
||||
/// FNV-1a (64-bit). A *fixed* hash — deterministic across processes, unlike the
|
||||
/// std hasher's per-process-seeded `RandomState`, which would place the same IP
|
||||
/// in different slots in different processes and re-shard the buckets.
|
||||
fn fnv1a(bytes: &[u8]) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for &b in bytes {
|
||||
h ^= b as u64;
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
fn slot_count_for(max_ips: u32) -> usize {
|
||||
// Power of two so the home slot is a cheap mask. At least one slot.
|
||||
(max_ips.max(1) as usize).next_power_of_two()
|
||||
}
|
||||
|
||||
fn invalid(msg: &'static str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, msg)
|
||||
}
|
||||
|
||||
/// A held slot lock plus typed access to the slot body. Releases the lock on
|
||||
/// drop. All body access goes through this guard, so it only happens under the
|
||||
/// lock.
|
||||
struct SlotGuard {
|
||||
slot: *mut Slot,
|
||||
}
|
||||
|
||||
impl SlotGuard {
|
||||
/// Try to take a slot's lock within [`SPIN_LIMIT`]. `None` (→ fail open) if it
|
||||
/// stays held — only a crashed lock-holder makes that happen in practice.
|
||||
fn lock(slot: *mut Slot) -> Option<SlotGuard> {
|
||||
// The lock is the slot's first field, so the slot pointer is the lock's.
|
||||
let lock = unsafe { &*(slot as *const AtomicU32) };
|
||||
for _ in 0..SPIN_LIMIT {
|
||||
if lock
|
||||
.compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
{
|
||||
return Some(SlotGuard { slot });
|
||||
}
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn state(&self) -> u32 {
|
||||
unsafe { addr_of!((*self.slot).state).read() }
|
||||
}
|
||||
fn set_state(&self, v: u32) {
|
||||
unsafe { addr_of_mut!((*self.slot).state).write(v) }
|
||||
}
|
||||
fn tokens(&self) -> f64 {
|
||||
f64::from_bits(unsafe { addr_of!((*self.slot).tokens).read() })
|
||||
}
|
||||
fn set_tokens(&self, v: f64) {
|
||||
unsafe { addr_of_mut!((*self.slot).tokens).write(v.to_bits()) }
|
||||
}
|
||||
fn last_refill(&self) -> u64 {
|
||||
unsafe { addr_of!((*self.slot).last_refill).read() }
|
||||
}
|
||||
fn set_last_refill(&self, v: u64) {
|
||||
unsafe { addr_of_mut!((*self.slot).last_refill).write(v) }
|
||||
}
|
||||
|
||||
fn key_matches(&self, key: &[u8]) -> bool {
|
||||
unsafe {
|
||||
let len = addr_of!((*self.slot).key_len).read() as usize;
|
||||
if len != key.len() {
|
||||
return false;
|
||||
}
|
||||
let p = addr_of!((*self.slot).key) as *const u8;
|
||||
std::slice::from_raw_parts(p, len) == key
|
||||
}
|
||||
}
|
||||
|
||||
/// Claim an empty slot for `key` with a full bucket. Caller must hold the
|
||||
/// slot lock (i.e. be this guard) and have checked the slot is `EMPTY`.
|
||||
fn claim(&self, key: &[u8], cap: f64) {
|
||||
unsafe {
|
||||
let p = addr_of_mut!((*self.slot).key) as *mut u8;
|
||||
std::ptr::copy_nonoverlapping(key.as_ptr(), p, key.len());
|
||||
addr_of_mut!((*self.slot).key_len).write(key.len() as u32);
|
||||
}
|
||||
self.set_tokens(cap);
|
||||
self.set_last_refill(monotonic_ns());
|
||||
self.set_state(OCCUPIED);
|
||||
}
|
||||
|
||||
/// Refill toward `cap` by the elapsed fraction of a minute (same shape as the
|
||||
/// write-side `ratelimit`), clamped to one minute and capped at `cap`. A
|
||||
/// `last_refill` in the future (a stale entry carried across a reboot, where
|
||||
/// the monotonic clock reset) resets the slot to full.
|
||||
fn refill(&self, cap: f64) {
|
||||
let now = monotonic_ns();
|
||||
let last = self.last_refill();
|
||||
if last > now {
|
||||
// Stale from a prior boot: reset rather than freeze the bucket.
|
||||
self.set_tokens(cap);
|
||||
self.set_last_refill(now);
|
||||
return;
|
||||
}
|
||||
let elapsed = (now - last).min(MINUTE_NS);
|
||||
let refill = (elapsed as f64 / MINUTE_NS as f64) * cap;
|
||||
self.set_tokens((self.tokens() + refill).min(cap));
|
||||
self.set_last_refill(now);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SlotGuard {
|
||||
fn drop(&mut self) {
|
||||
let lock = unsafe { &*(self.slot as *const AtomicU32) };
|
||||
lock.store(0, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixed-size open-addressing table of per-IP byte buckets over one `mmap`.
|
||||
///
|
||||
/// Cloned only conceptually — construct one per process ([`Self::open`] to share
|
||||
/// a file across processes, [`Self::anonymous`] for a private per-process map).
|
||||
pub struct SharedByteBuckets {
|
||||
// Keeps the mapping alive; the raw `base`/pointers below borrow from it. The
|
||||
// mapping's virtual address is stable across a move of this struct.
|
||||
_mmap: MmapMut,
|
||||
base: *mut u8,
|
||||
slot_count: usize,
|
||||
}
|
||||
|
||||
impl SharedByteBuckets {
|
||||
/// Attach to (creating + initializing if absent) the shared file at `path`,
|
||||
/// sized for `max_ips` distinct IPs (rounded up to a power of two). Every
|
||||
/// `noteguard read` process on the host passes the same path + `max_ips`.
|
||||
pub fn open(path: &str, max_ips: u32) -> io::Result<Self> {
|
||||
let slot_count = slot_count_for(max_ips);
|
||||
let total = HEADER_SIZE + slot_count * SLOT_SIZE;
|
||||
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
// Never truncate: attaching to an existing table must preserve it
|
||||
// (grow-only sizing below), which is how the buckets survive a restart.
|
||||
.truncate(false)
|
||||
.open(path)?;
|
||||
// Grow-only: the first process sizes a fresh (zero-length) file; a process
|
||||
// attaching to an existing one leaves it be (and validates via the header).
|
||||
if (file.metadata()?.len() as usize) < total {
|
||||
file.set_len(total as u64)?;
|
||||
}
|
||||
// SAFETY: the file is sized to at least `total`; the mapping is `MAP_SHARED`.
|
||||
let mmap = unsafe { MmapOptions::new().len(total).map_mut(&file)? };
|
||||
Self::from_mmap(mmap, slot_count)
|
||||
}
|
||||
|
||||
/// A private, per-process map (zero-filled anonymous mapping). Used when no
|
||||
/// shared path is configured, and in tests. Behaves exactly like the old
|
||||
/// per-process `HashMap`, through the same slot logic.
|
||||
pub fn anonymous(max_ips: u32) -> io::Result<Self> {
|
||||
let slot_count = slot_count_for(max_ips);
|
||||
let total = HEADER_SIZE + slot_count * SLOT_SIZE;
|
||||
let mmap = MmapMut::map_anon(total)?;
|
||||
Self::from_mmap(mmap, slot_count)
|
||||
}
|
||||
|
||||
fn from_mmap(mmap: MmapMut, slot_count: usize) -> io::Result<Self> {
|
||||
let base = mmap.as_ptr() as *mut u8;
|
||||
let this = SharedByteBuckets {
|
||||
_mmap: mmap,
|
||||
base,
|
||||
slot_count,
|
||||
};
|
||||
this.init_or_attach(slot_count)?;
|
||||
Ok(this)
|
||||
}
|
||||
|
||||
/// One-time init handshake: the first process to see `UNINIT` writes the
|
||||
/// header and flips to `READY`; concurrent creators spin until `READY`; a
|
||||
/// process attaching to an already-`READY` file validates magic/version and
|
||||
/// that its `max_ips` agrees (a mismatch fails, → fail open, rather than
|
||||
/// silently sharding against a different-sized table). A freshly created file
|
||||
/// (or anon mapping) is zero-filled, so its slots are already `EMPTY`.
|
||||
fn init_or_attach(&self, our_slot_count: usize) -> io::Result<()> {
|
||||
let hdr = self.base as *mut Header;
|
||||
let state = unsafe { &*addr_of!((*hdr).init_state) };
|
||||
let mut spins = 0u64;
|
||||
loop {
|
||||
match state.compare_exchange(UNINIT, INITIALIZING, Ordering::Acquire, Ordering::Acquire)
|
||||
{
|
||||
Ok(_) => {
|
||||
unsafe {
|
||||
addr_of_mut!((*hdr).magic).write(MAGIC);
|
||||
addr_of_mut!((*hdr).version).write(VERSION);
|
||||
addr_of_mut!((*hdr).slot_count).write(our_slot_count as u32);
|
||||
}
|
||||
// Slots are already zeroed (fresh ftruncate / anon map) => EMPTY.
|
||||
state.store(READY, Ordering::Release);
|
||||
return Ok(());
|
||||
}
|
||||
Err(INITIALIZING) => {
|
||||
spins += 1;
|
||||
if spins > INIT_SPIN_LIMIT {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"shared byte-bucket init stalled (crashed initializer?)",
|
||||
));
|
||||
}
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
Err(READY) => {
|
||||
let (magic, version, sc) = unsafe {
|
||||
(
|
||||
addr_of!((*hdr).magic).read(),
|
||||
addr_of!((*hdr).version).read(),
|
||||
addr_of!((*hdr).slot_count).read(),
|
||||
)
|
||||
};
|
||||
if magic != MAGIC {
|
||||
return Err(invalid("shared byte-bucket file has wrong magic"));
|
||||
}
|
||||
if version != VERSION {
|
||||
return Err(invalid("shared byte-bucket file version mismatch"));
|
||||
}
|
||||
if sc as usize != our_slot_count {
|
||||
return Err(invalid(
|
||||
"shared byte-bucket max_ips disagrees with the existing file",
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Err(_) => return Err(invalid("shared byte-bucket init_state corrupt")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn slot_count(&self) -> usize {
|
||||
self.slot_count
|
||||
}
|
||||
|
||||
fn slot_ptr(&self, i: usize) -> *mut Slot {
|
||||
// Slots begin right after the header; `base` is page-aligned so the
|
||||
// 8-aligned header + slots stay naturally aligned.
|
||||
unsafe { (self.base.add(HEADER_SIZE) as *mut Slot).add(i) }
|
||||
}
|
||||
|
||||
/// Find `key`'s slot (or insert it, full), returning its held lock guard.
|
||||
/// `None` (→ fail open) if the key is over-long, a probed slot's lock cannot
|
||||
/// be taken, or the table is full.
|
||||
fn acquire(&self, key: &[u8], cap: f64) -> Option<SlotGuard> {
|
||||
if key.is_empty() || key.len() > KEY_LEN {
|
||||
return None;
|
||||
}
|
||||
let mask = self.slot_count - 1;
|
||||
let home = (fnv1a(key) as usize) & mask;
|
||||
for step in 0..self.slot_count {
|
||||
let idx = (home + step) & mask;
|
||||
let guard = SlotGuard::lock(self.slot_ptr(idx))?;
|
||||
match guard.state() {
|
||||
EMPTY => {
|
||||
// First empty in the probe chain: claim it. The empty-check
|
||||
// is under the lock, so a racing insert of the same key waits
|
||||
// here and then matches instead of double-inserting.
|
||||
guard.claim(key, cap);
|
||||
return Some(guard);
|
||||
}
|
||||
_ if guard.key_matches(key) => return Some(guard),
|
||||
// Occupied by a different key: release and probe on.
|
||||
_ => drop(guard),
|
||||
}
|
||||
}
|
||||
// Table full: no matching or empty slot within a full sweep.
|
||||
None
|
||||
}
|
||||
|
||||
/// Refill `key`'s bucket and return its current balance in bytes. Creates the
|
||||
/// bucket full on first sight. `None` → fail open.
|
||||
pub fn tokens_after_refill(&self, key: &[u8], cap: f64) -> Option<f64> {
|
||||
let guard = self.acquire(key, cap)?;
|
||||
guard.refill(cap);
|
||||
Some(guard.tokens())
|
||||
}
|
||||
|
||||
/// Refill `key`'s bucket and subtract `amount` bytes (may go transiently
|
||||
/// negative; it recovers on the next refill). Best-effort: a fail-open
|
||||
/// `acquire` just skips the charge.
|
||||
pub fn spend(&self, key: &[u8], cap: f64, amount: f64) {
|
||||
if let Some(guard) = self.acquire(key, cap) {
|
||||
guard.refill(cap);
|
||||
guard.set_tokens(guard.tokens() - amount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One OCCUPIED bucket, as read by [`dump`]. A read-only, best-effort snapshot
|
||||
/// of a slot's body — see [`dump`] for the lock-free-read caveat.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BucketEntry {
|
||||
/// The slot's key: the client IP text, or a `conn:<id>` fallback. Rendered
|
||||
/// lossily (keys are ASCII in practice, but a corrupt/foreign file might not
|
||||
/// be, and a diagnostic tool must never panic on the bytes it finds).
|
||||
pub key: String,
|
||||
/// Bucket balance in bytes at the instant of the snapshot, exactly as last
|
||||
/// written by a metering process — NOT refilled to now (the caller can do
|
||||
/// that against [`Dump::now_ns`] if it knows the capacity).
|
||||
pub tokens: f64,
|
||||
/// This slot's last refill, in `CLOCK_MONOTONIC` nanoseconds — comparable to
|
||||
/// [`Dump::now_ns`] (both read the same host-wide clock).
|
||||
pub last_refill_ns: u64,
|
||||
}
|
||||
|
||||
/// The result of a [`dump`]: the table's configured `slot_count`, a monotonic
|
||||
/// clock reading captured at dump time (so each entry can be aged against the
|
||||
/// same clock the buckets use), and every OCCUPIED slot.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Dump {
|
||||
/// Total slot capacity of the table (from the header) — power of two.
|
||||
pub slot_count: u32,
|
||||
/// `CLOCK_MONOTONIC` nanoseconds captured just before scanning the slots.
|
||||
/// Subtract an entry's `last_refill_ns` for its age; the difference can be
|
||||
/// negative for an entry carried across a reboot (the clock reset), which a
|
||||
/// caller should treat as stale.
|
||||
pub now_ns: u64,
|
||||
/// Every OCCUPIED slot, in slot order (unsorted).
|
||||
pub entries: Vec<BucketEntry>,
|
||||
}
|
||||
|
||||
/// Read-only, best-effort snapshot of the shared byte-bucket table at `path`,
|
||||
/// for operator inspection (the `noteguard dump-buckets` CLI). Opens the file
|
||||
/// **read-only** and maps it **read-only**: it never writes, so it cannot perturb
|
||||
/// live metering or leave a slot lock wedged. Validates the header's magic and
|
||||
/// version (a mismatch or an under-sized file is a clear `InvalidData` error)
|
||||
/// before trusting any offset.
|
||||
///
|
||||
/// **Lock-free by design.** Unlike the metering paths, `dump` does *not* take
|
||||
/// each slot's spinlock: acquiring the lock writes to the mapping, which a
|
||||
/// read-only tool must not do (a tool that died mid-hold would wedge a live
|
||||
/// slot). Instead it reads each field directly. This is sound as a diagnostic:
|
||||
/// a slot's `key`/`key_len` are written once under lock at claim time and are
|
||||
/// immutable thereafter (entries are never evicted), so an OCCUPIED slot's key
|
||||
/// never tears; `tokens`/`last_refill` are naturally-aligned 8-byte words whose
|
||||
/// reads don't tear on the single-host, coherent-cache architectures this table
|
||||
/// targets, though either may read an instant stale versus a concurrent refill.
|
||||
/// Good enough to peek at; never authoritative.
|
||||
pub fn dump(path: &str) -> io::Result<Dump> {
|
||||
let file = OpenOptions::new().read(true).open(path)?;
|
||||
let len = file.metadata()?.len() as usize;
|
||||
if len < HEADER_SIZE {
|
||||
return Err(invalid("shared byte-bucket file smaller than its header"));
|
||||
}
|
||||
// SAFETY: read-only mapping of a file at least `HEADER_SIZE` long; nothing
|
||||
// else holds a `&mut` to these bytes in this process.
|
||||
let mmap = unsafe { MmapOptions::new().len(len).map(&file)? };
|
||||
let base = mmap.as_ptr();
|
||||
|
||||
// Validate the header before trusting the slot_count it claims.
|
||||
let hdr = base as *const Header;
|
||||
let (magic, version, slot_count) = unsafe {
|
||||
(
|
||||
addr_of!((*hdr).magic).read(),
|
||||
addr_of!((*hdr).version).read(),
|
||||
addr_of!((*hdr).slot_count).read(),
|
||||
)
|
||||
};
|
||||
if magic != MAGIC {
|
||||
return Err(invalid("shared byte-bucket file has wrong magic"));
|
||||
}
|
||||
if version != VERSION {
|
||||
return Err(invalid("shared byte-bucket file version mismatch"));
|
||||
}
|
||||
|
||||
// The file must be large enough to hold the slot table the header claims,
|
||||
// or a slot read would run off the mapping.
|
||||
let slot_count = slot_count as usize;
|
||||
let need = HEADER_SIZE + slot_count * SLOT_SIZE;
|
||||
if len < need {
|
||||
return Err(invalid(
|
||||
"shared byte-bucket file truncated (smaller than its slot table)",
|
||||
));
|
||||
}
|
||||
|
||||
let now_ns = monotonic_ns();
|
||||
let mut entries = Vec::new();
|
||||
for i in 0..slot_count {
|
||||
// SAFETY: `i < slot_count` and the file is >= HEADER_SIZE + slot_count*SLOT_SIZE.
|
||||
let slot = unsafe { (base.add(HEADER_SIZE) as *const Slot).add(i) };
|
||||
if unsafe { addr_of!((*slot).state).read() } != OCCUPIED {
|
||||
continue;
|
||||
}
|
||||
let key_len = unsafe { addr_of!((*slot).key_len).read() } as usize;
|
||||
// Defensive: never trust an out-of-range key_len from a corrupt file.
|
||||
if key_len > KEY_LEN {
|
||||
continue;
|
||||
}
|
||||
let key = unsafe {
|
||||
let p = addr_of!((*slot).key) as *const u8;
|
||||
String::from_utf8_lossy(std::slice::from_raw_parts(p, key_len)).into_owned()
|
||||
};
|
||||
let tokens = f64::from_bits(unsafe { addr_of!((*slot).tokens).read() });
|
||||
let last_refill_ns = unsafe { addr_of!((*slot).last_refill).read() };
|
||||
entries.push(BucketEntry {
|
||||
key,
|
||||
tokens,
|
||||
last_refill_ns,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(Dump {
|
||||
slot_count: slot_count as u32,
|
||||
now_ns,
|
||||
entries,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicU32 as TestCtr;
|
||||
|
||||
/// A unique temp path with best-effort cleanup on drop.
|
||||
struct TmpFile(String);
|
||||
impl TmpFile {
|
||||
fn new(tag: &str) -> TmpFile {
|
||||
static CTR: TestCtr = TestCtr::new(0);
|
||||
let n = CTR.fetch_add(1, Ordering::Relaxed);
|
||||
let p = std::env::temp_dir()
|
||||
.join(format!("ng-shm-{}-{}-{}", tag, std::process::id(), n))
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let _ = std::fs::remove_file(&p);
|
||||
TmpFile(p)
|
||||
}
|
||||
}
|
||||
impl Drop for TmpFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Find `n` distinct keys that all hash to the same home slot in a table of
|
||||
/// `slot_count`, to force probing/collisions deterministically.
|
||||
fn colliding_keys(slot_count: usize, n: usize) -> Vec<Vec<u8>> {
|
||||
let mask = slot_count - 1;
|
||||
let target = 0usize;
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0u64;
|
||||
while out.len() < n {
|
||||
let k = format!("collide-{}", i).into_bytes();
|
||||
if (fnv1a(&k) as usize) & mask == target {
|
||||
out.push(k);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anonymous_creates_full_bucket_and_spends() {
|
||||
let m = SharedByteBuckets::anonymous(16).unwrap();
|
||||
let cap = 1000.0;
|
||||
// First sight: a full bucket.
|
||||
assert_eq!(m.tokens_after_refill(b"1.2.3.4", cap), Some(cap));
|
||||
m.spend(b"1.2.3.4", cap, 600.0);
|
||||
let t = m.tokens_after_refill(b"1.2.3.4", cap).unwrap();
|
||||
assert!((t - 400.0).abs() < 1.0, "expected ~400, got {t}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spend_can_go_transiently_negative() {
|
||||
let m = SharedByteBuckets::anonymous(16).unwrap();
|
||||
let cap = 100.0;
|
||||
m.tokens_after_refill(b"9.9.9.9", cap);
|
||||
m.spend(b"9.9.9.9", cap, 250.0);
|
||||
let t = m.tokens_after_refill(b"9.9.9.9", cap).unwrap();
|
||||
assert!(
|
||||
t < 0.0,
|
||||
"overspend should leave a negative balance, got {t}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refill_recovers_over_elapsed_time() {
|
||||
let m = SharedByteBuckets::anonymous(16).unwrap();
|
||||
let cap = 6000.0;
|
||||
m.tokens_after_refill(b"5.5.5.5", cap);
|
||||
// Drain, then backdate last_refill by 30s: half a minute => half a cap.
|
||||
{
|
||||
let g = m.acquire(b"5.5.5.5", cap).unwrap();
|
||||
g.set_tokens(0.0);
|
||||
g.set_last_refill(monotonic_ns() - 30 * 1_000_000_000);
|
||||
}
|
||||
let t = m.tokens_after_refill(b"5.5.5.5", cap).unwrap();
|
||||
assert!(
|
||||
(t - cap / 2.0).abs() < cap * 0.02,
|
||||
"expected ~half cap ({}), got {t}",
|
||||
cap / 2.0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refill_clamps_at_one_minute() {
|
||||
let m = SharedByteBuckets::anonymous(16).unwrap();
|
||||
let cap = 1000.0;
|
||||
m.tokens_after_refill(b"1.1.1.1", cap);
|
||||
{
|
||||
let g = m.acquire(b"1.1.1.1", cap).unwrap();
|
||||
g.set_tokens(0.0);
|
||||
// A long time ago: refill is clamped to one minute => full, not more.
|
||||
g.set_last_refill(monotonic_ns() - 600 * 1_000_000_000);
|
||||
}
|
||||
assert_eq!(m.tokens_after_refill(b"1.1.1.1", cap), Some(cap));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn future_timestamp_resets_slot() {
|
||||
let m = SharedByteBuckets::anonymous(16).unwrap();
|
||||
let cap = 1000.0;
|
||||
m.tokens_after_refill(b"2.2.2.2", cap);
|
||||
{
|
||||
let g = m.acquire(b"2.2.2.2", cap).unwrap();
|
||||
g.set_tokens(0.0);
|
||||
// Stale-from-prior-boot: a last_refill in the future resets to full.
|
||||
g.set_last_refill(monotonic_ns() + 100 * 1_000_000_000);
|
||||
}
|
||||
assert_eq!(m.tokens_after_refill(b"2.2.2.2", cap), Some(cap));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probing_keeps_colliding_keys_distinct() {
|
||||
// A 4-slot table; three keys sharing a home slot must land in distinct
|
||||
// slots (linear probing) and keep independent balances.
|
||||
let m = SharedByteBuckets::anonymous(4).unwrap();
|
||||
assert_eq!(m.slot_count(), 4);
|
||||
let cap = 1000.0;
|
||||
let keys = colliding_keys(4, 3);
|
||||
for k in &keys {
|
||||
m.tokens_after_refill(k, cap);
|
||||
}
|
||||
m.spend(&keys[0], cap, 100.0);
|
||||
m.spend(&keys[1], cap, 200.0);
|
||||
// keys[2] untouched, keys[0]/[1] independently charged.
|
||||
assert!((m.tokens_after_refill(&keys[0], cap).unwrap() - 900.0).abs() < 1.0);
|
||||
assert!((m.tokens_after_refill(&keys[1], cap).unwrap() - 800.0).abs() < 1.0);
|
||||
assert!((m.tokens_after_refill(&keys[2], cap).unwrap() - 1000.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_table_fails_open() {
|
||||
// Two slots, three distinct keys: the third has nowhere to go => None
|
||||
// (fail open), never clobbering an existing bucket.
|
||||
let m = SharedByteBuckets::anonymous(2).unwrap();
|
||||
assert_eq!(m.slot_count(), 2);
|
||||
let cap = 1000.0;
|
||||
assert!(m.tokens_after_refill(b"a", cap).is_some());
|
||||
assert!(m.tokens_after_refill(b"b", cap).is_some());
|
||||
assert_eq!(m.tokens_after_refill(b"c", cap), None);
|
||||
// A key already present still resolves even when the table is full.
|
||||
assert!(m.tokens_after_refill(b"a", cap).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlong_key_fails_open() {
|
||||
let m = SharedByteBuckets::anonymous(16).unwrap();
|
||||
let long = vec![b'x'; KEY_LEN + 1];
|
||||
assert_eq!(m.tokens_after_refill(&long, 1000.0), None);
|
||||
m.spend(&long, 1000.0, 10.0); // no-op, must not panic
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_views_over_one_file_share_state() {
|
||||
// The crux: two SharedByteBuckets over ONE file model two processes.
|
||||
// A spend through view A is visible through view B — the whole point.
|
||||
let tf = TmpFile::new("share");
|
||||
let a = SharedByteBuckets::open(&tf.0, 64).unwrap();
|
||||
let b = SharedByteBuckets::open(&tf.0, 64).unwrap(); // attaches to A's file
|
||||
let cap = 1000.0;
|
||||
a.tokens_after_refill(b"1.2.3.4", cap); // A creates a full bucket
|
||||
a.spend(b"1.2.3.4", cap, 700.0); // A: 300 left
|
||||
let seen_by_b = b.tokens_after_refill(b"1.2.3.4", cap).unwrap();
|
||||
assert!(
|
||||
(seen_by_b - 300.0).abs() < 1.0,
|
||||
"view B must see view A's spend; got {seen_by_b}"
|
||||
);
|
||||
// And a spend through B is visible through A.
|
||||
b.spend(b"1.2.3.4", cap, 100.0);
|
||||
let seen_by_a = a.tokens_after_refill(b"1.2.3.4", cap).unwrap();
|
||||
assert!((seen_by_a - 200.0).abs() < 1.0, "got {seen_by_a}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopen_reuses_existing_buckets() {
|
||||
// Survive-restart: drop the map and reopen the same file; the bucket's
|
||||
// balance persists (as it would across a strfry restart on tmpfs).
|
||||
let tf = TmpFile::new("reopen");
|
||||
let cap = 1000.0;
|
||||
{
|
||||
let a = SharedByteBuckets::open(&tf.0, 64).unwrap();
|
||||
a.tokens_after_refill(b"7.7.7.7", cap);
|
||||
a.spend(b"7.7.7.7", cap, 400.0);
|
||||
}
|
||||
let b = SharedByteBuckets::open(&tf.0, 64).unwrap();
|
||||
let t = b.tokens_after_refill(b"7.7.7.7", cap).unwrap();
|
||||
assert!((t - 600.0).abs() < 1.0, "expected persisted ~600, got {t}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_with_mismatched_capacity_fails() {
|
||||
let tf = TmpFile::new("mismatch");
|
||||
let _a = SharedByteBuckets::open(&tf.0, 64).unwrap();
|
||||
// A second process configured for a different max_ips must not silently
|
||||
// shard against a different-sized table.
|
||||
assert!(SharedByteBuckets::open(&tf.0, 128).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dump_reports_occupied_buckets() {
|
||||
// The operator peek: write two known buckets through the metering paths,
|
||||
// drop the map, then read them back read-only via `dump`.
|
||||
let tf = TmpFile::new("dump");
|
||||
let cap = 1000.0;
|
||||
{
|
||||
let m = SharedByteBuckets::open(&tf.0, 64).unwrap();
|
||||
m.tokens_after_refill(b"1.2.3.4", cap); // full
|
||||
m.spend(b"1.2.3.4", cap, 600.0); // ~400 left
|
||||
m.tokens_after_refill(b"5.6.7.8", cap); // full
|
||||
}
|
||||
let d = dump(&tf.0).unwrap();
|
||||
assert_eq!(d.slot_count, 64);
|
||||
assert_eq!(d.entries.len(), 2, "exactly the two OCCUPIED slots");
|
||||
|
||||
let by_key = |k: &str| {
|
||||
d.entries
|
||||
.iter()
|
||||
.find(|e| e.key == k)
|
||||
.unwrap_or_else(|| panic!("missing bucket for {k}"))
|
||||
};
|
||||
assert!((by_key("1.2.3.4").tokens - 400.0).abs() < 1.0);
|
||||
assert!((by_key("5.6.7.8").tokens - 1000.0).abs() < 1.0);
|
||||
|
||||
// Both slots were just refilled, so their ages are small & non-negative
|
||||
// against the same monotonic clock `dump` captured.
|
||||
for e in &d.entries {
|
||||
let age = d.now_ns as i128 - e.last_refill_ns as i128;
|
||||
assert!(age >= 0, "fresh dump should not see a future last_refill");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dump_rejects_a_non_bucket_file() {
|
||||
// A file that isn't a bucket table (wrong magic) is a clear error, not a
|
||||
// pile of garbage rows.
|
||||
let tf = TmpFile::new("dump-bad");
|
||||
std::fs::write(&tf.0, b"this is definitely not a noteguard bucket file..").unwrap();
|
||||
assert!(dump(&tf.0).is_err());
|
||||
}
|
||||
}
|
||||
+395
@@ -0,0 +1,395 @@
|
||||
//! Read-side (readPolicy) plugin wire protocol.
|
||||
//!
|
||||
//! strfry's read plugin is the REQ-path analogue of the writePolicy plugin
|
||||
//! implemented in [`crate::messages`]. Whereas the write plugin decides whether
|
||||
//! an incoming event is *stored* (a reject deletes it for everyone), the read
|
||||
//! plugin decides, per subscription, which already-stored events are *delivered*
|
||||
//! to that particular subscriber. See `strfry/docs/plugins.md` ("Read-policy
|
||||
//! plugins") and `strfry/src/PluginReadPolicy.h` for the authoritative protocol.
|
||||
//!
|
||||
//! Every message is one minified JSON object followed by a newline. All requests
|
||||
//! carry a monotonic `reqId`; responses to `reqOpen`/`req` must echo it.
|
||||
//! `reqClose`/`connClose` are fire-and-forget — the plugin must NOT respond to
|
||||
//! them (a stray response desyncs the pipe).
|
||||
|
||||
use crate::Note;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::value::RawValue;
|
||||
use serde_json::Value;
|
||||
|
||||
/// An event object from a `req` batch, kept in its original unparsed wire form.
|
||||
///
|
||||
/// Wrapping the raw JSON (rather than a fully-parsed [`Note`]) lets us measure
|
||||
/// the exact number of bytes strfry streamed — [`size`](Self::size) is the wire
|
||||
/// length with no re-serialization — while deferring the cost of a full parse to
|
||||
/// the paths that actually need field access. The bandwidth-only metering path
|
||||
/// never parses a `Note` at all; it only ever calls `size()` and, for the
|
||||
/// accept-list, the cheap id-only [`id`](Self::id).
|
||||
///
|
||||
/// `RawValue` only captures the original source bytes when it is deserialized
|
||||
/// straight from the top-level `serde_json` deserializer. That is why
|
||||
/// [`ReadInput`] uses a manual `Deserialize` over a flat struct instead of the
|
||||
/// derived `#[serde(tag = "type")]` enum: an internally-tagged enum buffers the
|
||||
/// object into a serde `Content` value first, which strips `RawValue`'s capture.
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct UnparsedNote(Box<RawValue>);
|
||||
|
||||
impl UnparsedNote {
|
||||
/// Exact byte length of the event object as strfry streamed it (the token
|
||||
/// cost charged by the bandwidth throttle). No re-serialization.
|
||||
pub fn size(&self) -> usize {
|
||||
self.0.get().len()
|
||||
}
|
||||
|
||||
/// Fully parse the event into a [`Note`]. Only used when a guest filter
|
||||
/// actually needs the event's fields.
|
||||
pub fn parse(&self) -> serde_json::Result<Note> {
|
||||
serde_json::from_str(self.0.get())
|
||||
}
|
||||
|
||||
/// Cheaply parse just the event `id` for the accept-list, avoiding a full
|
||||
/// [`Note`] parse on the bandwidth-only (no-guest) path.
|
||||
pub fn id(&self) -> serde_json::Result<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct IdOnly {
|
||||
id: String,
|
||||
}
|
||||
let IdOnly { id } = serde_json::from_str(self.0.get())?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Construct one directly from a JSON string (test helper / for callers that
|
||||
/// already hold the wire bytes).
|
||||
#[cfg(test)]
|
||||
pub fn from_json(json: &str) -> serde_json::Result<Self> {
|
||||
Ok(UnparsedNote(RawValue::from_string(json.to_string())?))
|
||||
}
|
||||
}
|
||||
|
||||
/// A message sent from strfry to the read plugin, discriminated by `type`.
|
||||
///
|
||||
/// Deserialized via a manual `impl Deserialize` (below) rather than the derived
|
||||
/// internally-tagged enum, so the nested `Vec<UnparsedNote>` in [`Req`] captures
|
||||
/// true wire bytes for byte metering. See [`UnparsedNote`].
|
||||
#[derive(Debug)]
|
||||
pub enum ReadInput {
|
||||
/// A subscription started serving on a read thread. The admission/throttle
|
||||
/// hook and the authoritative place the subscription's `filter` arrives.
|
||||
ReqOpen {
|
||||
req_id: u64,
|
||||
conn_id: u64,
|
||||
sub_id: String,
|
||||
/// The authenticated pubkey (hex), present only if the connection did
|
||||
/// NIP-42 AUTH. This is the subscriber / script owner.
|
||||
authed: Option<String>,
|
||||
/// The subscription's filters, as a JSON array. Sent authoritatively
|
||||
/// here; omitted on `req`. Cache it per `(connId, subId)` if needed.
|
||||
filter: Option<Value>,
|
||||
/// The rendered client IP string, present when strfry knows it (newer
|
||||
/// strfry builds only; absent → `None` against older strfry). Cached
|
||||
/// per `connId` so the per-IP bandwidth throttle can meter on `req`,
|
||||
/// which carries no IP.
|
||||
ip: Option<String>,
|
||||
},
|
||||
|
||||
/// A batch of already-matched events to make deliverability decisions about.
|
||||
/// `filter` is NOT resent here — use the one cached from `reqOpen`.
|
||||
Req {
|
||||
req_id: u64,
|
||||
conn_id: u64,
|
||||
sub_id: String,
|
||||
authed: Option<String>,
|
||||
events: Vec<UnparsedNote>,
|
||||
},
|
||||
|
||||
/// A subscription went away. Free per-subscription state. No response.
|
||||
ReqClose { conn_id: u64, sub_id: String },
|
||||
|
||||
/// A connection went away. Free all per-connection state. No response.
|
||||
ConnClose { conn_id: u64 },
|
||||
}
|
||||
|
||||
/// Flat wire shape of every read-plugin message. Deserialized straight from the
|
||||
/// top-level `serde_json` deserializer (no tag/flatten/untagged buffering) so
|
||||
/// the nested `Vec<UnparsedNote>` keeps its raw bytes; [`ReadInput`]'s manual
|
||||
/// `Deserialize` dispatches on `msg_type` to build the typed enum.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RawInput {
|
||||
#[serde(rename = "type")]
|
||||
msg_type: String,
|
||||
#[serde(default)]
|
||||
req_id: Option<u64>,
|
||||
#[serde(default)]
|
||||
conn_id: Option<u64>,
|
||||
#[serde(default)]
|
||||
sub_id: Option<String>,
|
||||
#[serde(default)]
|
||||
authed: Option<String>,
|
||||
#[serde(default)]
|
||||
filter: Option<Value>,
|
||||
#[serde(default)]
|
||||
ip: Option<String>,
|
||||
#[serde(default)]
|
||||
events: Vec<UnparsedNote>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ReadInput {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
use serde::de::Error;
|
||||
let RawInput {
|
||||
msg_type,
|
||||
req_id,
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed,
|
||||
filter,
|
||||
ip,
|
||||
events,
|
||||
} = RawInput::deserialize(deserializer)?;
|
||||
|
||||
match msg_type.as_str() {
|
||||
"reqOpen" => Ok(ReadInput::ReqOpen {
|
||||
req_id: req_id.ok_or_else(|| D::Error::missing_field("reqId"))?,
|
||||
conn_id: conn_id.ok_or_else(|| D::Error::missing_field("connId"))?,
|
||||
sub_id: sub_id.ok_or_else(|| D::Error::missing_field("subId"))?,
|
||||
authed,
|
||||
filter,
|
||||
ip,
|
||||
}),
|
||||
"req" => Ok(ReadInput::Req {
|
||||
req_id: req_id.ok_or_else(|| D::Error::missing_field("reqId"))?,
|
||||
conn_id: conn_id.ok_or_else(|| D::Error::missing_field("connId"))?,
|
||||
sub_id: sub_id.ok_or_else(|| D::Error::missing_field("subId"))?,
|
||||
authed,
|
||||
events,
|
||||
}),
|
||||
"reqClose" => Ok(ReadInput::ReqClose {
|
||||
conn_id: conn_id.ok_or_else(|| D::Error::missing_field("connId"))?,
|
||||
sub_id: sub_id.ok_or_else(|| D::Error::missing_field("subId"))?,
|
||||
}),
|
||||
"connClose" => Ok(ReadInput::ConnClose {
|
||||
conn_id: conn_id.ok_or_else(|| D::Error::missing_field("connId"))?,
|
||||
}),
|
||||
other => Err(D::Error::unknown_variant(
|
||||
other,
|
||||
&["reqOpen", "req", "reqClose", "connClose"],
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Admission action returned to a `reqOpen`.
|
||||
#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ReadAction {
|
||||
/// Admit the subscription.
|
||||
Accept,
|
||||
/// Refuse / throttle the whole subscription.
|
||||
Reject,
|
||||
}
|
||||
|
||||
/// Response to a `reqOpen`: admit or refuse the subscription.
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReqOpenResponse {
|
||||
pub req_id: u64,
|
||||
pub action: ReadAction,
|
||||
/// Reason surfaced to the client on reject (optional).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub msg: Option<String>,
|
||||
/// Retry hint in milliseconds, appended to the reject message (optional).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub retry_ms: Option<u64>,
|
||||
/// Opt out of per-event filtering for this subscription. When `true` (only
|
||||
/// meaningful on an `accept`), the plugin declares it needs no `req`
|
||||
/// batches: strfry skips all per-event marshaling and delivers this
|
||||
/// subscription via its zero-copy fast path, while still sending
|
||||
/// `reqClose`/`connClose` so the plugin can free state. Omitted from the
|
||||
/// wire when `false`.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub passthrough: bool,
|
||||
}
|
||||
|
||||
impl ReqOpenResponse {
|
||||
/// Admit the subscription. With `passthrough`, opt out of per-event
|
||||
/// filtering: strfry never sends `req` for it and delivers via the
|
||||
/// zero-copy fast path.
|
||||
pub fn accept(req_id: u64, passthrough: bool) -> Self {
|
||||
ReqOpenResponse {
|
||||
req_id,
|
||||
action: ReadAction::Accept,
|
||||
msg: None,
|
||||
retry_ms: None,
|
||||
passthrough,
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse the subscription with an optional message and retry hint.
|
||||
pub fn reject(req_id: u64, msg: Option<String>, retry_ms: Option<u64>) -> Self {
|
||||
ReqOpenResponse {
|
||||
req_id,
|
||||
action: ReadAction::Reject,
|
||||
msg,
|
||||
retry_ms,
|
||||
passthrough: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Response to a `req`: the accept-list is authoritative. Every event in the
|
||||
/// batch whose id is NOT listed is withheld from this subscriber. (Delivering
|
||||
/// all = echo every id; withholding all = empty array.)
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReqResponse {
|
||||
pub req_id: u64,
|
||||
pub accept: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_req_open_with_filter_and_auth() {
|
||||
let line = r#"{"type":"reqOpen","reqId":7,"connId":3,"subId":"sub0","authed":"aa","filter":[{"kinds":[1]}]}"#;
|
||||
match serde_json::from_str::<ReadInput>(line).unwrap() {
|
||||
ReadInput::ReqOpen {
|
||||
req_id,
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed,
|
||||
filter,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(req_id, 7);
|
||||
assert_eq!(conn_id, 3);
|
||||
assert_eq!(sub_id, "sub0");
|
||||
assert_eq!(authed.as_deref(), Some("aa"));
|
||||
assert!(filter.is_some());
|
||||
}
|
||||
other => panic!("expected reqOpen, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_req_open_unauthed_no_filter() {
|
||||
let line = r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#;
|
||||
match serde_json::from_str::<ReadInput>(line).unwrap() {
|
||||
ReadInput::ReqOpen {
|
||||
authed, filter, ip, ..
|
||||
} => {
|
||||
assert!(authed.is_none());
|
||||
assert!(filter.is_none());
|
||||
// Absent `ip` field (older strfry) => None, still parses.
|
||||
assert!(ip.is_none());
|
||||
}
|
||||
other => panic!("expected reqOpen, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_req_open_with_ip() {
|
||||
let line = r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"127.0.0.1"}"#;
|
||||
match serde_json::from_str::<ReadInput>(line).unwrap() {
|
||||
ReadInput::ReqOpen { ip, .. } => assert_eq!(ip.as_deref(), Some("127.0.0.1")),
|
||||
other => panic!("expected reqOpen, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_req_with_events() {
|
||||
let event = r#"{"id":"ab","pubkey":"cd","content":"hi","created_at":1,"kind":1,"tags":[],"sig":"ef"}"#;
|
||||
let line =
|
||||
format!(r#"{{"type":"req","reqId":9,"connId":3,"subId":"sub0","events":[{event}]}}"#);
|
||||
match serde_json::from_str::<ReadInput>(&line).unwrap() {
|
||||
ReadInput::Req {
|
||||
req_id,
|
||||
conn_id,
|
||||
events,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(req_id, 9);
|
||||
assert_eq!(conn_id, 3);
|
||||
assert_eq!(events.len(), 1);
|
||||
// The raw wire bytes are captured verbatim...
|
||||
assert_eq!(events[0].size(), event.len());
|
||||
// ...and both the cheap id-only and full parse agree.
|
||||
assert_eq!(events[0].id().unwrap(), "ab");
|
||||
assert_eq!(events[0].parse().unwrap().id, "ab");
|
||||
}
|
||||
other => panic!("expected req, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unparsed_note_size_is_raw_wire_length() {
|
||||
// Deliberately include whitespace: size() must reflect the exact bytes
|
||||
// as delivered, not a re-minified form.
|
||||
let raw = r#"{"id": "ab", "kind": 1}"#;
|
||||
let note = UnparsedNote::from_json(raw).unwrap();
|
||||
assert_eq!(note.size(), raw.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unparsed_note_parse_round_trips() {
|
||||
let raw = r#"{"id":"ab","pubkey":"cd","content":"hi","created_at":1,"kind":1,"tags":[],"sig":"ef"}"#;
|
||||
let note = UnparsedNote::from_json(raw).unwrap();
|
||||
let parsed = note.parse().unwrap();
|
||||
assert_eq!(parsed.id, "ab");
|
||||
assert_eq!(parsed.pubkey, "cd");
|
||||
assert_eq!(parsed.kind, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_lifecycle_messages() {
|
||||
match serde_json::from_str::<ReadInput>(r#"{"type":"reqClose","connId":3,"subId":"sub0"}"#)
|
||||
.unwrap()
|
||||
{
|
||||
ReadInput::ReqClose { conn_id, sub_id } => {
|
||||
assert_eq!(conn_id, 3);
|
||||
assert_eq!(sub_id, "sub0");
|
||||
}
|
||||
other => panic!("expected reqClose, got {:?}", other),
|
||||
}
|
||||
|
||||
match serde_json::from_str::<ReadInput>(r#"{"type":"connClose","connId":3}"#).unwrap() {
|
||||
ReadInput::ConnClose { conn_id } => assert_eq!(conn_id, 3),
|
||||
other => panic!("expected connClose, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_responses_minified() {
|
||||
let accept = ReqOpenResponse::accept(2, false);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&accept).unwrap(),
|
||||
r#"{"reqId":2,"action":"accept"}"#
|
||||
);
|
||||
|
||||
let passthrough = ReqOpenResponse::accept(2, true);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&passthrough).unwrap(),
|
||||
r#"{"reqId":2,"action":"accept","passthrough":true}"#
|
||||
);
|
||||
|
||||
let reject = ReqOpenResponse::reject(2, Some("slow down".into()), Some(1000));
|
||||
assert_eq!(
|
||||
serde_json::to_string(&reject).unwrap(),
|
||||
r#"{"reqId":2,"action":"reject","msg":"slow down","retryMs":1000}"#
|
||||
);
|
||||
|
||||
let batch = ReqResponse {
|
||||
req_id: 5,
|
||||
accept: vec!["deadbeef".into()],
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_string(&batch).unwrap(),
|
||||
r#"{"reqId":5,"accept":["deadbeef"]}"#
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,815 @@
|
||||
//! Read-side (readPolicy) plugin engine.
|
||||
//!
|
||||
//! Speaks strfry's per-subscription REQ deliverability protocol
|
||||
//! ([`crate::readmsg`]) and drives a config-composed pipeline of
|
||||
//! [`ReadFilter`]s to make per-subscriber, per-event deliver/withhold decisions.
|
||||
//! It is the read-path counterpart to the write-side [`Noteguard`] engine in
|
||||
//! `main.rs`: a name-keyed `registered_filters` registry, a
|
||||
//! [`register_filter`](ReadPolicy::register_filter) hook, and a config-driven
|
||||
//! `pipeline: Vec<String>` composed in [`load_config`](ReadPolicy::load_config).
|
||||
//!
|
||||
//! ## Batch semantics (the check / commit split)
|
||||
//!
|
||||
//! Unlike the write side's pure `fn(event) -> action`, read filters carry
|
||||
//! cross-event state (a per-IP byte bucket, a per-conn counter) and can withhold
|
||||
//! the *rest* of a batch once a budget is exhausted. To compose these correctly
|
||||
//! the engine runs a **two-phase** batch loop per event:
|
||||
//!
|
||||
//! 1. [`filter_event`](ReadFilter::filter_event) — a *check* over the pipeline in
|
||||
//! order. First [`Skip`](EventVerdict::Skip) withholds just this event; first
|
||||
//! [`Stop`](EventVerdict::Stop) withholds this event and breaks the batch. A
|
||||
//! filter must not consume budget here.
|
||||
//! 2. [`on_delivered`](ReadFilter::on_delivered) — called on every filter, in
|
||||
//! order, *only if* every filter delivered the event, so counters/buckets
|
||||
//! advance exactly once and only for events that actually reach the client.
|
||||
//!
|
||||
//! This reproduces the old inline `continue`/`break` semantics faithfully: an
|
||||
//! event a later filter withholds never charges an earlier filter's budget.
|
||||
//!
|
||||
//! ## Fail-open
|
||||
//!
|
||||
//! Like strfry, this loop FAILS OPEN. Filters honour that internally (a guest
|
||||
//! trap delivers); the engine no-responds on unparseable input so strfry times
|
||||
//! out and delivers, and a bad/unknown pipeline entry is logged and skipped
|
||||
//! rather than aborting the loop.
|
||||
//!
|
||||
//! As an optimization, a subscription whose filters all report `!needs_events`
|
||||
//! answers `reqOpen` with `passthrough: true`, telling strfry to skip per-event
|
||||
//! marshaling and deliver via the zero-copy fast path (no `req` batches).
|
||||
|
||||
use crate::read_filter::{Admission, ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
use crate::readfilters::{MaxEventsPerConn, ReadBandwidth};
|
||||
use crate::readmsg::{ReadInput, ReqOpenResponse, ReqResponse, UnparsedNote};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, BufRead, Write};
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
use crate::readfilters::NScriptRead;
|
||||
|
||||
/// The `[readpolicy]` config table (read from `noteguard.toml`, or the file
|
||||
/// named by `$NOTEGUARD_CONFIG`). Mirrors the write-side `Config`: an ordered
|
||||
/// `pipeline` of filter names plus a `filters` map of each filter's own config.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct ReadPolicyConfig {
|
||||
/// Ordered list of read-filter names to compose. Empty => deliver all
|
||||
/// (every subscription is passthrough).
|
||||
pub pipeline: Vec<String>,
|
||||
|
||||
/// Per-filter config tables, keyed by filter name (`[readpolicy.filters.X]`).
|
||||
pub filters: HashMap<String, toml::Value>,
|
||||
}
|
||||
|
||||
/// Wrapper matching the surrounding `noteguard.toml` shape so the read loop can
|
||||
/// share the same config file as the write loop (the write-side `pipeline` and
|
||||
/// `filters` keys are ignored by serde here).
|
||||
#[derive(Deserialize, Default)]
|
||||
struct FileConfig {
|
||||
readpolicy: Option<ReadPolicyConfig>,
|
||||
}
|
||||
|
||||
/// Per-connection identity captured at `reqOpen` and freed at `connClose`.
|
||||
/// Cached because `req` batches carry no client IP, but a per-IP filter must
|
||||
/// meter on `req` — so the engine caches the IP (and `authed`, for whitelists)
|
||||
/// under `connId` and hands it to filters via [`ConnContext`].
|
||||
struct ConnInfo {
|
||||
ip: Option<String>,
|
||||
authed: Option<String>,
|
||||
}
|
||||
|
||||
/// Constructs a boxed [`ReadFilter`] from its TOML config. Mirrors the
|
||||
/// write-side `ConstructFilter`.
|
||||
type ConstructReadFilter = Box<fn(toml::Value) -> Result<Box<dyn ReadFilter>, toml::de::Error>>;
|
||||
|
||||
/// The read-policy engine: a name-keyed filter registry, the loaded pipeline,
|
||||
/// and the engine-owned shared per-connection context.
|
||||
#[derive(Default)]
|
||||
pub struct ReadPolicy {
|
||||
registered_filters: HashMap<String, ConstructReadFilter>,
|
||||
pipeline: Vec<Box<dyn ReadFilter>>,
|
||||
/// `connId` -> its IP/authed identity, cached at `reqOpen`. Freed at
|
||||
/// `connClose`.
|
||||
conn_info: HashMap<u64, ConnInfo>,
|
||||
}
|
||||
|
||||
impl ReadPolicy {
|
||||
/// A new engine with all built-in filters registered but an empty pipeline
|
||||
/// (call [`load_config`](Self::load_config) to compose it).
|
||||
pub fn new() -> Self {
|
||||
let mut rp = ReadPolicy::default();
|
||||
rp.register_builtin_filters();
|
||||
rp
|
||||
}
|
||||
|
||||
/// Register a read filter, keyed by its [`name`](ReadFilter::name). Mirrors
|
||||
/// the write-side `register_filter`.
|
||||
pub fn register_filter<F: ReadFilter + '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 ReadFilter>)
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// All built-in read filters, available on every new [`ReadPolicy`]. The
|
||||
/// guest (`nscript`) filter is registered only in `nscript` builds.
|
||||
fn register_builtin_filters(&mut self) {
|
||||
self.register_filter::<MaxEventsPerConn>();
|
||||
self.register_filter::<ReadBandwidth>();
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
self.register_filter::<NScriptRead>();
|
||||
}
|
||||
|
||||
/// Compose the pipeline from config. Unlike the write side (which panics on a
|
||||
/// bad/unknown pipeline entry), the read side fails open: a bad or unknown
|
||||
/// entry is logged and skipped, since a misconfigured read filter must not
|
||||
/// take down a subscriber's feed.
|
||||
pub fn load_config(&mut self, config: &ReadPolicyConfig) {
|
||||
self.pipeline.clear();
|
||||
|
||||
for name in &config.pipeline {
|
||||
let cfg = config
|
||||
.filters
|
||||
.get(name)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| toml::Value::Table(Default::default()));
|
||||
|
||||
match self.registered_filters.get(name.as_str()) {
|
||||
Some(constructor) => match constructor(cfg) {
|
||||
Ok(filter) => self.pipeline.push(filter),
|
||||
Err(e) => log::error!(
|
||||
"readpolicy: bad config for filter '{}' ({}); skipping (fail open)",
|
||||
name,
|
||||
e
|
||||
),
|
||||
},
|
||||
None => log::error!(
|
||||
"readpolicy: unknown read filter '{}'; skipping (fail open)",
|
||||
name
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle one input line. Returns `Some(json)` to write back for
|
||||
/// `reqOpen`/`req`, or `None` for the fire-and-forget lifecycle messages
|
||||
/// (`reqClose`/`connClose`) and unparseable input (strfry fails open on no
|
||||
/// response).
|
||||
pub fn handle(&mut self, line: &str) -> Option<String> {
|
||||
let input: ReadInput = match serde_json::from_str(line) {
|
||||
Ok(input) => input,
|
||||
Err(e) => {
|
||||
// Can't recover a reqId, so we can't respond; strfry will time
|
||||
// out and deliver (fail open).
|
||||
log::error!("readpolicy: unparseable input ({}): {}", e, line);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
match input {
|
||||
ReadInput::ReqOpen {
|
||||
req_id,
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed,
|
||||
filter,
|
||||
ip,
|
||||
} => {
|
||||
log::info!(
|
||||
"reqOpen conn={} sub={} authed={:?} ip={:?} filter={}",
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed,
|
||||
ip,
|
||||
filter.as_ref().map(|f| f.to_string()).unwrap_or_default()
|
||||
);
|
||||
Some(json(
|
||||
&self.req_open(req_id, conn_id, sub_id, authed, ip, filter),
|
||||
))
|
||||
}
|
||||
|
||||
ReadInput::Req {
|
||||
req_id,
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed: _,
|
||||
events,
|
||||
} => {
|
||||
let accept = self.filter_batch(conn_id, &sub_id, &events);
|
||||
log::info!(
|
||||
"req conn={} sub={} events={} delivered={}",
|
||||
conn_id,
|
||||
sub_id,
|
||||
events.len(),
|
||||
accept.len()
|
||||
);
|
||||
Some(json(&ReqResponse { req_id, accept }))
|
||||
}
|
||||
|
||||
ReadInput::ReqClose { conn_id, sub_id } => {
|
||||
log::info!("reqClose conn={} sub={}", conn_id, sub_id);
|
||||
for filter in &mut self.pipeline {
|
||||
filter.req_close(conn_id, &sub_id);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
ReadInput::ConnClose { conn_id } => {
|
||||
log::info!("connClose conn={}", conn_id);
|
||||
for filter in &mut self.pipeline {
|
||||
filter.conn_close(conn_id);
|
||||
}
|
||||
self.conn_info.remove(&conn_id);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Admit (or refuse) a subscription. Caches the connection identity, runs
|
||||
/// every filter's `req_open`, and composes the result: reject if any filter
|
||||
/// rejects (first message wins), else accept — with `passthrough` iff NO
|
||||
/// filter needs per-event batches.
|
||||
fn req_open(
|
||||
&mut self,
|
||||
req_id: u64,
|
||||
conn_id: u64,
|
||||
sub_id: String,
|
||||
authed: Option<String>,
|
||||
ip: Option<String>,
|
||||
filter: Option<serde_json::Value>,
|
||||
) -> ReqOpenResponse {
|
||||
// Cache the connection's identity so per-IP filters can meter on `req`,
|
||||
// which carries no IP. Refreshed on each reqOpen (a connection's IP is
|
||||
// stable, but a later AUTH can add an authed pubkey).
|
||||
self.conn_info.insert(
|
||||
conn_id,
|
||||
ConnInfo {
|
||||
ip: ip.clone(),
|
||||
authed: authed.clone(),
|
||||
},
|
||||
);
|
||||
|
||||
let ctx = ConnContext {
|
||||
conn_id,
|
||||
sub_id: &sub_id,
|
||||
ip: ip.as_deref(),
|
||||
authed: authed.as_deref(),
|
||||
};
|
||||
|
||||
// Run req_open on EVERY filter (so each allocates its per-sub state and
|
||||
// gets symmetric reqClose/connClose cleanup even under reject), while
|
||||
// collecting the composed decision.
|
||||
let mut needs_events = false;
|
||||
let mut reject: Option<(Option<String>, Option<u64>)> = None;
|
||||
for f in &mut self.pipeline {
|
||||
let decision = f.req_open(&ctx, filter.as_ref());
|
||||
let OpenDecision {
|
||||
admission,
|
||||
needs_events: filter_needs,
|
||||
} = decision;
|
||||
needs_events |= filter_needs;
|
||||
if reject.is_none() {
|
||||
if let Admission::Reject { msg, retry_ms } = admission {
|
||||
reject = Some((msg, retry_ms));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((msg, retry_ms)) = reject {
|
||||
return ReqOpenResponse::reject(req_id, msg, retry_ms);
|
||||
}
|
||||
|
||||
// Passthrough iff no filter needs per-event work: strfry skips per-event
|
||||
// marshaling and delivers via its zero-copy fast path.
|
||||
ReqOpenResponse::accept(req_id, !needs_events)
|
||||
}
|
||||
|
||||
/// Decide which events in a batch to deliver by running the two-phase
|
||||
/// pipeline (see the module docs). Returns the accept-list of event ids.
|
||||
fn filter_batch(&mut self, conn_id: u64, sub_id: &str, events: &[UnparsedNote]) -> Vec<String> {
|
||||
// Resolve the connection's cached identity (req carries no IP).
|
||||
// Destructured so the conn_info borrow is disjoint from the pipeline's.
|
||||
let ReadPolicy {
|
||||
pipeline,
|
||||
conn_info,
|
||||
..
|
||||
} = self;
|
||||
let conn = conn_info.get(&conn_id);
|
||||
let ctx = ConnContext {
|
||||
conn_id,
|
||||
sub_id,
|
||||
ip: conn.and_then(|c| c.ip.as_deref()),
|
||||
authed: conn.and_then(|c| c.authed.as_deref()),
|
||||
};
|
||||
|
||||
// The accept-list can never exceed the batch.
|
||||
let mut accept = Vec::with_capacity(events.len());
|
||||
'batch: for ev in events {
|
||||
// Phase 1: check the pipeline in order. First Skip withholds this
|
||||
// event; first Stop withholds this event and the rest of the batch.
|
||||
let mut deliver = true;
|
||||
for filter in pipeline.iter_mut() {
|
||||
match filter.filter_event(&ctx, ev) {
|
||||
EventVerdict::Deliver => {}
|
||||
EventVerdict::Skip => {
|
||||
deliver = false;
|
||||
break;
|
||||
}
|
||||
EventVerdict::Stop => break 'batch,
|
||||
}
|
||||
}
|
||||
if !deliver {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Phase 2: the event is delivered by ALL filters — commit budget.
|
||||
for filter in pipeline.iter_mut() {
|
||||
filter.on_delivered(&ctx, ev);
|
||||
}
|
||||
|
||||
// Accept-list needs the id. A cheap id-only parse — the bandwidth-
|
||||
// only path still never full-parses. A malformed id (should not
|
||||
// happen post-delivery) just drops the event from the accept-list.
|
||||
match ev.id() {
|
||||
Ok(id) => accept.push(id),
|
||||
Err(e) => log::error!("readpolicy: unparseable event id (withholding): {}", e),
|
||||
}
|
||||
}
|
||||
accept
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize a response to minified JSON (never fails for our types).
|
||||
fn json<T: serde::Serialize>(msg: &T) -> String {
|
||||
serde_json::to_string(msg).expect("read policy response should always serialize")
|
||||
}
|
||||
|
||||
/// Load the `[readpolicy]` table from the shared config file
|
||||
/// ([`crate::config_path`]). A missing file or absent `[readpolicy]` table
|
||||
/// yields the default (empty pipeline => deliver-all) config.
|
||||
///
|
||||
/// (Named apart from [`ReadPolicy::load_config`], which composes the pipeline
|
||||
/// from an already-parsed config.)
|
||||
fn read_config_file() -> ReadPolicyConfig {
|
||||
let path = crate::config_path();
|
||||
|
||||
let contents = match std::fs::read_to_string(&path) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::warn!("readpolicy: no config at {} ({}); delivering all", path, e);
|
||||
return ReadPolicyConfig::default();
|
||||
}
|
||||
};
|
||||
|
||||
match toml::from_str::<FileConfig>(&contents) {
|
||||
Ok(cfg) => cfg.readpolicy.unwrap_or_default(),
|
||||
Err(e) => {
|
||||
log::error!("readpolicy: bad config {} ({}); delivering all", path, e);
|
||||
ReadPolicyConfig::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `noteguard read` entrypoint: read line-delimited JSON requests from
|
||||
/// stdin, write line-delimited JSON responses to stdout (line-buffered).
|
||||
pub fn run() {
|
||||
log::info!("running noteguard read policy");
|
||||
let config = read_config_file();
|
||||
log::info!(
|
||||
"readpolicy pipeline: {:?} ({} filter configs)",
|
||||
config.pipeline,
|
||||
config.filters.len()
|
||||
);
|
||||
|
||||
let mut engine = ReadPolicy::new();
|
||||
engine.load_config(&config);
|
||||
|
||||
let stdin = io::stdin();
|
||||
let stdout = io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
|
||||
for line in stdin.lock().lines() {
|
||||
let line = match line {
|
||||
Ok(line) => line,
|
||||
Err(e) => {
|
||||
eprintln!("readpolicy: failed to read line: {}", e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(response) = engine.handle(&line) {
|
||||
if writeln!(out, "{}", response).is_err() {
|
||||
break;
|
||||
}
|
||||
// strfry reads a response per request; keep the pipe line-buffered.
|
||||
let _ = out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Build an engine from a `[readpolicy]`-inner TOML fragment (pipeline +
|
||||
/// filter tables), exercising the real registry + config path.
|
||||
///
|
||||
/// NB: every `read_bandwidth` fragment below sets `shared_state_path = ""`
|
||||
/// (the per-process opt-out). Unset, the filter now DEFAULTS to the shared
|
||||
/// `/dev/shm` file, so tests would share (and pollute) one real host path and
|
||||
/// cross-contaminate each other's buckets — `""` gives each test a fresh,
|
||||
/// isolated, in-process map.
|
||||
fn engine(config: &str) -> ReadPolicy {
|
||||
let config: ReadPolicyConfig = toml::from_str(config).expect("test config parses");
|
||||
let mut engine = ReadPolicy::new();
|
||||
engine.load_config(&config);
|
||||
engine
|
||||
}
|
||||
|
||||
/// An [`UnparsedNote`] built from wire JSON so `size()` is realistic.
|
||||
fn unparsed_note(id: &str, kind: i64, content: &str) -> UnparsedNote {
|
||||
let json = format!(
|
||||
r#"{{"id":"{}","pubkey":"00","content":"{}","created_at":0,"kind":{},"tags":[],"sig":"00"}}"#,
|
||||
id, content, kind
|
||||
);
|
||||
UnparsedNote::from_json(&json).unwrap()
|
||||
}
|
||||
|
||||
fn events(ids: &[&str]) -> Vec<UnparsedNote> {
|
||||
ids.iter().map(|id| unparsed_note(id, 1, "")).collect()
|
||||
}
|
||||
|
||||
fn parse_accept(json: &str) -> Vec<String> {
|
||||
let v: serde_json::Value = serde_json::from_str(json).unwrap();
|
||||
v["accept"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|x| x.as_str().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_pipeline_delivers_all_via_passthrough() {
|
||||
// No filters => no per-event work => passthrough (strfry fast path).
|
||||
let mut engine = engine("pipeline = []");
|
||||
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","authed":"aa"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept","passthrough":true}"#);
|
||||
|
||||
// Belt-and-suspenders: if an older strfry still sends `req` for a
|
||||
// passthrough sub, we deliver everything anyway.
|
||||
let resp = engine
|
||||
.handle(
|
||||
r#"{"type":"req","reqId":1,"connId":1,"subId":"s","events":[{"id":"a","pubkey":"0","content":"","created_at":0,"kind":1,"tags":[],"sig":"0"},{"id":"b","pubkey":"0","content":"","created_at":0,"kind":1,"tags":[],"sig":"0"}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(parse_accept(&resp), vec!["a", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_throttle_disables_passthrough() {
|
||||
// A configured throttle means strfry must keep sending `req` batches so
|
||||
// the connId counter can shrink delivery — so NOT passthrough.
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 10
|
||||
"#,
|
||||
);
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept"}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_throttle_caps_delivery_per_connection() {
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 3
|
||||
"#,
|
||||
);
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":7,"subId":"s"}"#);
|
||||
|
||||
// Two batches of 2 events; only the first 3 (across batches) deliver.
|
||||
let first = engine.filter_batch(7, "s", &events(&["a", "b"]));
|
||||
assert_eq!(first, vec!["a", "b"]);
|
||||
|
||||
let second = engine.filter_batch(7, "s", &events(&["c", "d"]));
|
||||
assert_eq!(second, vec!["c"]); // 3rd delivered, 4th withheld by cap
|
||||
|
||||
let third = engine.filter_batch(7, "s", &events(&["e"]));
|
||||
assert!(third.is_empty()); // cap already reached
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conn_close_frees_state_and_lifecycle_is_silent() {
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 1
|
||||
"#,
|
||||
);
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#);
|
||||
|
||||
// Deliver the one allowed event, then the cap is hit.
|
||||
assert_eq!(engine.filter_batch(1, "s", &events(&["a"])), vec!["a"]);
|
||||
assert!(engine.filter_batch(1, "s", &events(&["b"])).is_empty());
|
||||
|
||||
// Lifecycle messages produce no response.
|
||||
assert!(engine
|
||||
.handle(r#"{"type":"reqClose","connId":1,"subId":"s"}"#)
|
||||
.is_none());
|
||||
assert!(engine
|
||||
.handle(r#"{"type":"connClose","connId":1}"#)
|
||||
.is_none());
|
||||
assert!(!engine.conn_info.contains_key(&1));
|
||||
|
||||
// After connClose the per-conn counter is freed: reopening the same
|
||||
// connId delivers again.
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#);
|
||||
assert_eq!(engine.filter_batch(1, "s", &events(&["c"])), vec!["c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_disables_passthrough() {
|
||||
// A bandwidth budget means strfry must keep sending `req` so we can meter
|
||||
// bytes — so NOT passthrough, even with no guest and no count cap.
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["read_bandwidth"]
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = 1000
|
||||
shared_state_path = ""
|
||||
"#,
|
||||
);
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"1.2.3.4"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept"}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_caps_delivery_by_bytes() {
|
||||
// Budget for exactly two events' worth of bytes (single-char ids => all
|
||||
// events are the same wire size). Refill over the sub-ms test window
|
||||
// floors to ~0, so the byte cap is deterministic.
|
||||
let size = unparsed_note("a", 1, "").size() as u64;
|
||||
let mut engine = engine(&format!(
|
||||
r#"
|
||||
pipeline = ["read_bandwidth"]
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = {}
|
||||
shared_state_path = ""
|
||||
"#,
|
||||
size * 2 + 1
|
||||
));
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"9.9.9.9"}"#);
|
||||
|
||||
// First two fit the budget; the rest are withheld once bytes run out.
|
||||
assert_eq!(
|
||||
engine.filter_batch(1, "s", &events(&["a", "b", "c", "d"])),
|
||||
vec!["a", "b"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_keyed_per_ip_survives_reconnect() {
|
||||
// Budget for exactly one event.
|
||||
let size = unparsed_note("a", 1, "").size() as u64;
|
||||
let mut engine = engine(&format!(
|
||||
r#"
|
||||
pipeline = ["read_bandwidth"]
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = {}
|
||||
shared_state_path = ""
|
||||
"#,
|
||||
size + 1
|
||||
));
|
||||
|
||||
// connId=1 from ip X spends the whole budget on its first event.
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"1.2.3.4"}"#);
|
||||
let first = engine.filter_batch(1, "s", &events(&["a", "b"]));
|
||||
assert_eq!(first, vec!["a"]); // 2nd withheld; bucket now ~empty
|
||||
|
||||
// Reconnect: brand-new connId, SAME ip. Because the bucket is keyed by IP
|
||||
// (and not evicted on connClose), the budget is still empty.
|
||||
engine.handle(r#"{"type":"connClose","connId":1}"#);
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":2,"subId":"s","ip":"1.2.3.4"}"#);
|
||||
let second = engine.filter_batch(2, "s", &events(&["c"]));
|
||||
assert!(second.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_whitelist_exempts_and_passes_through() {
|
||||
// Whitelisted IP: the bandwidth gate is skipped entirely, so delivery
|
||||
// continues past a budget that would otherwise cap it — and, doing no
|
||||
// per-event work, the subscription is reported passthrough.
|
||||
let size = unparsed_note("a", 1, "").size() as u64;
|
||||
let mut engine = engine(&format!(
|
||||
r#"
|
||||
pipeline = ["read_bandwidth"]
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = {}
|
||||
whitelist = ["5.5.5.5"]
|
||||
shared_state_path = ""
|
||||
"#,
|
||||
size
|
||||
));
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"5.5.5.5"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept","passthrough":true}"#);
|
||||
|
||||
// And even if strfry sends `req`, all events deliver (no metering).
|
||||
assert_eq!(
|
||||
engine.filter_batch(1, "s", &events(&["a", "b", "c"])),
|
||||
vec!["a", "b", "c"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_rejects_at_open_when_drained() {
|
||||
// Budget for exactly one event. The first sub drains the IP's bucket; a
|
||||
// fresh REQ from the SAME IP is then rejected OUTRIGHT at reqOpen with a
|
||||
// CLOSED (msg + retryMs) — real backpressure — rather than a silent
|
||||
// empty feed. The not-yet-drained accept case is covered by
|
||||
// `bandwidth_disables_passthrough`.
|
||||
let size = unparsed_note("a", 1, "").size() as u64;
|
||||
let mut engine = engine(&format!(
|
||||
r#"
|
||||
pipeline = ["read_bandwidth"]
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = {}
|
||||
shared_state_path = ""
|
||||
"#,
|
||||
size + 1
|
||||
));
|
||||
|
||||
// Fresh IP: admitted (a full bucket affords the nominal event).
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"1.2.3.4"}"#)
|
||||
.unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&open).unwrap();
|
||||
assert_eq!(v["action"], "accept");
|
||||
|
||||
// Spend the whole budget on the one affordable event.
|
||||
assert_eq!(engine.filter_batch(1, "s", &events(&["a"])), vec!["a"]);
|
||||
|
||||
// Reconnect from the SAME IP (bucket keyed by IP, never evicted): now
|
||||
// drained, so reqOpen is rejected with a CLOSED + retry hint.
|
||||
engine.handle(r#"{"type":"connClose","connId":1}"#);
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":9,"connId":2,"subId":"s2","ip":"1.2.3.4"}"#)
|
||||
.unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&open).unwrap();
|
||||
assert_eq!(v["reqId"], 9);
|
||||
assert_eq!(v["action"], "reject");
|
||||
assert!(v["msg"].as_str().unwrap().contains("bandwidth"));
|
||||
assert!(v["retryMs"].as_u64().unwrap() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_rejects_at_open_when_cap_reached() {
|
||||
// Once a connection has been delivered its lifetime cap, a new sub on the
|
||||
// same connId is rejected at reqOpen (CLOSED, no retryMs — the cap has no
|
||||
// refill on this connId, so a same-connId retry is futile). The
|
||||
// not-yet-capped accept case is covered by
|
||||
// `count_throttle_disables_passthrough`.
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 1
|
||||
"#,
|
||||
);
|
||||
// Fresh conn: admitted.
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept"}"#);
|
||||
|
||||
// Deliver the one allowed event to reach the cap.
|
||||
assert_eq!(engine.filter_batch(1, "s", &events(&["a"])), vec!["a"]);
|
||||
|
||||
// A new sub on the SAME connId is now rejected — message, NO retryMs.
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":3,"connId":1,"subId":"s2"}"#)
|
||||
.unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&open).unwrap();
|
||||
assert_eq!(v["action"], "reject");
|
||||
assert!(v["msg"].as_str().unwrap().contains("cap reached"));
|
||||
assert!(v["retryMs"].is_null());
|
||||
|
||||
// A reconnect (fresh connId) resets the counter and is admitted again.
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":4,"connId":2,"subId":"s"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":4,"action":"accept"}"#);
|
||||
}
|
||||
|
||||
/// A test-only filter that withholds (`Skip`) any event whose id starts with
|
||||
/// `x`, and otherwise delivers. Used to exercise cross-filter composition
|
||||
/// (an earlier stateful filter must not charge an event a later filter
|
||||
/// withholds).
|
||||
#[derive(Default)]
|
||||
struct SkipX;
|
||||
impl ReadFilter for SkipX {
|
||||
fn name(&self) -> &'static str {
|
||||
"skip_x"
|
||||
}
|
||||
fn req_open(
|
||||
&mut self,
|
||||
_ctx: &ConnContext,
|
||||
_filter: Option<&serde_json::Value>,
|
||||
) -> OpenDecision {
|
||||
OpenDecision::needs_events()
|
||||
}
|
||||
fn filter_event(&mut self, _ctx: &ConnContext, ev: &UnparsedNote) -> EventVerdict {
|
||||
if ev.id().unwrap().starts_with('x') {
|
||||
EventVerdict::Skip
|
||||
} else {
|
||||
EventVerdict::Deliver
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ReadPolicy {
|
||||
/// Build an engine from pre-constructed filters (test-only, so a pipeline
|
||||
/// can include a filter that isn't in the registry).
|
||||
fn from_pipeline(pipeline: Vec<Box<dyn ReadFilter>>) -> Self {
|
||||
ReadPolicy {
|
||||
registered_filters: HashMap::new(),
|
||||
pipeline,
|
||||
conn_info: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skip_does_not_charge_an_earlier_stateful_filter() {
|
||||
// The crux of the check/commit split. Pipeline [count(max=2), skip_x].
|
||||
// count's counter must advance only for events delivered by the WHOLE
|
||||
// pipeline — a skipped event must NOT consume the count budget.
|
||||
let mut engine = ReadPolicy::from_pipeline(vec![
|
||||
Box::new(MaxEventsPerConn {
|
||||
max: 2,
|
||||
..Default::default()
|
||||
}),
|
||||
Box::new(SkipX),
|
||||
]);
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#);
|
||||
|
||||
// "x0" is skipped and must not charge count; then a, b deliver (using the
|
||||
// whole cap of 2); c is stopped by the cap. If count had charged the
|
||||
// skipped "x0", only "a" would survive.
|
||||
assert_eq!(
|
||||
engine.filter_batch(1, "s", &events(&["x0", "a", "b", "c"])),
|
||||
vec!["a", "b"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_and_bandwidth_compose() {
|
||||
// count cap 5, bandwidth budget for 2 events, pipeline [count, bandwidth]:
|
||||
// bandwidth is the binding constraint here and caps the batch at 2.
|
||||
let size = unparsed_note("a", 1, "").size() as u64;
|
||||
let mut engine = engine(&format!(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn", "read_bandwidth"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 5
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = {}
|
||||
shared_state_path = ""
|
||||
"#,
|
||||
size * 2 + 1
|
||||
));
|
||||
// Both throttles need events, so the sub is non-passthrough.
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"7.7.7.7"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept"}"#);
|
||||
|
||||
assert_eq!(
|
||||
engine.filter_batch(1, "s", &events(&["a", "b", "c"])),
|
||||
vec!["a", "b"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
{"type": "new","receivedAt":12345,"sourceType":"IP4","sourceInfo": "127.0.0.3","event":{"id":"eabb9491951fc64d85b6cba28a7d53c333c3f1d59779d63abccf9a8f61a0bdef","pubkey":"5f54041530509de28550475bfe73db709609a4ee1e59281527ba81692923418f","created_at":1722305142,"kind":1,"tags":[["t","lightning"],["t","zapping"],["t","introductions"],["t","freefrom"],["t","help"],["t","nostr"],["t","plebchain"],["t","zapathon"],["t","damus"],["t","bitcoin"],["t","anime"],["t","grownostr"],["t","music"],["t","programming"],["t","cat"],["t","dog"],["t","nsfw"],["t","asknostr"],["t","foodstr"],["t","sports"],["t","acg"],["t","game"],["t","movie"],["t","book"],["t","art"],["t","tech"],["t","science"]],"content":"Freefrom is running out of funds and is about to close down. Please scan the QR code to donate.\n Freefrom 资金不足即将倒闭,请扫描二维码捐款\n https://ice.frostsky.com/2024/07/29/9e447d397cac0c27993f0cbcb6efb235.png\n https://cdn.nostr.build/i/270de92fa4e5118a28352720b7f26c360aa2dbfdb1c12517f3e3117a2f9de47a.png\n ","sig":"6fa13bedffb2250e2437af6898ab3b11444eb3aef5fd4b484b25658632d283774186f98a024c225581cd9bbaccb0966fa1360d13fd5671f97c7f7bf515f94166"}}
|
||||
{"type": "new","receivedAt":12345,"sourceType":"IP4","sourceInfo": "127.0.0.3","event":{"id": "70651d96a2b6b3431cc06b7543249ccd22ab5c203c6aa590b7688f916f252f8f","pubkey": "879d67486027539073d6531d271e3791b15c3e48becbfe4c3727e93355330cc8","created_at": 1720545068,"kind": 1,"tags": [["-"]],"content": "hello there","sig": "21a901e3663bac846493df588ad2185751a5a2826a64c26afb9edce8f9d9344cf00c1ea43016e7faca69da661eadd2731b457a0c31b207ab6ed509a047bf7845"}}
|
||||
{"type": "new","receivedAt":12345,"sourceType":"IP4","sourceInfo": "127.0.0.3","event":{"id": "68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","pubkey": "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at": 1720408658,"kind": 1,"tags": [],"content": "hi","sig": "7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type": "new","receivedAt":12345,"sourceType":"IP4","sourceInfo": "127.0.0.3","event":{"id": "68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","pubkey": "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at": 1720408658,"kind": 1,"tags": [],"content": "hi","sig": "7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
|
||||
Reference in New Issue
Block a user