Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b25aa6cf8 | ||
|
|
d2f160e0f3 | ||
|
|
059e763022 | ||
|
|
f63e2d9087 | ||
|
|
70a69aa114 | ||
|
|
9ee6254697 | ||
|
|
a9e4c044bf | ||
|
|
0e29aab85a | ||
|
|
3fdd9738c9 | ||
|
|
215b98576e | ||
|
|
d867e64974 | ||
|
|
c46029d2d7 | ||
|
|
44d61df9c9 | ||
|
|
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 |
Generated
+1524
-46
File diff suppressed because it is too large
Load Diff
+22
-2
@@ -5,15 +5,35 @@ 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"]
|
||||
# remote: fetch [sources] lists (premium members, blacklists) over http(s)
|
||||
remote = ["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"] }
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
# Deploying Azzamo Noteguard
|
||||
|
||||
One binary, two configs:
|
||||
|
||||
| Relay | Config |
|
||||
|---|---|
|
||||
| nostr.azzamo.net (free) | [noteguard-free.example.toml](noteguard-free.example.toml) |
|
||||
| relay, us, asia (premium) | [noteguard-premium.example.toml](noteguard-premium.example.toml) |
|
||||
|
||||
## 1. Build
|
||||
|
||||
Rust 1.88 or newer is required for the `remote` and `cloudflare` features.
|
||||
|
||||
```sh
|
||||
cargo build --release --features remote,cloudflare
|
||||
cargo test --features remote,cloudflare
|
||||
```
|
||||
|
||||
For a static binary, build for `x86_64-unknown-linux-musl` with the same
|
||||
features. rustls pulls in `ring`, which needs a musl C toolchain
|
||||
(`musl-tools` on Debian) on the build host.
|
||||
|
||||
## 2. Prepare each relay host
|
||||
|
||||
- [ ] Fill in the real API URLs in the config (replace every `CHANGEME`).
|
||||
- [ ] Copy the config to e.g. `/etc/noteguard/free.toml` or `/etc/noteguard/premium.toml`.
|
||||
- [ ] Create the cache directory, writable by the user strfry runs as:
|
||||
`install -d -o strfry -g strfry /var/lib/noteguard`
|
||||
(or `StateDirectory=noteguard` in the systemd unit).
|
||||
- [ ] Give strfry the environment. noteguard inherits strfry's environment, so
|
||||
set it on the strfry service, for example in a systemd drop-in:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
Environment=NOTEGUARD_CONFIG=/etc/noteguard/premium.toml
|
||||
Environment=RUST_LOG=info
|
||||
EnvironmentFile=/etc/noteguard/secrets.env
|
||||
```
|
||||
|
||||
with `/etc/noteguard/secrets.env` (mode 600) holding
|
||||
`AZZAMO_API_TOKEN=...` and, if Cloudflare edge bans are used,
|
||||
`CLOUDFLARE_API_TOKEN=...`. Then `systemctl daemon-reload`.
|
||||
|
||||
## 3. Smoke test on the host, before switching strfry over
|
||||
|
||||
```sh
|
||||
sudo -u strfry env NOTEGUARD_CONFIG=/etc/noteguard/premium.toml RUST_LOG=info \
|
||||
AZZAMO_API_TOKEN=... ./noteguard.new < test/inputs
|
||||
```
|
||||
|
||||
Check the log lines on stderr:
|
||||
|
||||
- `source premium: loaded N entries (M skipped)` for every source. A large `M`
|
||||
means the API shape does not match what noteguard expects.
|
||||
- No `token_env $AZZAMO_API_TOKEN is not set`.
|
||||
- No `fetch failed ... no usable cache`.
|
||||
|
||||
Then check the cache files exist in `/var/lib/noteguard/`.
|
||||
|
||||
Expected verdicts: on the premium config, a note from a non-member is
|
||||
rejected with the `whitelist.message`; on the free config it is accepted.
|
||||
|
||||
## 4. Install
|
||||
|
||||
```sh
|
||||
cp /path/strfry/noteguard /path/strfry/noteguard.prev
|
||||
cp /etc/noteguard/premium.toml /etc/noteguard/premium.toml.prev # if one existed
|
||||
install -m755 noteguard.new /path/strfry/noteguard.tmp
|
||||
mv /path/strfry/noteguard.tmp /path/strfry/noteguard
|
||||
```
|
||||
|
||||
Always replace the binary with `mv` (an atomic rename), never `cp` over the
|
||||
running file. strfry relaunches the write plugin when the plugin file changes;
|
||||
if in doubt, restart strfry. noteguard reads its config only at startup, so
|
||||
after a config-only change `touch` the binary or restart strfry.
|
||||
|
||||
Point strfry at it (`strfry.conf`):
|
||||
|
||||
```
|
||||
writePolicy {
|
||||
plugin = "/path/strfry/noteguard"
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Rollout order
|
||||
|
||||
1. Free relay first. Watch the log for one reload interval (5 minutes): every
|
||||
source should reload cleanly, and premium members should not be rate limited.
|
||||
2. One premium relay (asia). Post as a member (accepted) and as a non-member
|
||||
(rejected). Watch for one reload interval.
|
||||
3. The remaining premium relays (us, then relay).
|
||||
|
||||
## 6. Rollback
|
||||
|
||||
On the affected relay:
|
||||
|
||||
```sh
|
||||
mv /path/strfry/noteguard.prev /path/strfry/noteguard
|
||||
mv /etc/noteguard/premium.toml.prev /etc/noteguard/premium.toml # if the config changed
|
||||
```
|
||||
|
||||
Then make sure strfry picked it up: restart strfry, or `touch` the binary if
|
||||
only the config changed. The cache files in `/var/lib/noteguard/` can stay;
|
||||
older binaries ignore them.
|
||||
|
||||
Every new config key is optional, so the previous config also runs on the new
|
||||
binary: rolling back the config alone turns the new behavior off.
|
||||
|
||||
## Operational notes
|
||||
|
||||
- If the API is down, each relay keeps its last good lists. Member expiries
|
||||
still apply to that stale copy, but new payments and revocations wait until
|
||||
the API is back.
|
||||
- A premium relay that starts with no list and no cache rejects every
|
||||
non-whitelisted writer with `whitelist.unavailable_message` until the first
|
||||
successful fetch. Keep `cache_path` set to avoid this.
|
||||
- API load is roughly (relays x strfry ingester threads x sources) requests
|
||||
every `reload_secs`.
|
||||
- Zap receipts (kind 9735) and NIP-17 gift wraps (kind 1059) addressed to
|
||||
members are signed by non-member keys, so premium relays reject them.
|
||||
- Events arriving through strfry router or sync pass through the same
|
||||
filters, so an expired member's notes stop syncing into premium relays.
|
||||
@@ -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,9 +1,27 @@
|
||||
# Azzamo Noteguard
|
||||
|
||||
# noteguard
|
||||
A high performance note filter plugin system for [strfry], extended to run the
|
||||
Azzamo relays. It is a fork of [damus-io/noteguard] and keeps all of its
|
||||
filters; one binary and one codebase serve every relay, each with its own
|
||||
`noteguard.toml`:
|
||||
|
||||
A high performance note filter plugin system for [strfry]
|
||||
| Relay | Who can write | Config |
|
||||
|---|---|---|
|
||||
| nostr.azzamo.net (free) | Everyone, rate limited per IP. Premium members skip the rate limit and IP bans. | [noteguard-free.example.toml](noteguard-free.example.toml) |
|
||||
| relay, us, asia (premium) | Active premium members only. | [noteguard-premium.example.toml](noteguard-premium.example.toml) |
|
||||
|
||||
WIP!
|
||||
On both, every note is also checked against the Azzamo pubkey and word
|
||||
blacklists. What this fork adds on top of upstream:
|
||||
|
||||
- **Remote lists ([Sources](#sources))**: premium members, blacklisted pubkeys and blocked words fetched from the Azzamo API (or a file), reloaded in the background, with the last good copy kept through outages and an optional disk cache for restarts. Premium entries carry an expiry that is checked on every note.
|
||||
- **Premium gate**: `whitelist.pubkey_sources` lets only active members write, and fails closed if the member list could not be loaded.
|
||||
- **Premium exemptions**: `ratelimit.exempt_source` and `content.exempt_source` let members skip rate limits and IP bans.
|
||||
- **Custom rejection messages** for every filter ([Rejection messages](#rejection-messages)), with the old texts as defaults.
|
||||
- **NIP-05 lists**: accept only the pubkeys in a `nostr.json` `names` map.
|
||||
|
||||
Without any of the new keys, noteguard behaves exactly like upstream; a golden
|
||||
output test guards that. [DEPLOY.md](DEPLOY.md) is the rollout and rollback
|
||||
checklist for the Azzamo relays.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -19,6 +37,7 @@ 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"]
|
||||
@@ -42,6 +61,21 @@ queue_size = 2000
|
||||
|
||||
You can install noteguard by copying the binary to the strfry directory.
|
||||
|
||||
Optional features are enabled at build time:
|
||||
|
||||
| Feature | What it adds | Needed by the Azzamo configs |
|
||||
|---|---|---|
|
||||
| `remote` | Fetching [sources](#sources) over http(s) | yes |
|
||||
| `cloudflare` | Pushing IP bans to a Cloudflare WAF list ([details](#cloudflare-edge-banning)) | optional |
|
||||
| `forwarder` | The [forwarder](#forwarder) filter | no |
|
||||
| `nscript` | WASM filters ([details](#nscript-experimental)) | no |
|
||||
|
||||
`remote` and `cloudflare` need Rust 1.88 or newer:
|
||||
|
||||
```sh
|
||||
$ cargo build --release --features remote,cloudflare
|
||||
```
|
||||
|
||||
Static musl builds are convenient ways to package noteguard for deployment. It enables you to copy the binary directly to your server, ensure that you are using the correct architecture that your server is running.
|
||||
|
||||
You most likely want `x86_64-unknown-linux-musl` or `aarch64-unknown-linux-musl`. Install this target with rustup, build noteguard, and copy the binary to the server:
|
||||
@@ -74,11 +108,100 @@ writePolicy {
|
||||
|
||||
And you're done! Enjoy.
|
||||
|
||||
### Azzamo deployments
|
||||
|
||||
Ready-to-edit configs for the Azzamo relays, both served by the same binary:
|
||||
|
||||
- [noteguard-free.example.toml](noteguard-free.example.toml): everyone can write, rate limited per IP, premium members exempt, Azzamo blacklists applied.
|
||||
- [noteguard-premium.example.toml](noteguard-premium.example.toml): only active premium members can write, Azzamo blacklists applied.
|
||||
|
||||
They fetch their lists over https, so build them with the `remote` feature (see
|
||||
above). Before deploying, replace every `CHANGEME` URL with the real Azzamo API
|
||||
endpoint and set `AZZAMO_API_TOKEN` in strfry's environment.
|
||||
[DEPLOY.md](DEPLOY.md) is the step-by-step checklist for rolling them out and
|
||||
rolling back.
|
||||
|
||||
## Filters
|
||||
|
||||
You can use any of the builtin filters, or create your own!
|
||||
|
||||
This is the initial release, and only includes one filter so far:
|
||||
| Filter | Does |
|
||||
|---|---|
|
||||
| [`protected_events`](#protected-events) | Rejects NIP-70 protected events |
|
||||
| [`kinds`](#kinds) | Rejects listed event kinds |
|
||||
| [`blacklist`](#blacklist) | Rejects listed pubkeys, IPs and CIDR ranges (static and remote) |
|
||||
| [`whitelist`](#whitelist) | Accepts only listed pubkeys and IPs; with `pubkey_sources`, the premium gate |
|
||||
| [`content`](#content) | Silently drops notes containing blocked words (static and remote) |
|
||||
| [`ratelimit`](#ratelimit) | Limits notes per minute per IP, with optional IP bans |
|
||||
| [`forwarder`](#forwarder) | Forwards notes to another relay |
|
||||
| [`nscript`](#nscript-experimental) | Runs a WASM filter |
|
||||
|
||||
### Rejection messages
|
||||
|
||||
Every filter that visibly rejects a note takes an optional `message` key that
|
||||
replaces its built-in text. Leave it out and the default below is sent, so
|
||||
existing configs behave exactly as before.
|
||||
|
||||
| Filter | Key | Default |
|
||||
|---|---|---|
|
||||
| `ratelimit` | `message` | `rate-limited: you are noting too much` |
|
||||
| `ratelimit` | `ban_message` | `banned: too many violations, try again later` |
|
||||
| `blacklist` | `message` | `blocked: pubkey/ip is blacklisted` |
|
||||
| `whitelist` | `message` | `blocked: pubkey/ip not on the whitelist` |
|
||||
| `kinds` | `messages.<kind>`, then `message` | `blocked: note kind is not allowed here` |
|
||||
| `protected_events` | `message` | `blocked: event marked as protected` |
|
||||
| `nscript` | `message` | none |
|
||||
|
||||
`content` has no message: it shadow-rejects, and strfry tells the client the
|
||||
note was accepted, so no text is ever sent.
|
||||
|
||||
### Sources
|
||||
|
||||
A source is a named list fetched from an API or a file, kept fresh in the
|
||||
background, and used by filters by name. Declare each one once at the top
|
||||
level of the config:
|
||||
|
||||
```toml
|
||||
[sources.premium]
|
||||
url = "https://api.example.com/premium" # https://, http://, file:///path or a plain path
|
||||
format = "pubkeys" # "pubkeys", "words" or "nip05"
|
||||
token_env = "AZZAMO_API_TOKEN" # optional: env var holding a bearer token
|
||||
reload_secs = 300 # optional: default 300, minimum 30
|
||||
timeout_secs = 10 # optional: per-request timeout, default 10
|
||||
max_bytes = 10485760 # optional: larger bodies are rejected, default 10 MiB
|
||||
cache_path = "/var/lib/noteguard/premium.json" # optional: last good copy for restarts
|
||||
```
|
||||
|
||||
Then refer to it from a filter: `blacklist.pubkeys_source`, `ratelimit.exempt_source`,
|
||||
`content.words_source`, `content.exempt_source` and `whitelist.pubkey_sources`.
|
||||
A name that is not declared, or a list of the wrong format, stops noteguard at
|
||||
startup with an error.
|
||||
|
||||
How loading works:
|
||||
|
||||
- Every source is loaded once at startup, before the first note. If that fails, the `cache_path` copy is used. If there is no cache either, the list counts as unavailable until a reload succeeds (only `whitelist` treats that specially, see `unavailable`).
|
||||
- A background thread reloads each source every `reload_secs`. A failed fetch, a non-2xx response, an oversized or unparseable body all keep the last good copy, and the failure is logged with the copy's age.
|
||||
- No network call ever happens while a note is being filtered.
|
||||
- strfry runs one noteguard process per ingester thread, and each fetches its own copy.
|
||||
|
||||
Accepted bodies (unknown fields are ignored; unusable entries are skipped and
|
||||
counted in the log):
|
||||
|
||||
- `format = "pubkeys"`: a JSON array, or `{"pubkeys": [...]}`, whose items are either a hex pubkey string or `{"pubkey": "<hex>", "expires_at": <unix seconds or null>}`. Keys are lowercased; npub and malformed keys are skipped. An entry stops counting once `expires_at` passes, even if the API is down and the list is stale. A key listed twice keeps the latest expiry.
|
||||
- `format = "words"`: a JSON array of strings, or `{"words": [...]}`.
|
||||
- `format = "nip05"`: a NIP-05 `nostr.json` document; every pubkey in its `names` map is listed, with no expiry. The server must return the full map (some only answer `?name=` lookups; that body has no `names` map for everyone and is rejected). Use it with `whitelist.pubkey_sources` to let only a domain's NIP-05 users write:
|
||||
|
||||
```toml
|
||||
[sources.members]
|
||||
url = "https://example.com/.well-known/nostr.json"
|
||||
format = "nip05"
|
||||
|
||||
[filters.whitelist]
|
||||
pubkey_sources = ["members"]
|
||||
```
|
||||
|
||||
HTTP sources need a build with `--features remote`; a config with an http(s)
|
||||
source in a build without it stops at startup with an error.
|
||||
|
||||
### Ratelimit
|
||||
|
||||
@@ -88,10 +211,44 @@ The ratelimit filter limits the rate at which notes are written to the relay per
|
||||
|
||||
Settings:
|
||||
|
||||
- `notes_per_minute`: the number of notes per minute which are allowed to be written per ip.
|
||||
- `posts_per_minute`: the number of notes per minute which are allowed to be written per ip.
|
||||
|
||||
- `whitelist` *optional*: a list of IP4 or IP6 addresses that are allowed to bypass the ratelimit.
|
||||
|
||||
- `exempt_source` *optional*: the name of a `[sources.<name>]` pubkey list (see [Sources](#sources)), typically premium members. Active members skip the rate limit and the IP-ban check, and their posts neither spend the IP's budget nor reset its strike streak.
|
||||
|
||||
- `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 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`
|
||||
@@ -102,7 +259,46 @@ The whitelist filter only allows notes to pass if it matches a particular pubkey
|
||||
|
||||
- `ips` *optional*: a list of ip addresses to let through
|
||||
|
||||
Either criteria can match
|
||||
- `message` *optional*: the error message for notes that match nothing. Default is: `blocked: pubkey/ip not on the whitelist`
|
||||
|
||||
- `pubkey_sources` *optional*: names of `[sources.<name>]` pubkey lists (see [Sources](#sources)) whose active, unexpired members are let through. With `["premium"]` this is the premium gate.
|
||||
|
||||
- `unavailable` *optional*: what to do with a note that matches nothing while one of `pubkey_sources` has never loaded (no successful fetch and no cache). `"reject"` (default) fails closed; `"accept"` fails open and logs a warning.
|
||||
|
||||
- `unavailable_message` *optional*: the message for that case under `"reject"`. Default is: `blocked: membership list unavailable, try again shortly`
|
||||
|
||||
Any criterion can match
|
||||
|
||||
### Blacklist
|
||||
|
||||
* 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
|
||||
|
||||
- `pubkeys_source` *optional*: the name of a `[sources.<name>]` pubkey list (see [Sources](#sources)) checked alongside `pubkeys`. Entries with an `expires_at` stop blocking once it passes. If the list has never loaded, only `pubkeys` applies.
|
||||
|
||||
- `message` *optional*: the error message for a blocked note. Default is: `blocked: pubkey/ip is blacklisted`
|
||||
|
||||
### Content
|
||||
|
||||
* name: `content`
|
||||
|
||||
Silently drops (shadow-rejects) notes whose content contains a blocked word or
|
||||
phrase. Matching is case- and homoglyph-insensitive.
|
||||
|
||||
- `filters`: a list of words or phrases to block
|
||||
|
||||
- `words_source` *optional*: the name of a `[sources.<name>]` word list (see [Sources](#sources)) matched in addition to `filters`
|
||||
|
||||
- `ban_after`, `ban_duration_secs` *optional*: IP-ban an IP after this many matching notes (cumulative); a banned IP has every note silently dropped
|
||||
|
||||
- `exempt_source` *optional*: the name of a `[sources.<name>]` pubkey list, typically premium members. Active members skip the IP-ban check, so they can post from an IP banned because of someone else. Their notes are still checked against the words, but a match does not count against their IP.
|
||||
|
||||
### Kinds
|
||||
|
||||
@@ -114,6 +310,8 @@ A filter that blacklists certain kinds
|
||||
|
||||
- `kinds.messages` *optional*: a map of kinds to message to deliver when the kind is blocked
|
||||
|
||||
- `message` *optional*: the message for a blocked kind with no entry in `kinds.messages`. Default is: `blocked: note kind is not allowed here`
|
||||
|
||||
Example:
|
||||
|
||||
```toml
|
||||
@@ -131,10 +329,12 @@ See [nip70]
|
||||
|
||||
* name: `protected_events`
|
||||
|
||||
There are no config options, but an empty config entry is still needed:
|
||||
An empty config entry is still needed:
|
||||
|
||||
`[filters.protected_events]`
|
||||
|
||||
- `message` *optional*: the error message for a protected event. Default is: `blocked: event marked as protected`
|
||||
|
||||
### Forwarder
|
||||
|
||||
* name: `forwarder`
|
||||
@@ -152,16 +352,250 @@ be queued if the connection goes down (up to the `queue_size` buffer limit)
|
||||
|
||||
- `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
|
||||
|
||||
You can test your filters like so:
|
||||
Run the test suite for the default build and for the feature builds:
|
||||
|
||||
```sh
|
||||
$ cargo test
|
||||
$ cargo test --features remote,cloudflare
|
||||
```
|
||||
|
||||
`tests/golden.rs` pipes [test/golden.inputs](test/golden.inputs) through the
|
||||
binary with a frozen config ([test/golden.toml](test/golden.toml)) and compares
|
||||
the output line by line with [test/golden.expected](test/golden.expected). It
|
||||
pins the behavior of an unmodified config, so any change that alters existing
|
||||
verdicts or messages fails it. Regenerate the expected file only for an
|
||||
intentional behavior change.
|
||||
|
||||
You can also feed notes to a build by hand:
|
||||
|
||||
```sh
|
||||
$ cargo build
|
||||
$ <test/inputs ./target/debug/noteguard
|
||||
$ ./test/delay | ./target/debug/noteguard
|
||||
$ ./test/delayed | ./target/debug/noteguard
|
||||
```
|
||||
|
||||
To try a config with http(s) sources, build with `remote`, point
|
||||
`NOTEGUARD_CONFIG` at it and turn on logging to see each list load (with the
|
||||
placeholder `CHANGEME` URLs every fetch fails, and the log says so):
|
||||
|
||||
```sh
|
||||
$ cargo build --features remote
|
||||
$ NOTEGUARD_CONFIG=noteguard-free.example.toml RUST_LOG=info ./target/debug/noteguard <test/inputs
|
||||
```
|
||||
|
||||
[strfry]: https://github.com/hoytech/strfry
|
||||
[damus-io/noteguard]: https://github.com/damus-io/noteguard
|
||||
[nip70]: https://github.com/nostr-protocol/nips/blob/protected-events-tag/70.md
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
# Azzamo FREE relay (nostr.azzamo.net)
|
||||
#
|
||||
# Everyone can write. Notes are rate limited per IP, premium members are
|
||||
# exempt from the rate limit and from IP bans, and everyone is checked
|
||||
# against the Azzamo pubkey and word blacklists.
|
||||
#
|
||||
# Build: cargo build --release --features remote,cloudflare
|
||||
# Run: NOTEGUARD_CONFIG=/etc/noteguard/free.toml (see DEPLOY.md)
|
||||
#
|
||||
# The source URLs below are placeholders until the Azzamo API endpoints and
|
||||
# response shapes are confirmed. Accepted shapes are documented in the README
|
||||
# (section "Sources").
|
||||
|
||||
pipeline = ["protected_events", "kinds", "blacklist", "content", "ratelimit"]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Remote lists. Each is fetched at startup, then every reload_secs in the
|
||||
# background; a failed fetch keeps the last good copy, and cache_path lets a
|
||||
# restart during an API outage come back with the last good list.
|
||||
# The token is read from the AZZAMO_API_TOKEN environment variable.
|
||||
# ---------------------------------------------------------------------------
|
||||
[sources.premium]
|
||||
url = "https://api.azzamo.net/CHANGEME/premium"
|
||||
format = "pubkeys"
|
||||
token_env = "AZZAMO_API_TOKEN"
|
||||
reload_secs = 300
|
||||
timeout_secs = 10
|
||||
cache_path = "/var/lib/noteguard/premium.json"
|
||||
|
||||
[sources.blacklist_pubkeys]
|
||||
url = "https://api.azzamo.net/CHANGEME/blacklist/pubkeys"
|
||||
format = "pubkeys"
|
||||
token_env = "AZZAMO_API_TOKEN"
|
||||
reload_secs = 300
|
||||
timeout_secs = 10
|
||||
cache_path = "/var/lib/noteguard/blacklist_pubkeys.json"
|
||||
|
||||
[sources.blacklist_words]
|
||||
url = "https://api.azzamo.net/CHANGEME/blacklist/words"
|
||||
format = "words"
|
||||
token_env = "AZZAMO_API_TOKEN"
|
||||
reload_secs = 300
|
||||
timeout_secs = 10
|
||||
cache_path = "/var/lib/noteguard/blacklist_words.json"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Filters, in pipeline order.
|
||||
# ---------------------------------------------------------------------------
|
||||
[filters.protected_events]
|
||||
# message = "blocked: event marked as protected"
|
||||
|
||||
[filters.kinds]
|
||||
kinds = [30065, 1064, 34550, 4550]
|
||||
# message = "blocked: note kind is not allowed here"
|
||||
|
||||
[filters.kinds.messages]
|
||||
30065 = "blocked: files on nostr is dumb"
|
||||
1064 = "blocked: files on nostr is dumb"
|
||||
34550 = "blocked: please use a dedicated relay for moderated communities"
|
||||
4550 = "blocked: please use a dedicated relay for moderated communities"
|
||||
|
||||
# Blacklisted pubkeys (static + Azzamo list) and IPs get a visible reject.
|
||||
[filters.blacklist]
|
||||
pubkeys_source = "blacklist_pubkeys"
|
||||
# pubkeys = []
|
||||
# ips = []
|
||||
# cidrs = []
|
||||
# message = "blocked: pubkey/ip is blacklisted"
|
||||
|
||||
# Blocked words (static + Azzamo list) are silently dropped. Repeat offenders
|
||||
# are IP-banned; premium members skip the ban but are still word-checked.
|
||||
[filters.content]
|
||||
filters = ["Damus Airdrop"]
|
||||
words_source = "blacklist_words"
|
||||
exempt_source = "premium"
|
||||
ban_after = 5
|
||||
ban_duration_secs = 3600
|
||||
|
||||
# Per-IP rate limit. Premium members are exempt.
|
||||
[filters.ratelimit]
|
||||
posts_per_minute = 8
|
||||
whitelist = ["127.0.0.1"]
|
||||
exempt_source = "premium"
|
||||
message = "rate-limited: you note too much"
|
||||
ban_after = 10
|
||||
ban_duration_secs = 3600
|
||||
ban_message = "banned: too many rate-limit violations, try again later"
|
||||
|
||||
# Optional: push IP bans to a Cloudflare WAF list (needs the cloudflare
|
||||
# feature and CLOUDFLARE_API_TOKEN). See the README.
|
||||
# [cloudflare]
|
||||
# account_id = "<cloudflare account id>"
|
||||
# list_id = "<ip list id>"
|
||||
@@ -0,0 +1,85 @@
|
||||
# Azzamo PREMIUM relays (relay, us, asia)
|
||||
#
|
||||
# Only active premium members can write. The member list comes from the
|
||||
# Azzamo API with an expiry per member, and members are still checked against
|
||||
# the Azzamo pubkey and word blacklists.
|
||||
#
|
||||
# Build: cargo build --release --features remote,cloudflare
|
||||
# Run: NOTEGUARD_CONFIG=/etc/noteguard/premium.toml (see DEPLOY.md)
|
||||
#
|
||||
# The source URLs below are placeholders until the Azzamo API endpoints and
|
||||
# response shapes are confirmed. Accepted shapes are documented in the README
|
||||
# (section "Sources").
|
||||
|
||||
# blacklist runs before the gate so a blacklisted member gets the blacklist
|
||||
# message; the gate runs before content so strangers never reach the word
|
||||
# check or count towards IP bans.
|
||||
pipeline = ["protected_events", "kinds", "blacklist", "whitelist", "content", "ratelimit"]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Remote lists. See noteguard-free.example.toml for how loading works. The
|
||||
# cache matters most here: with no list and no cache the gate rejects
|
||||
# everyone (see `unavailable` below).
|
||||
# ---------------------------------------------------------------------------
|
||||
[sources.premium]
|
||||
url = "https://api.azzamo.net/CHANGEME/premium"
|
||||
format = "pubkeys"
|
||||
token_env = "AZZAMO_API_TOKEN"
|
||||
reload_secs = 300
|
||||
timeout_secs = 10
|
||||
cache_path = "/var/lib/noteguard/premium.json"
|
||||
|
||||
[sources.blacklist_pubkeys]
|
||||
url = "https://api.azzamo.net/CHANGEME/blacklist/pubkeys"
|
||||
format = "pubkeys"
|
||||
token_env = "AZZAMO_API_TOKEN"
|
||||
reload_secs = 300
|
||||
timeout_secs = 10
|
||||
cache_path = "/var/lib/noteguard/blacklist_pubkeys.json"
|
||||
|
||||
[sources.blacklist_words]
|
||||
url = "https://api.azzamo.net/CHANGEME/blacklist/words"
|
||||
format = "words"
|
||||
token_env = "AZZAMO_API_TOKEN"
|
||||
reload_secs = 300
|
||||
timeout_secs = 10
|
||||
cache_path = "/var/lib/noteguard/blacklist_words.json"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Filters, in pipeline order.
|
||||
# ---------------------------------------------------------------------------
|
||||
[filters.protected_events]
|
||||
|
||||
[filters.kinds]
|
||||
kinds = [30065, 1064, 34550, 4550]
|
||||
|
||||
[filters.kinds.messages]
|
||||
30065 = "blocked: files on nostr is dumb"
|
||||
1064 = "blocked: files on nostr is dumb"
|
||||
34550 = "blocked: please use a dedicated relay for moderated communities"
|
||||
4550 = "blocked: please use a dedicated relay for moderated communities"
|
||||
|
||||
[filters.blacklist]
|
||||
pubkeys_source = "blacklist_pubkeys"
|
||||
|
||||
# The premium gate. Static pubkeys and IPs are allowed too (e.g. localhost for
|
||||
# admin imports). Zap receipts (kind 9735) and NIP-17 gift wraps (kind 1059)
|
||||
# are signed by non-member keys, so they are rejected here like any stranger.
|
||||
[filters.whitelist]
|
||||
pubkey_sources = ["premium"]
|
||||
ips = ["127.0.0.1"]
|
||||
message = "restricted: this relay is for Azzamo premium members"
|
||||
# "reject" (default) fails closed when the premium list has never loaded and
|
||||
# there is no cache; "accept" lets everyone write until it loads.
|
||||
unavailable = "reject"
|
||||
unavailable_message = "restricted: membership list unavailable, try again shortly"
|
||||
|
||||
[filters.content]
|
||||
filters = ["Damus Airdrop"]
|
||||
words_source = "blacklist_words"
|
||||
|
||||
# A guard against runaway clients rather than a quota: everyone here is a
|
||||
# member, so there is no premium exemption and no IP ban.
|
||||
[filters.ratelimit]
|
||||
posts_per_minute = 60
|
||||
whitelist = ["127.0.0.1"]
|
||||
+104
-2
@@ -1,12 +1,56 @@
|
||||
|
||||
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"]
|
||||
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"]
|
||||
@@ -22,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,192 @@
|
||||
use crate::sources::PubkeyRef;
|
||||
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>>,
|
||||
/// Message returned on reject. Defaults to `blocked: pubkey/ip is blacklisted`.
|
||||
pub message: Option<String>,
|
||||
/// A `[sources.<name>]` pubkey list checked alongside `pubkeys`. Entries
|
||||
/// with an `expires_at` stop blocking once it passes.
|
||||
pub pubkeys_source: Option<PubkeyRef>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Blacklist {
|
||||
pubkeys: Option<Vec<String>>,
|
||||
ips: Option<Vec<String>>,
|
||||
cidrs: Option<Vec<IpNetwork>>,
|
||||
message: Option<String>,
|
||||
pubkeys_source: Option<PubkeyRef>,
|
||||
}
|
||||
|
||||
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()
|
||||
}),
|
||||
message: config.message,
|
||||
pubkeys_source: config.pubkeys_source,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Blacklist {
|
||||
/// Static `pubkeys` first, then the remote list. A remote list that has
|
||||
/// never loaded blocks nothing, so the static list still applies.
|
||||
fn is_pubkey_blocked(&self, pubkey: &str) -> bool {
|
||||
self.pubkeys
|
||||
.as_ref()
|
||||
.is_some_and(|pubkeys| pubkeys.iter().any(|p| p == pubkey))
|
||||
|| self
|
||||
.pubkeys_source
|
||||
.as_ref()
|
||||
.is_some_and(|source| source.is_active(pubkey))
|
||||
}
|
||||
|
||||
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 = self
|
||||
.message
|
||||
.as_deref()
|
||||
.unwrap_or("blocked: pubkey/ip is blacklisted")
|
||||
.to_owned();
|
||||
|
||||
if self.is_pubkey_blocked(&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"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sources::testing;
|
||||
use crate::Note;
|
||||
|
||||
fn msg(pubkey: &str, ip: &str) -> InputMessage {
|
||||
InputMessage {
|
||||
message_type: "new".to_string(),
|
||||
event: Note {
|
||||
id: "e".to_string(),
|
||||
pubkey: pubkey.to_string(),
|
||||
created_at: 0,
|
||||
kind: 1,
|
||||
tags: vec![],
|
||||
content: "hi".to_string(),
|
||||
sig: "sig".to_string(),
|
||||
},
|
||||
received_at: 0,
|
||||
source_type: "IP4".to_string(),
|
||||
source_info: ip.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn blacklist(toml_cfg: &str) -> Blacklist {
|
||||
toml::from_str(toml_cfg).expect("valid blacklist config")
|
||||
}
|
||||
|
||||
fn action(b: &mut Blacklist, pubkey: &str, ip: &str) -> Action {
|
||||
b.filter_note(&msg(pubkey, ip)).action
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_pubkey_rejected() {
|
||||
testing::pubkeys("bl_remote", Some(&[("spammer", None)]));
|
||||
let mut b = blacklist("pubkeys_source = \"bl_remote\"\nmessage = \"nope\"");
|
||||
let out = b.filter_note(&msg("spammer", "1.1.1.1"));
|
||||
assert_eq!(out.action, Action::Reject);
|
||||
assert_eq!(out.msg.as_deref(), Some("nope"));
|
||||
assert_eq!(action(&mut b, "friend", "1.1.1.1"), Action::Accept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_still_rejected_with_source() {
|
||||
testing::pubkeys("bl_static", Some(&[("spammer", None)]));
|
||||
let mut b = blacklist("pubkeys = [\"local\"]\npubkeys_source = \"bl_static\"");
|
||||
assert_eq!(action(&mut b, "local", "1.1.1.1"), Action::Reject);
|
||||
assert_eq!(action(&mut b, "spammer", "1.1.1.1"), Action::Reject);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_remote_entry_accepted() {
|
||||
testing::pubkeys(
|
||||
"bl_expired",
|
||||
Some(&[("was_bad", Some(1)), ("still_bad", Some(u64::MAX))]),
|
||||
);
|
||||
let mut b = blacklist("pubkeys_source = \"bl_expired\"");
|
||||
assert_eq!(action(&mut b, "was_bad", "1.1.1.1"), Action::Accept);
|
||||
assert_eq!(action(&mut b, "still_bad", "1.1.1.1"), Action::Reject);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_loaded_source_falls_back_to_static() {
|
||||
testing::pubkeys("bl_unloaded", None);
|
||||
let mut b = blacklist("pubkeys = [\"local\"]\npubkeys_source = \"bl_unloaded\"");
|
||||
assert_eq!(action(&mut b, "local", "1.1.1.1"), Action::Reject);
|
||||
assert_eq!(action(&mut b, "anyone", "1.1.1.1"), Action::Accept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_source_name_fails_load() {
|
||||
let err = toml::from_str::<Blacklist>("pubkeys_source = \"bl_typo_nowhere\"")
|
||||
.err()
|
||||
.expect("unknown source must not load");
|
||||
assert!(err.to_string().contains("unknown source"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ip_and_cidr_unchanged() {
|
||||
testing::pubkeys("bl_ips", Some(&[]));
|
||||
let mut b =
|
||||
blacklist("ips = [\"9.9.9.9\"]\ncidrs = [\"10.0.0.0/8\"]\npubkeys_source = \"bl_ips\"");
|
||||
assert_eq!(action(&mut b, "anyone", "9.9.9.9"), Action::Reject);
|
||||
assert_eq!(action(&mut b, "anyone", "10.1.2.3"), Action::Reject);
|
||||
assert_eq!(action(&mut b, "anyone", "11.0.0.1"), Action::Accept);
|
||||
}
|
||||
}
|
||||
+259
-3
@@ -1,17 +1,106 @@
|
||||
use crate::filters::ban::BanTracker;
|
||||
use crate::sources::{PubkeyRef, WordList, WordsRef};
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
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>>,
|
||||
|
||||
/// A `[sources.<name>]` word list matched in addition to `filters`, with
|
||||
/// the same homoglyph-insensitive matching.
|
||||
words_source: Option<WordsRef>,
|
||||
|
||||
/// Normalized copy of the `words_source` snapshot it was built from,
|
||||
/// rebuilt on the note path whenever a reload swaps in a new snapshot.
|
||||
#[serde(skip)]
|
||||
remote_normalized: Option<(Arc<WordList>, Vec<String>)>,
|
||||
|
||||
/// A `[sources.<name>]` pubkey list (e.g. premium members) whose active
|
||||
/// members skip the IP-ban check. Their notes are still word-checked, but
|
||||
/// a match does not count against their IP.
|
||||
exempt_source: Option<PubkeyRef>,
|
||||
|
||||
/// 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 Content {
|
||||
/// Whether `content` contains any static or remote term, both sides folded
|
||||
/// through [`normalize`].
|
||||
fn matches(&mut self, content: &str) -> bool {
|
||||
let content = normalize(content);
|
||||
let normalized = self
|
||||
.normalized
|
||||
.get_or_insert_with(|| self.filters.iter().map(|f| normalize(f)).collect());
|
||||
if normalized.iter().any(|filter| content.contains(filter)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let Some(current) = self.words_source.as_ref().and_then(WordsRef::get) else {
|
||||
return false;
|
||||
};
|
||||
// Re-normalize only when a reload swapped the snapshot.
|
||||
let stale = self
|
||||
.remote_normalized
|
||||
.as_ref()
|
||||
.is_none_or(|(seen, _)| !Arc::ptr_eq(seen, ¤t));
|
||||
if stale {
|
||||
let words = current.0.iter().map(|w| normalize(w)).collect();
|
||||
self.remote_normalized = Some((current, words));
|
||||
}
|
||||
self.remote_normalized
|
||||
.as_ref()
|
||||
.is_some_and(|(_, words)| words.iter().any(|w| content.contains(w)))
|
||||
}
|
||||
}
|
||||
|
||||
impl NoteFilter for Content {
|
||||
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
|
||||
for filter in &self.filters {
|
||||
if msg.event.content.contains(filter) {
|
||||
return OutputMessage::new(msg.event.id.clone(), Action::ShadowReject, None);
|
||||
let now = Instant::now();
|
||||
let exempt = self
|
||||
.exempt_source
|
||||
.as_ref()
|
||||
.is_some_and(|source| source.is_active(&msg.event.pubkey));
|
||||
|
||||
// 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. Exempt (premium) authors are not subject to it.
|
||||
if !exempt && self.ban.is_banned(&msg.source_info, now) {
|
||||
return OutputMessage::new(msg.event.id.clone(), Action::ShadowReject, None);
|
||||
}
|
||||
|
||||
if self.matches(&msg.event.content) {
|
||||
// Count the violation (may trip a ban for next time); either way this
|
||||
// note is shadow-rejected. An exempt author's match never strikes the
|
||||
// IP, so they cannot get a shared IP banned for everyone else.
|
||||
if !exempt {
|
||||
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)
|
||||
@@ -21,3 +110,170 @@ impl NoteFilter for Content {
|
||||
"content"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sources::testing;
|
||||
use crate::Note;
|
||||
|
||||
fn msg(id: &str, ip: &str, content: &str) -> InputMessage {
|
||||
msg_from(id, ip, content, "pk")
|
||||
}
|
||||
|
||||
fn msg_from(id: &str, ip: &str, content: &str, pubkey: &str) -> InputMessage {
|
||||
InputMessage {
|
||||
message_type: "new".to_string(),
|
||||
event: Note {
|
||||
id: id.to_string(),
|
||||
pubkey: pubkey.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
|
||||
);
|
||||
}
|
||||
|
||||
fn shadow(c: &mut Content, ip: &str, content: &str, pubkey: &str) -> bool {
|
||||
c.filter_note(&msg_from("e", ip, content, pubkey)).action == Action::ShadowReject
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_word_shadow_rejects() {
|
||||
testing::words("ct_remote", Some(&["casino bonus"]));
|
||||
let mut c = content("filters = []\nwords_source = \"ct_remote\"\n");
|
||||
assert!(shadow(&mut c, "1.1.1.1", "Get your CASINO BONUS now", "pk"));
|
||||
assert!(!shadow(&mut c, "1.1.1.1", "gm", "pk"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_homoglyph_caught() {
|
||||
testing::words("ct_homoglyph", Some(&["Damus Airdrop"]));
|
||||
let mut c = content("filters = []\nwords_source = \"ct_homoglyph\"\n");
|
||||
assert!(shadow(&mut c, "1.1.1.1", "D\u{0430}mus \u{0410}irdrop is open", "pk"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_renormalizes() {
|
||||
testing::words("ct_reload", Some(&["alpha"]));
|
||||
let mut c = content("filters = []\nwords_source = \"ct_reload\"\n");
|
||||
assert!(shadow(&mut c, "1.1.1.1", "alpha", "pk"));
|
||||
assert!(!shadow(&mut c, "1.1.1.1", "beta", "pk"));
|
||||
|
||||
testing::words("ct_reload", Some(&["beta"]));
|
||||
assert!(!shadow(&mut c, "1.1.1.1", "alpha", "pk"));
|
||||
assert!(shadow(&mut c, "1.1.1.1", "beta", "pk"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_words_still_apply() {
|
||||
testing::words("ct_static", None);
|
||||
let mut c = content("filters = [\"spam\"]\nwords_source = \"ct_static\"\n");
|
||||
assert!(shadow(&mut c, "1.1.1.1", "spam", "pk"));
|
||||
assert!(!shadow(&mut c, "1.1.1.1", "ham", "pk"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premium_skips_ip_ban() {
|
||||
testing::pubkeys("ct_premium_ban", Some(&[("member", None)]));
|
||||
let mut c = content(
|
||||
"filters = [\"spam\"]\nban_after = 1\nexempt_source = \"ct_premium_ban\"\n",
|
||||
);
|
||||
assert!(shadow(&mut c, "5.5.5.5", "spam", "pk"));
|
||||
// The IP is now banned: a clean note from a non-member is dropped,
|
||||
// a clean note from a member is not.
|
||||
assert!(shadow(&mut c, "5.5.5.5", "hello", "pk"));
|
||||
assert!(!shadow(&mut c, "5.5.5.5", "hello", "member"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premium_still_word_checked() {
|
||||
testing::pubkeys("ct_premium_words", Some(&[("member", None)]));
|
||||
let mut c = content("filters = [\"spam\"]\nexempt_source = \"ct_premium_words\"\n");
|
||||
assert!(shadow(&mut c, "5.5.5.5", "spam", "member"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premium_match_does_not_strike() {
|
||||
testing::pubkeys("ct_premium_strike", Some(&[("member", None)]));
|
||||
let mut c = content(
|
||||
"filters = [\"spam\"]\nban_after = 1\nexempt_source = \"ct_premium_strike\"\n",
|
||||
);
|
||||
assert!(shadow(&mut c, "3.3.3.3", "spam", "member"));
|
||||
// No strike was counted, so the IP is not banned for others.
|
||||
assert!(!shadow(&mut c, "3.3.3.3", "hello", "pk"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "timing probe, run with --ignored --nocapture"]
|
||||
fn normalize_10k_words_timing() {
|
||||
let words: Vec<String> = (0..10_000).map(|i| format!("spam phrase number {i}")).collect();
|
||||
let refs: Vec<&str> = words.iter().map(String::as_str).collect();
|
||||
testing::words("ct_timing", Some(&refs));
|
||||
let mut c = content("filters = []\nwords_source = \"ct_timing\"\n");
|
||||
let start = std::time::Instant::now();
|
||||
c.filter_note(&msg("e", "1.1.1.1", "hello"));
|
||||
let first = start.elapsed();
|
||||
let start = std::time::Instant::now();
|
||||
c.filter_note(&msg("e", "1.1.1.1", "hello"));
|
||||
println!("first note (normalize 10k): {first:?}, next note: {:?}", start.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -6,6 +6,8 @@ use std::collections::HashMap;
|
||||
pub struct Kinds {
|
||||
kinds: Vec<i64>,
|
||||
messages: Option<HashMap<String, String>>,
|
||||
/// Fallback for blocked kinds with no entry in `messages`.
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
impl NoteFilter for Kinds {
|
||||
@@ -16,6 +18,7 @@ impl NoteFilter for Kinds {
|
||||
.messages
|
||||
.as_ref()
|
||||
.and_then(|msgs| msgs.get(&kind.to_string()).cloned())
|
||||
.or_else(|| self.message.clone())
|
||||
.unwrap_or_else(|| "blocked: note kind is not allowed here".to_string());
|
||||
OutputMessage::new(input.event.id.clone(), Action::Reject, Some(msg))
|
||||
} else {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
mod ban;
|
||||
mod blacklist;
|
||||
mod content;
|
||||
mod kinds;
|
||||
mod protected_events;
|
||||
@@ -7,6 +9,10 @@ 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;
|
||||
@@ -15,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,10 @@ use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct ProtectedEvents {}
|
||||
pub struct ProtectedEvents {
|
||||
/// Message returned on reject. Defaults to `blocked: event marked as protected`.
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
impl NoteFilter for ProtectedEvents {
|
||||
fn filter_note(&mut self, input: &InputMessage) -> OutputMessage {
|
||||
@@ -12,7 +15,12 @@ impl NoteFilter for ProtectedEvents {
|
||||
return OutputMessage::new(
|
||||
input.event.id.clone(),
|
||||
Action::Reject,
|
||||
Some("blocked: event marked as protected".to_string()),
|
||||
Some(
|
||||
self.message
|
||||
.as_deref()
|
||||
.unwrap_or("blocked: event marked as protected")
|
||||
.to_owned(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+227
-3
@@ -1,3 +1,5 @@
|
||||
use crate::filters::ban::BanTracker;
|
||||
use crate::sources::PubkeyRef;
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
@@ -12,6 +14,17 @@ pub struct Tokens {
|
||||
pub struct RateLimit {
|
||||
pub posts_per_minute: i32,
|
||||
pub whitelist: Option<Vec<String>>,
|
||||
pub message: Option<String>,
|
||||
|
||||
/// A `[sources.<name>]` pubkey list (e.g. premium members) whose active
|
||||
/// members skip rate limiting and the IP-ban check entirely.
|
||||
pub exempt_source: Option<PubkeyRef>,
|
||||
|
||||
/// 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 +42,32 @@ impl NoteFilter for RateLimit {
|
||||
}
|
||||
}
|
||||
|
||||
// Exempt pubkeys (premium) are checked before the IP-ban, so a member on
|
||||
// a shared IP with a banned spammer can still post. They neither spend
|
||||
// nor refill the IP's tokens, nor touch its strike streak.
|
||||
if let Some(exempt) = &self.exempt_source {
|
||||
if exempt.is_active(&msg.event.pubkey) {
|
||||
return OutputMessage::new(msg.event.id.clone(), Action::Accept, None);
|
||||
}
|
||||
}
|
||||
|
||||
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 +75,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 +95,205 @@ 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::sources::testing;
|
||||
use crate::Note;
|
||||
|
||||
fn msg(id: &str, ip: &str) -> InputMessage {
|
||||
msg_from(id, ip, "pk")
|
||||
}
|
||||
|
||||
fn msg_from(id: &str, ip: &str, pubkey: &str) -> InputMessage {
|
||||
InputMessage {
|
||||
message_type: "new".to_string(),
|
||||
event: Note {
|
||||
id: id.to_string(),
|
||||
pubkey: pubkey.to_string(),
|
||||
created_at: 0,
|
||||
kind: 1,
|
||||
tags: vec![],
|
||||
content: "hi".to_string(),
|
||||
sig: "sig".to_string(),
|
||||
},
|
||||
received_at: 0,
|
||||
source_type: "IP4".to_string(),
|
||||
source_info: ip.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn 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"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premium_never_rate_limited() {
|
||||
testing::pubkeys("rl_premium", Some(&[("member", None)]));
|
||||
let mut rl = ratelimit("posts_per_minute = 1\nexempt_source = \"rl_premium\"\n");
|
||||
for i in 0..10 {
|
||||
let r = rl.filter_note(&msg_from(&format!("e{i}"), "1.2.3.4", "member"));
|
||||
assert_eq!(r.action, Action::Accept);
|
||||
}
|
||||
// Premium posts spent none of the IP's budget: a non-member from the
|
||||
// same IP still gets its first post through.
|
||||
assert_eq!(rl.filter_note(&msg("x", "1.2.3.4")).action, Action::Accept);
|
||||
assert_eq!(rl.filter_note(&msg("y", "1.2.3.4")).action, Action::Reject);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premium_accepted_from_banned_ip() {
|
||||
testing::pubkeys("rl_banned_ip", Some(&[("member", None)]));
|
||||
let mut rl = ratelimit(
|
||||
"posts_per_minute = 1\nban_after = 1\nexempt_source = \"rl_banned_ip\"\n",
|
||||
);
|
||||
rl.filter_note(&msg("e1", "6.6.6.6"));
|
||||
let banned = rl.filter_note(&msg("e2", "6.6.6.6"));
|
||||
assert!(banned.msg.unwrap().contains("banned"));
|
||||
|
||||
let r = rl.filter_note(&msg_from("e3", "6.6.6.6", "member"));
|
||||
assert_eq!(r.action, Action::Accept);
|
||||
// The ban still holds for everyone else on that IP.
|
||||
assert!(rl.filter_note(&msg("e4", "6.6.6.6")).msg.unwrap().contains("banned"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premium_does_not_reset_ip_streak() {
|
||||
testing::pubkeys("rl_streak", Some(&[("member", None)]));
|
||||
let mut rl = ratelimit(
|
||||
"posts_per_minute = 1\nban_after = 2\nexempt_source = \"rl_streak\"\n",
|
||||
);
|
||||
rl.filter_note(&msg("e1", "7.7.7.7"));
|
||||
// Strike 1, then a premium post, then strike 2 must still ban.
|
||||
assert_eq!(rl.filter_note(&msg("e2", "7.7.7.7")).action, Action::Reject);
|
||||
assert_eq!(
|
||||
rl.filter_note(&msg_from("e3", "7.7.7.7", "member")).action,
|
||||
Action::Accept
|
||||
);
|
||||
assert!(rl.filter_note(&msg("e4", "7.7.7.7")).msg.unwrap().contains("banned"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_premium_is_rate_limited() {
|
||||
testing::pubkeys("rl_expired", Some(&[("lapsed", Some(1))]));
|
||||
let mut rl = ratelimit("posts_per_minute = 1\nexempt_source = \"rl_expired\"\n");
|
||||
assert_eq!(
|
||||
rl.filter_note(&msg_from("e1", "8.8.4.4", "lapsed")).action,
|
||||
Action::Accept
|
||||
);
|
||||
assert_eq!(
|
||||
rl.filter_note(&msg_from("e2", "8.8.4.4", "lapsed")).action,
|
||||
Action::Reject
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_loaded_source_exempts_nobody() {
|
||||
testing::pubkeys("rl_unloaded", None);
|
||||
let mut rl = ratelimit("posts_per_minute = 1\nexempt_source = \"rl_unloaded\"\n");
|
||||
assert_eq!(
|
||||
rl.filter_note(&msg_from("e1", "4.4.4.4", "member")).action,
|
||||
Action::Accept
|
||||
);
|
||||
assert_eq!(
|
||||
rl.filter_note(&msg_from("e2", "4.4.4.4", "member")).action,
|
||||
Action::Reject
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+254
-6
@@ -1,30 +1,103 @@
|
||||
use crate::sources::PubkeyRef;
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use log::warn;
|
||||
use serde::Deserialize;
|
||||
|
||||
/// What the whitelist does with a note it cannot place because one of its
|
||||
/// `pubkey_sources` has never loaded (no fetch and no cache succeeded).
|
||||
#[derive(Deserialize, Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Unavailable {
|
||||
/// Fail closed: reject with `unavailable_message`.
|
||||
#[default]
|
||||
Reject,
|
||||
/// Fail open: accept, and log a warning.
|
||||
Accept,
|
||||
}
|
||||
|
||||
/// Lets a note through only if its pubkey or source IP is allowed. With
|
||||
/// `pubkey_sources` it is the premium gate: active members of any listed
|
||||
/// source are allowed too.
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct Whitelist {
|
||||
pub pubkeys: Option<Vec<String>>,
|
||||
pub ips: Option<Vec<String>>,
|
||||
/// Message returned on reject. Defaults to `blocked: pubkey/ip not on the whitelist`.
|
||||
pub message: Option<String>,
|
||||
|
||||
/// `[sources.<name>]` pubkey lists whose active (unexpired) members are
|
||||
/// allowed, e.g. `["premium"]`.
|
||||
#[serde(default)]
|
||||
pub pubkey_sources: Vec<PubkeyRef>,
|
||||
/// Policy when a note matches nothing and a source has never loaded.
|
||||
#[serde(default)]
|
||||
pub unavailable: Unavailable,
|
||||
/// Message for that case under `unavailable = "reject"`.
|
||||
pub unavailable_message: Option<String>,
|
||||
|
||||
/// Whether the fail-open warning has been logged, so an outage logs once
|
||||
/// rather than once per note.
|
||||
#[serde(skip)]
|
||||
warned_unavailable: bool,
|
||||
}
|
||||
|
||||
impl NoteFilter for Whitelist {
|
||||
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
|
||||
let accept = || OutputMessage::new(msg.event.id.clone(), Action::Accept, None);
|
||||
let reject = |text: &str| {
|
||||
OutputMessage::new(msg.event.id.clone(), Action::Reject, Some(text.to_owned()))
|
||||
};
|
||||
|
||||
if let Some(pubkeys) = &self.pubkeys {
|
||||
if pubkeys.contains(&msg.event.pubkey) {
|
||||
return OutputMessage::new(msg.event.id.clone(), Action::Accept, None);
|
||||
return accept();
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ips) = &self.ips {
|
||||
if ips.contains(&msg.source_info) {
|
||||
return OutputMessage::new(msg.event.id.clone(), Action::Accept, None);
|
||||
return accept();
|
||||
}
|
||||
}
|
||||
|
||||
OutputMessage::new(
|
||||
msg.event.id.clone(),
|
||||
Action::Reject,
|
||||
Some("blocked: pubkey/ip not on the whitelist".to_string()),
|
||||
if self
|
||||
.pubkey_sources
|
||||
.iter()
|
||||
.any(|source| source.is_active(&msg.event.pubkey))
|
||||
{
|
||||
return accept();
|
||||
}
|
||||
|
||||
// Nothing matched. If a list we depend on never loaded we cannot tell
|
||||
// a member from a stranger, so apply the configured policy instead of
|
||||
// the normal rejection.
|
||||
if let Some(missing) = self.pubkey_sources.iter().find(|s| !s.is_loaded()) {
|
||||
match self.unavailable {
|
||||
Unavailable::Reject => {
|
||||
return reject(
|
||||
self.unavailable_message
|
||||
.as_deref()
|
||||
.unwrap_or("blocked: membership list unavailable, try again shortly"),
|
||||
);
|
||||
}
|
||||
Unavailable::Accept => {
|
||||
if !self.warned_unavailable {
|
||||
warn!(
|
||||
"whitelist: source {} unavailable, accepting notes (unavailable = \"accept\")",
|
||||
missing.name()
|
||||
);
|
||||
self.warned_unavailable = true;
|
||||
}
|
||||
return accept();
|
||||
}
|
||||
}
|
||||
}
|
||||
self.warned_unavailable = false;
|
||||
|
||||
reject(
|
||||
self.message
|
||||
.as_deref()
|
||||
.unwrap_or("blocked: pubkey/ip not on the whitelist"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -32,3 +105,178 @@ impl NoteFilter for Whitelist {
|
||||
"whitelist"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sources::{declare, pubkey_source, testing, SourceConfig};
|
||||
use crate::Note;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn msg(pubkey: &str, ip: &str) -> InputMessage {
|
||||
InputMessage {
|
||||
message_type: "new".to_string(),
|
||||
event: Note {
|
||||
id: "e".to_string(),
|
||||
pubkey: pubkey.to_string(),
|
||||
created_at: 0,
|
||||
kind: 1,
|
||||
tags: vec![],
|
||||
content: "hi".to_string(),
|
||||
sig: "sig".to_string(),
|
||||
},
|
||||
received_at: 0,
|
||||
source_type: "IP4".to_string(),
|
||||
source_info: ip.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn whitelist(toml_cfg: &str) -> Whitelist {
|
||||
toml::from_str(toml_cfg).expect("valid whitelist config")
|
||||
}
|
||||
|
||||
fn run(w: &mut Whitelist, pubkey: &str, ip: &str) -> OutputMessage {
|
||||
w.filter_note(&msg(pubkey, ip))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premium_pubkey_accepted() {
|
||||
testing::pubkeys("wl_premium", Some(&[("member", None)]));
|
||||
let mut w = whitelist("pubkey_sources = [\"wl_premium\"]");
|
||||
assert_eq!(run(&mut w, "member", "1.1.1.1").action, Action::Accept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_premium_rejected_with_message() {
|
||||
testing::pubkeys("wl_nonmember", Some(&[("member", None)]));
|
||||
let mut w = whitelist("pubkey_sources = [\"wl_nonmember\"]");
|
||||
let out = run(&mut w, "stranger", "1.1.1.1");
|
||||
assert_eq!(out.action, Action::Reject);
|
||||
assert_eq!(
|
||||
out.msg.as_deref(),
|
||||
Some("blocked: pubkey/ip not on the whitelist")
|
||||
);
|
||||
|
||||
let mut w =
|
||||
whitelist("pubkey_sources = [\"wl_nonmember\"]\nmessage = \"premium members only\"");
|
||||
let out = run(&mut w, "stranger", "1.1.1.1");
|
||||
assert_eq!(out.msg.as_deref(), Some("premium members only"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_premium_rejected() {
|
||||
testing::pubkeys("wl_expired", Some(&[("lapsed", Some(1))]));
|
||||
let mut w = whitelist("pubkey_sources = [\"wl_expired\"]");
|
||||
assert_eq!(run(&mut w, "lapsed", "1.1.1.1").action, Action::Reject);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_listed_source_admits() {
|
||||
testing::pubkeys("wl_any_a", Some(&[("alice", None)]));
|
||||
testing::pubkeys("wl_any_b", Some(&[("bob", None)]));
|
||||
let mut w = whitelist("pubkey_sources = [\"wl_any_a\", \"wl_any_b\"]");
|
||||
assert_eq!(run(&mut w, "alice", "1.1.1.1").action, Action::Accept);
|
||||
assert_eq!(run(&mut w, "bob", "1.1.1.1").action, Action::Accept);
|
||||
assert_eq!(run(&mut w, "carol", "1.1.1.1").action, Action::Reject);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_pubkey_still_accepted() {
|
||||
testing::pubkeys("wl_static", Some(&[]));
|
||||
let mut w = whitelist("pubkeys = [\"admin\"]\npubkey_sources = [\"wl_static\"]");
|
||||
assert_eq!(run(&mut w, "admin", "1.1.1.1").action, Action::Accept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localhost_ip_still_accepted() {
|
||||
testing::pubkeys("wl_localhost", None);
|
||||
let mut w = whitelist("ips = [\"127.0.0.1\"]\npubkey_sources = [\"wl_localhost\"]");
|
||||
assert_eq!(run(&mut w, "anyone", "127.0.0.1").action, Action::Accept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_loaded_reject_policy() {
|
||||
testing::pubkeys("wl_unloaded_reject", None);
|
||||
let mut w = whitelist("pubkey_sources = [\"wl_unloaded_reject\"]");
|
||||
let out = run(&mut w, "member", "1.1.1.1");
|
||||
assert_eq!(out.action, Action::Reject);
|
||||
assert_eq!(
|
||||
out.msg.as_deref(),
|
||||
Some("blocked: membership list unavailable, try again shortly")
|
||||
);
|
||||
|
||||
let mut w = whitelist(
|
||||
"pubkey_sources = [\"wl_unloaded_reject\"]\nunavailable_message = \"try later\"",
|
||||
);
|
||||
assert_eq!(
|
||||
run(&mut w, "member", "1.1.1.1").msg.as_deref(),
|
||||
Some("try later")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_loaded_accept_policy() {
|
||||
testing::pubkeys("wl_unloaded_accept", None);
|
||||
let mut w =
|
||||
whitelist("pubkey_sources = [\"wl_unloaded_accept\"]\nunavailable = \"accept\"");
|
||||
assert_eq!(run(&mut w, "anyone", "1.1.1.1").action, Action::Accept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loaded_from_cache_counts_as_loaded() {
|
||||
let member = "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93";
|
||||
let cache = std::env::temp_dir()
|
||||
.join(format!("noteguard-wl-cache-{}", std::process::id()))
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
std::fs::write(&cache, format!(r#"["{member}"]"#)).unwrap();
|
||||
let config: SourceConfig = toml::from_str(&format!(
|
||||
"url = \"/nonexistent/wl-source\"\nformat = \"pubkeys\"\ncache_path = \"{cache}\""
|
||||
))
|
||||
.unwrap();
|
||||
declare(&HashMap::from([("wl_cached".to_string(), config)])).unwrap();
|
||||
pubkey_source("wl_cached").unwrap().initial_load();
|
||||
|
||||
let mut w = whitelist("pubkey_sources = [\"wl_cached\"]");
|
||||
assert_eq!(run(&mut w, member, "1.1.1.1").action, Action::Accept);
|
||||
// A stranger gets the normal message, not the unavailable one.
|
||||
assert_eq!(
|
||||
run(&mut w, "stranger", "1.1.1.1").msg.as_deref(),
|
||||
Some("blocked: pubkey/ip not on the whitelist")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitelist_accepts_nip05_member() {
|
||||
let member = "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93";
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("noteguard-wl-nip05-{}", std::process::id()))
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
std::fs::write(&path, format!(r#"{{"names": {{"alice": "{member}"}}}}"#)).unwrap();
|
||||
let config: SourceConfig =
|
||||
toml::from_str(&format!("url = \"{path}\"\nformat = \"nip05\"")).unwrap();
|
||||
declare(&HashMap::from([("wl_nip05".to_string(), config)])).unwrap();
|
||||
pubkey_source("wl_nip05").unwrap().initial_load();
|
||||
|
||||
let mut w = whitelist("pubkey_sources = [\"wl_nip05\"]");
|
||||
assert_eq!(run(&mut w, member, "1.1.1.1").action, Action::Accept);
|
||||
assert_eq!(run(&mut w, "stranger", "1.1.1.1").action, Action::Reject);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_sources_behaves_as_today() {
|
||||
let mut w = whitelist("pubkeys = [\"admin\"]\nips = [\"127.0.0.1\"]");
|
||||
assert_eq!(run(&mut w, "admin", "9.9.9.9").action, Action::Accept);
|
||||
assert_eq!(run(&mut w, "x", "127.0.0.1").action, Action::Accept);
|
||||
assert_eq!(
|
||||
run(&mut w, "x", "9.9.9.9").msg.as_deref(),
|
||||
Some("blocked: pubkey/ip not on the whitelist")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_unavailable_value_fails_load() {
|
||||
assert!(toml::from_str::<Whitelist>("unavailable = \"maybe\"").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
+19
@@ -1,6 +1,25 @@
|
||||
pub mod filters;
|
||||
mod messages;
|
||||
mod note_filter;
|
||||
mod read_filter;
|
||||
pub mod readfilters;
|
||||
pub mod readmsg;
|
||||
pub mod readpolicy;
|
||||
pub mod sources;
|
||||
|
||||
#[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())
|
||||
}
|
||||
|
||||
+627
-32
@@ -1,19 +1,33 @@
|
||||
use noteguard::filters::{Content, 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, Read};
|
||||
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>,
|
||||
|
||||
/// Named remote lists (`[sources.<name>]`) that filters refer to by name.
|
||||
#[serde(default)]
|
||||
sources: HashMap<String, noteguard::sources::SourceConfig>,
|
||||
}
|
||||
|
||||
type ConstructFilter = Box<fn(toml::Value) -> Result<Box<dyn NoteFilter>, toml::de::Error>>;
|
||||
@@ -47,12 +61,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
|
||||
@@ -106,12 +124,240 @@ 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 {
|
||||
@@ -119,24 +365,34 @@ fn serialize_output_message(msg: &OutputMessage) -> String {
|
||||
}
|
||||
|
||||
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")
|
||||
};
|
||||
|
||||
// Load the remote lists before building filters: filters resolve source
|
||||
// names while they deserialize, and a list-gated relay needs its list from
|
||||
// the very first note.
|
||||
let declared = noteguard::sources::declare(&config.sources)
|
||||
.unwrap_or_else(|e| panic!("invalid [sources] config: {e}"));
|
||||
noteguard::sources::start(declared);
|
||||
|
||||
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();
|
||||
|
||||
for line in stdin.lines() {
|
||||
@@ -176,12 +432,14 @@ fn noteguard() {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use noteguard::filters::{Kinds, ProtectedEvents, RateLimit, Whitelist};
|
||||
use noteguard::{Action, Note};
|
||||
use serde_json::json;
|
||||
|
||||
// Helper function to create a mock InputMessage
|
||||
fn create_mock_input_message(event_id: &str, message_type: &str) -> 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 {
|
||||
@@ -195,20 +453,7 @@ mod tests {
|
||||
},
|
||||
received_at: 0,
|
||||
source_type: "mock_source".to_string(),
|
||||
source_info: "mock_source_info".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to create a mock OutputMessage
|
||||
fn create_mock_output_message(
|
||||
event_id: &str,
|
||||
action: Action,
|
||||
msg: Option<&str>,
|
||||
) -> OutputMessage {
|
||||
OutputMessage {
|
||||
id: event_id.to_string(),
|
||||
action,
|
||||
msg: msg.map(|s| s.to_string()),
|
||||
source_info: source_info.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,6 +462,7 @@ mod tests {
|
||||
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"));
|
||||
@@ -261,17 +507,17 @@ mod tests {
|
||||
.load_config(&config)
|
||||
.expect("Failed to load config");
|
||||
|
||||
let input_message = create_mock_input_message("test_event_1", "new");
|
||||
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() {
|
||||
fn test_protected_events_reject() {
|
||||
let mut noteguard = Noteguard::new();
|
||||
|
||||
// Create a mock config with one filter (ProtectedEvents) which will shadow reject the input
|
||||
// Create a mock config with one filter (ProtectedEvents) which will reject the input
|
||||
let config: Config = toml::from_str(
|
||||
r#"
|
||||
pipeline = ["protected_events"]
|
||||
@@ -285,7 +531,7 @@ mod tests {
|
||||
.load_config(&config)
|
||||
.expect("Failed to load config");
|
||||
|
||||
let input_message = create_mock_input_message("test_event_3", "new");
|
||||
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);
|
||||
@@ -309,12 +555,361 @@ mod tests {
|
||||
.load_config(&config)
|
||||
.expect("Failed to load config");
|
||||
|
||||
let input_message = create_mock_input_message("test_event_2", "new");
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
// Default rejection messages, pinned byte for byte so that making them
|
||||
// configurable can never change what an unconfigured relay sends.
|
||||
|
||||
/// Load `config_toml`, push `count` identical notes from one IP through the
|
||||
/// pipeline, and return the last output.
|
||||
fn run_n(config_toml: &str, count: usize) -> OutputMessage {
|
||||
let mut noteguard = Noteguard::new();
|
||||
let config: Config = toml::from_str(config_toml).expect("Failed to parse config");
|
||||
noteguard
|
||||
.load_config(&config)
|
||||
.expect("Failed to load config");
|
||||
|
||||
let mut out = None;
|
||||
for i in 0..count {
|
||||
let input = create_mock_input_message(&format!("e{i}"), "new", "1.2.3.4");
|
||||
out = Some(noteguard.run(input));
|
||||
}
|
||||
out.expect("count must be at least 1")
|
||||
}
|
||||
|
||||
fn assert_reject_msg(out: OutputMessage, expected: &str) {
|
||||
assert_eq!(out.action, Action::Reject);
|
||||
assert_eq!(out.msg.as_deref(), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_message_blacklist() {
|
||||
let out = run_n(
|
||||
"pipeline = [\"blacklist\"]\n[filters.blacklist]\npubkeys = [\"mock_pubkey\"]\n",
|
||||
1,
|
||||
);
|
||||
assert_reject_msg(out, "blocked: pubkey/ip is blacklisted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_message_whitelist() {
|
||||
let out = run_n(
|
||||
"pipeline = [\"whitelist\"]\n[filters.whitelist]\npubkeys = [\"someone_else\"]\n",
|
||||
1,
|
||||
);
|
||||
assert_reject_msg(out, "blocked: pubkey/ip not on the whitelist");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_message_kinds_fallback() {
|
||||
// A blocked kind with no entry in `messages` gets the generic default.
|
||||
let out = run_n("pipeline = [\"kinds\"]\n[filters.kinds]\nkinds = [1]\n", 1);
|
||||
assert_reject_msg(out, "blocked: note kind is not allowed here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_message_protected() {
|
||||
let out = run_n(
|
||||
"pipeline = [\"protected_events\"]\n[filters.protected_events]\n",
|
||||
1,
|
||||
);
|
||||
assert_reject_msg(out, "blocked: event marked as protected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_message_ratelimit() {
|
||||
// First note seeds the bucket, the second is rate limited.
|
||||
let out = run_n(
|
||||
"pipeline = [\"ratelimit\"]\n[filters.ratelimit]\nposts_per_minute = 1\n",
|
||||
2,
|
||||
);
|
||||
assert_reject_msg(out, "rate-limited: you are noting too much");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_message_ban() {
|
||||
// Seed, then two consecutive rate-limit hits trip `ban_after = 2`.
|
||||
let out = run_n(
|
||||
"pipeline = [\"ratelimit\"]\n[filters.ratelimit]\nposts_per_minute = 1\nban_after = 2\n",
|
||||
3,
|
||||
);
|
||||
assert_reject_msg(out, "banned: too many violations, try again later");
|
||||
}
|
||||
|
||||
// Custom rejection messages: each filter's optional `message` key.
|
||||
|
||||
#[test]
|
||||
fn blacklist_custom_message() {
|
||||
let out = run_n(
|
||||
"pipeline = [\"blacklist\"]\n[filters.blacklist]\npubkeys = [\"mock_pubkey\"]\n\
|
||||
message = \"go away\"\n",
|
||||
1,
|
||||
);
|
||||
assert_reject_msg(out, "go away");
|
||||
|
||||
// The same message covers IP and CIDR matches.
|
||||
let out = run_n(
|
||||
"pipeline = [\"blacklist\"]\n[filters.blacklist]\ncidrs = [\"1.2.3.0/24\"]\n\
|
||||
message = \"go away\"\n",
|
||||
1,
|
||||
);
|
||||
assert_reject_msg(out, "go away");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitelist_custom_message() {
|
||||
let out = run_n(
|
||||
"pipeline = [\"whitelist\"]\n[filters.whitelist]\npubkeys = [\"someone_else\"]\n\
|
||||
message = \"members only\"\n",
|
||||
1,
|
||||
);
|
||||
assert_reject_msg(out, "members only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinds_message_fallback_order() {
|
||||
let mut noteguard = Noteguard::new();
|
||||
let config: Config = toml::from_str(
|
||||
r#"
|
||||
pipeline = ["kinds"]
|
||||
[filters.kinds]
|
||||
kinds = [1, 2]
|
||||
message = "generic kind block"
|
||||
[filters.kinds.messages]
|
||||
1 = "kind one block"
|
||||
"#,
|
||||
)
|
||||
.expect("Failed to parse config");
|
||||
noteguard
|
||||
.load_config(&config)
|
||||
.expect("Failed to load config");
|
||||
|
||||
// A per-kind entry wins over `message`...
|
||||
let input = create_mock_input_message("k1", "new", "1.2.3.4");
|
||||
assert_reject_msg(noteguard.run(input), "kind one block");
|
||||
|
||||
// ...and `message` wins over the built-in default.
|
||||
let mut input = create_mock_input_message("k2", "new", "1.2.3.4");
|
||||
input.event.kind = 2;
|
||||
assert_reject_msg(noteguard.run(input), "generic kind block");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protected_events_custom_message() {
|
||||
let out = run_n(
|
||||
"pipeline = [\"protected_events\"]\n[filters.protected_events]\n\
|
||||
message = \"no protected events here\"\n",
|
||||
1,
|
||||
);
|
||||
assert_reject_msg(out, "no protected events here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_without_sources_parses() {
|
||||
let config: Config =
|
||||
toml::from_str("pipeline = []\n[filters]\n").expect("Failed to parse config");
|
||||
assert!(config.sources.is_empty());
|
||||
}
|
||||
|
||||
/// Load a config file from the repo with every source pointed at a missing
|
||||
/// file, declared but never started: no network, no `remote` feature
|
||||
/// needed, and every list stays "never loaded".
|
||||
fn load_repo_config(path: &str) -> Noteguard {
|
||||
let contents = std::fs::read_to_string(format!("{}/{path}", env!("CARGO_MANIFEST_DIR")))
|
||||
.expect("read config");
|
||||
let mut config: Config = toml::from_str(&contents).expect("Failed to parse config");
|
||||
for source in config.sources.values_mut() {
|
||||
source.url = "/nonexistent/noteguard-example-source".to_string();
|
||||
}
|
||||
noteguard::sources::declare(&config.sources).expect("sources declare");
|
||||
|
||||
let mut noteguard = Noteguard::new();
|
||||
noteguard
|
||||
.load_config(&config)
|
||||
.expect("Failed to load config");
|
||||
noteguard
|
||||
}
|
||||
|
||||
fn plain_note(pubkey: &str) -> InputMessage {
|
||||
let mut msg = create_mock_input_message("example", "new", "1.2.3.4");
|
||||
msg.event.tags.clear();
|
||||
msg.event.pubkey = pubkey.to_string();
|
||||
msg
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_example_config_loads() {
|
||||
let mut noteguard = load_repo_config("noteguard-free.example.toml");
|
||||
assert_eq!(noteguard.loaded_filters.len(), 5);
|
||||
// Lists not loaded yet: the free relay still accepts a plain note.
|
||||
assert_eq!(noteguard.run(plain_note("anyone")).action, Action::Accept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premium_example_config_loads() {
|
||||
let mut noteguard = load_repo_config("noteguard-premium.example.toml");
|
||||
assert_eq!(noteguard.loaded_filters.len(), 6);
|
||||
// No premium list and no cache: the gate fails closed.
|
||||
assert_reject_msg(
|
||||
noteguard.run(plain_note("anyone")),
|
||||
"restricted: membership list unavailable, try again shortly",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_noteguard_toml_still_loads() {
|
||||
let noteguard = load_repo_config("noteguard.toml");
|
||||
assert_eq!(noteguard.loaded_filters.len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_input_message() {
|
||||
let input_json = r#"
|
||||
|
||||
+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"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! HTTP(S) transport for sources (the `remote` feature): a blocking `ureq`
|
||||
//! GET, as in `cloudflare.rs`. Only ever called from startup and the reload
|
||||
//! thread, never from the note path.
|
||||
|
||||
use super::runtime::{read_capped, SourceConfig};
|
||||
|
||||
/// GET `config.url` with the source's timeout, size cap and optional bearer
|
||||
/// token. Any non-2xx status is an error, so an API error page can never
|
||||
/// replace a good list.
|
||||
pub(crate) fn fetch(config: &SourceConfig) -> Result<Vec<u8>, String> {
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.timeout_connect(config.timeout())
|
||||
.timeout(config.timeout())
|
||||
.build();
|
||||
|
||||
let mut request = agent.get(&config.url);
|
||||
if let Some(var) = &config.token_env {
|
||||
let token = std::env::var(var).map_err(|_| format!("token_env ${var} is not set"))?;
|
||||
request = request.set("Authorization", &format!("Bearer {token}"));
|
||||
}
|
||||
|
||||
let response = request.call().map_err(|e| match e {
|
||||
ureq::Error::Status(code, _) => format!("HTTP {code}"),
|
||||
ureq::Error::Transport(t) => t.to_string(),
|
||||
})?;
|
||||
read_capped(response.into_reader(), config.max_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::sources::{declare, pubkey_source, PubkeySet, Source, SourceConfig};
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
const A: &str = "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93";
|
||||
const B: &str = "879d67486027539073d6531d271e3791b15c3e48becbfe4c3727e93355330cc8";
|
||||
|
||||
/// One canned reply: status, body, and how long to stall before replying.
|
||||
struct Reply(u16, String, Duration);
|
||||
|
||||
fn ok(body: &str) -> Reply {
|
||||
Reply(200, body.to_string(), Duration::ZERO)
|
||||
}
|
||||
|
||||
/// Serve `replies` to successive connections on a local port. Returns the
|
||||
/// base URL and the raw requests received so far.
|
||||
fn serve(replies: Vec<Reply>) -> (String, Arc<Mutex<Vec<String>>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}/list", listener.local_addr().unwrap());
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let log = seen.clone();
|
||||
std::thread::spawn(move || {
|
||||
for Reply(status, body, delay) in replies {
|
||||
let Ok((mut conn, _)) = listener.accept() else {
|
||||
return;
|
||||
};
|
||||
let mut req = Vec::new();
|
||||
let mut buf = [0u8; 1024];
|
||||
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
|
||||
match conn.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => req.extend_from_slice(&buf[..n]),
|
||||
}
|
||||
}
|
||||
log.lock()
|
||||
.unwrap()
|
||||
.push(String::from_utf8_lossy(&req).into_owned());
|
||||
std::thread::sleep(delay);
|
||||
let _ = write!(
|
||||
conn,
|
||||
"HTTP/1.1 {status} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
}
|
||||
});
|
||||
(url, seen)
|
||||
}
|
||||
|
||||
fn source(name: &str, url: &str, extra: &str) -> Arc<Source<PubkeySet>> {
|
||||
let config: SourceConfig =
|
||||
toml::from_str(&format!("url = \"{url}\"\nformat = \"pubkeys\"\n{extra}")).unwrap();
|
||||
declare(&HashMap::from([(name.to_string(), config)])).unwrap();
|
||||
pubkey_source(name).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_200_loads() {
|
||||
let (url, _) = serve(vec![ok(&format!(r#"["{A}"]"#))]);
|
||||
let src = source("h_200", &url, "");
|
||||
src.initial_load();
|
||||
assert!(src.get().unwrap().is_active(A, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_500_keeps_last_good() {
|
||||
let (url, _) = serve(vec![
|
||||
ok(&format!(r#"["{A}"]"#)),
|
||||
Reply(500, format!(r#"["{B}"]"#), Duration::ZERO),
|
||||
]);
|
||||
let src = source("h_500", &url, "");
|
||||
src.initial_load();
|
||||
assert_eq!(src.reload(), Err("HTTP 500".to_string()));
|
||||
let set = src.get().unwrap();
|
||||
assert!(set.is_active(A, 0));
|
||||
assert!(!set.is_active(B, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_timeout_keeps_last_good() {
|
||||
let (url, _) = serve(vec![
|
||||
ok(&format!(r#"["{A}"]"#)),
|
||||
Reply(200, format!(r#"["{B}"]"#), Duration::from_secs(3)),
|
||||
]);
|
||||
let src = source("h_timeout", &url, "timeout_secs = 1");
|
||||
src.initial_load();
|
||||
assert!(src.reload().is_err());
|
||||
assert!(src.get().unwrap().is_active(A, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_oversize_rejected() {
|
||||
let (url, _) = serve(vec![ok(&format!(r#"["{A}", "{B}"]"#))]);
|
||||
let src = source("h_oversize", &url, "max_bytes = 80");
|
||||
assert!(src.reload().unwrap_err().contains("max_bytes"));
|
||||
assert!(!src.is_loaded());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_header_sent_when_env_set() {
|
||||
std::env::set_var("NOTEGUARD_TEST_TOKEN_BEARER", "s3cret");
|
||||
let (url, seen) = serve(vec![ok("[]")]);
|
||||
let src = source(
|
||||
"h_bearer",
|
||||
&url,
|
||||
"token_env = \"NOTEGUARD_TEST_TOKEN_BEARER\"",
|
||||
);
|
||||
src.reload().unwrap();
|
||||
let req = seen.lock().unwrap()[0].to_ascii_lowercase();
|
||||
assert!(req.contains("authorization: bearer s3cret"), "{req}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_auth_header_without_token_env() {
|
||||
let (url, seen) = serve(vec![ok("[]")]);
|
||||
source("h_noauth", &url, "").reload().unwrap();
|
||||
let req = seen.lock().unwrap()[0].to_ascii_lowercase();
|
||||
assert!(!req.contains("authorization"), "{req}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_token_env_fails_fetch() {
|
||||
let src = source(
|
||||
"h_notoken",
|
||||
"http://127.0.0.1:9/never",
|
||||
"token_env = \"NOTEGUARD_TEST_TOKEN_UNSET\"",
|
||||
);
|
||||
assert!(src.reload().unwrap_err().contains("is not set"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Remote lists ("sources") shared by write-path filters: premium members,
|
||||
//! pubkey blacklists and word blocklists, fetched outside the note path and
|
||||
//! read by filters through a cheap snapshot. See [`runtime`] for the loading
|
||||
//! model and [`parse`] for the accepted body shapes.
|
||||
|
||||
#[cfg(feature = "remote")]
|
||||
mod http;
|
||||
pub mod parse;
|
||||
pub mod runtime;
|
||||
|
||||
pub use parse::{parse_nip05, parse_pubkeys, parse_words, Format, PubkeySet, WordList};
|
||||
pub use runtime::{
|
||||
declare, now_unix, pubkey_source, start, word_source, Declared, PubkeyRef, Source,
|
||||
SourceConfig, WordsRef,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use runtime::testing;
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Pure parsers for remote list bodies. No I/O: bytes in, typed list out.
|
||||
//!
|
||||
//! The parsers are deliberately shape-tolerant so a small change on the API
|
||||
//! side (an extra field, a wrapper object) does not need a noteguard release.
|
||||
//! Entries that cannot be used are skipped and counted, never fatal; only a
|
||||
//! body that is not the expected JSON shape at all is an error.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// How a source's body is parsed, from `format = "..."` in `[sources.<name>]`.
|
||||
#[derive(Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Format {
|
||||
/// Hex pubkeys with optional expiry (premium members, pubkey blacklist).
|
||||
Pubkeys,
|
||||
/// Words or phrases (content blocklist).
|
||||
Words,
|
||||
/// A NIP-05 `nostr.json` document: the pubkeys of its `names` map, with no
|
||||
/// expiry. Usable anywhere a pubkey list is (e.g. `whitelist`).
|
||||
Nip05,
|
||||
}
|
||||
|
||||
/// Hex pubkeys, each with an optional expiry in unix seconds (`None` never
|
||||
/// expires). Expiry is checked on every lookup, so a stale copy kept through
|
||||
/// an API outage still drops members on time.
|
||||
#[derive(Default, Debug)]
|
||||
pub struct PubkeySet {
|
||||
map: HashMap<String, Option<u64>>,
|
||||
}
|
||||
|
||||
impl PubkeySet {
|
||||
/// Whether `pubkey` is listed and not yet expired at `now_unix`. Nostr
|
||||
/// pubkeys are lowercase hex (NIP-01) and list entries are lowercased on
|
||||
/// parse, so the lookup is an exact match.
|
||||
pub fn is_active(&self, pubkey: &str, now_unix: u64) -> bool {
|
||||
match self.map.get(pubkey) {
|
||||
Some(None) => true,
|
||||
Some(Some(expires_at)) => now_unix < *expires_at,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.map.is_empty()
|
||||
}
|
||||
|
||||
/// Add `pubkey` (already validated), keeping the most generous expiry when
|
||||
/// it is listed twice: no expiry beats any expiry, a later one beats an
|
||||
/// earlier one.
|
||||
pub(crate) fn insert(&mut self, pubkey: String, expires_at: Option<u64>) {
|
||||
let merged = match (self.map.get(&pubkey), expires_at) {
|
||||
(Some(None), _) | (_, None) => None,
|
||||
(Some(Some(old)), Some(new)) => Some((*old).max(new)),
|
||||
(None, Some(new)) => Some(new),
|
||||
};
|
||||
self.map.insert(pubkey, merged);
|
||||
}
|
||||
}
|
||||
|
||||
/// Words or phrases, trimmed, empties dropped. Matching (and any
|
||||
/// normalization for it) is the consuming filter's job.
|
||||
#[derive(Default, Debug)]
|
||||
pub struct WordList(pub Vec<String>);
|
||||
|
||||
/// Lowercase `s` and check it is a 64-char hex pubkey. npub (bech32) and
|
||||
/// anything else malformed return `None`.
|
||||
pub(crate) fn normalize_hex_pubkey(s: &str) -> Option<String> {
|
||||
let s = s.trim().to_ascii_lowercase();
|
||||
(s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())).then_some(s)
|
||||
}
|
||||
|
||||
/// The list inside `body`: a top-level array, or an object holding the array
|
||||
/// under `key` (e.g. `{"pubkeys": [...]}`).
|
||||
fn top_level_array(body: &[u8], key: &str) -> Result<Vec<Value>, String> {
|
||||
let value: Value = serde_json::from_slice(body).map_err(|e| format!("invalid JSON: {e}"))?;
|
||||
match value {
|
||||
Value::Array(items) => Ok(items),
|
||||
Value::Object(mut obj) => match obj.remove(key) {
|
||||
Some(Value::Array(items)) => Ok(items),
|
||||
_ => Err(format!("expected a JSON array or {{\"{key}\": [...]}}")),
|
||||
},
|
||||
_ => Err(format!("expected a JSON array or {{\"{key}\": [...]}}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a pubkey list. Accepts a JSON array (optionally wrapped as
|
||||
/// `{"pubkeys": [...]}`) whose items are either a hex string or an object
|
||||
/// `{"pubkey": "<hex>", "expires_at": <unix secs or null>}`; other object
|
||||
/// fields are ignored. Returns the set and how many items were skipped.
|
||||
pub fn parse_pubkeys(body: &[u8]) -> Result<(PubkeySet, usize), String> {
|
||||
let mut set = PubkeySet::default();
|
||||
let mut skipped = 0;
|
||||
|
||||
for item in top_level_array(body, "pubkeys")? {
|
||||
let entry = match &item {
|
||||
Value::String(s) => normalize_hex_pubkey(s).map(|pk| (pk, None)),
|
||||
Value::Object(obj) => {
|
||||
let pubkey = obj
|
||||
.get("pubkey")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(normalize_hex_pubkey);
|
||||
// Missing or null means no expiry; anything else must be
|
||||
// non-negative integer seconds, or the entry is unusable.
|
||||
let expires_at = match obj.get("expires_at") {
|
||||
None | Some(Value::Null) => Some(None),
|
||||
Some(v) => v.as_u64().map(Some),
|
||||
};
|
||||
pubkey.zip(expires_at)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
match entry {
|
||||
Some((pubkey, expires_at)) => set.insert(pubkey, expires_at),
|
||||
None => skipped += 1,
|
||||
}
|
||||
}
|
||||
|
||||
Ok((set, skipped))
|
||||
}
|
||||
|
||||
/// Parse a word list: a JSON array of strings (optionally wrapped as
|
||||
/// `{"words": [...]}`). Entries are trimmed; empty and non-string entries are
|
||||
/// skipped and counted.
|
||||
pub fn parse_words(body: &[u8]) -> Result<(WordList, usize), String> {
|
||||
let mut words = Vec::new();
|
||||
let mut skipped = 0;
|
||||
|
||||
for item in top_level_array(body, "words")? {
|
||||
match item.as_str().map(str::trim) {
|
||||
Some(w) if !w.is_empty() => words.push(w.to_owned()),
|
||||
_ => skipped += 1,
|
||||
}
|
||||
}
|
||||
|
||||
Ok((WordList(words), skipped))
|
||||
}
|
||||
|
||||
/// Parse a NIP-05 `nostr.json` (`{"names": {"alice": "<hex>", ...}}`) into a
|
||||
/// pubkey set with no expiries. `relays` and other fields are ignored; invalid
|
||||
/// keys are skipped and counted. A body without a `names` object is an error,
|
||||
/// so a server that only answers `?name=` lookups is caught at load time.
|
||||
pub fn parse_nip05(body: &[u8]) -> Result<(PubkeySet, usize), String> {
|
||||
let value: Value = serde_json::from_slice(body).map_err(|e| format!("invalid JSON: {e}"))?;
|
||||
let names = value
|
||||
.get("names")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or("expected a NIP-05 document with a \"names\" object")?;
|
||||
|
||||
let mut set = PubkeySet::default();
|
||||
let mut skipped = 0;
|
||||
for pubkey in names.values() {
|
||||
match pubkey.as_str().and_then(normalize_hex_pubkey) {
|
||||
Some(pk) => set.insert(pk, None),
|
||||
None => skipped += 1,
|
||||
}
|
||||
}
|
||||
Ok((set, skipped))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const A: &str = "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93";
|
||||
const B: &str = "879d67486027539073d6531d271e3791b15c3e48becbfe4c3727e93355330cc8";
|
||||
|
||||
fn pubkeys(json: &str) -> (PubkeySet, usize) {
|
||||
parse_pubkeys(json.as_bytes()).expect("parses")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_plain_hex_array() {
|
||||
let (set, skipped) = pubkeys(&format!(r#"["{A}", "{B}"]"#));
|
||||
assert_eq!((set.len(), skipped), (2, 0));
|
||||
assert!(set.is_active(A, 0));
|
||||
assert!(set.is_active(B, u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_object_array_with_expiry() {
|
||||
let (set, _) = pubkeys(&format!(
|
||||
r#"[{{"pubkey": "{A}", "expires_at": 1000, "tier": "gold"}}]"#
|
||||
));
|
||||
assert!(set.is_active(A, 999));
|
||||
assert!(!set.is_active(A, 1000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_wrapped_object() {
|
||||
let (set, _) = pubkeys(&format!(r#"{{"pubkeys": ["{A}"], "count": 1}}"#));
|
||||
assert!(set.is_active(A, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_strings_and_objects() {
|
||||
let (set, skipped) = pubkeys(&format!(r#"["{A}", {{"pubkey": "{B}"}}]"#));
|
||||
assert_eq!((set.len(), skipped), (2, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uppercase_normalized() {
|
||||
let (set, _) = pubkeys(&format!(r#"["{}"]"#, A.to_uppercase()));
|
||||
assert!(set.is_active(A, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_and_npub_skipped_and_counted() {
|
||||
let (set, skipped) = pubkeys(&format!(
|
||||
r#"["{A}",
|
||||
"npub1zmpp2krkzzy2lse8flvny3h48xy3fau7psmfx8mugg7jr27rt6fs9h6k6c",
|
||||
"abc", 42, null,
|
||||
{{"pubkey": "{B}", "expires_at": -1}},
|
||||
{{"pubkey": "{B}", "expires_at": "2026-01-01"}},
|
||||
{{"expires_at": 5}}]"#
|
||||
));
|
||||
assert_eq!((set.len(), skipped), (1, 7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_keeps_latest_expiry() {
|
||||
let (set, _) = pubkeys(&format!(
|
||||
r#"[{{"pubkey": "{A}", "expires_at": 2000}}, {{"pubkey": "{A}", "expires_at": 1000}}]"#
|
||||
));
|
||||
assert!(set.is_active(A, 1500));
|
||||
assert!(!set.is_active(A, 2000));
|
||||
|
||||
// No expiry wins over any expiry, whichever comes first.
|
||||
let (set, _) = pubkeys(&format!(
|
||||
r#"["{A}", {{"pubkey": "{A}", "expires_at": 1000}}]"#
|
||||
));
|
||||
assert!(set.is_active(A, u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_expiry_never_expires() {
|
||||
let (set, _) = pubkeys(&format!(r#"[{{"pubkey": "{A}", "expires_at": null}}]"#));
|
||||
assert!(set.is_active(A, u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_is_inactive_at_boundary() {
|
||||
let (set, _) = pubkeys(&format!(r#"[{{"pubkey": "{A}", "expires_at": 1000}}]"#));
|
||||
assert!(set.is_active(A, 999));
|
||||
assert!(!set.is_active(A, 1000));
|
||||
assert!(!set.is_active(B, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_array_is_an_empty_list() {
|
||||
let (set, skipped) = pubkeys("[]");
|
||||
assert!(set.is_empty());
|
||||
assert_eq!(skipped, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_array_and_wrapped() {
|
||||
let (words, skipped) = parse_words(br#"[" Damus Airdrop ", "", 7, "spam"]"#).unwrap();
|
||||
assert_eq!(words.0, vec!["Damus Airdrop", "spam"]);
|
||||
assert_eq!(skipped, 2);
|
||||
|
||||
let (words, _) = parse_words(br#"{"words": ["spam"]}"#).unwrap();
|
||||
assert_eq!(words.0, vec!["spam"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nip05_names_parsed() {
|
||||
let (set, skipped) = parse_nip05(
|
||||
format!(
|
||||
r#"{{"names": {{"alice": "{A}", "bob": "{}"}}, "relays": {{}}}}"#,
|
||||
B.to_uppercase()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((set.len(), skipped), (2, 0));
|
||||
assert!(set.is_active(A, u64::MAX));
|
||||
assert!(set.is_active(B, u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nip05_invalid_hex_skipped() {
|
||||
let (set, skipped) = parse_nip05(
|
||||
format!(r#"{{"names": {{"a": "{A}", "b": "npub1x", "c": 7}}}}"#).as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((set.len(), skipped), (1, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nip05_missing_names_is_error() {
|
||||
assert!(parse_nip05(br#"{"relays": {}}"#).is_err());
|
||||
assert!(parse_nip05(br#"{"names": ["not", "a", "map"]}"#).is_err());
|
||||
assert!(parse_nip05(b"[]").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_json_is_error() {
|
||||
assert!(parse_pubkeys(b"<html>502 Bad Gateway</html>").is_err());
|
||||
assert!(parse_pubkeys(br#"{"error": "unauthorized"}"#).is_err());
|
||||
assert!(parse_pubkeys(b"\"just a string\"").is_err());
|
||||
assert!(parse_words(br#"{"pubkeys": []}"#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,711 @@
|
||||
//! Loading, reloading and sharing named sources.
|
||||
//!
|
||||
//! Sources are declared once from the top-level `[sources.<name>]` tables,
|
||||
//! before any filter is built, and live in a process-global registry. Filters
|
||||
//! name the sources they use in their own config (`exempt_source = "premium"`)
|
||||
//! and resolve them while they deserialize, through [`PubkeyRef`] and
|
||||
//! [`WordsRef`]. A typo is therefore a startup error, like any other bad
|
||||
//! config, never a silently empty list.
|
||||
//!
|
||||
//! ## Why a snapshot and a background thread
|
||||
//!
|
||||
//! `filter_note` runs synchronously on strfry's ingest path, so no fetch may
|
||||
//! happen there. Each source holds an `Arc` snapshot behind an `RwLock`; a note
|
||||
//! only clones the `Arc` (a refcount bump), while one background thread per
|
||||
//! process refetches every `reload_secs` and swaps in a new snapshot when the
|
||||
//! body parses. On any failure the last good snapshot stays in place.
|
||||
//!
|
||||
//! The first load happens synchronously at startup, bounded by `timeout_secs`,
|
||||
//! so a list-gated relay does not reject the first notes after every restart.
|
||||
//! If it fails, the optional `cache_path` (the last good body, written after
|
||||
//! every successful fetch) is used instead, which covers a restart during an
|
||||
//! API outage.
|
||||
//!
|
||||
//! strfry runs one plugin process per ingester thread, so each source is
|
||||
//! fetched by each process. Cache writes go through a per-process temp file
|
||||
//! and an atomic rename, so concurrent writers never leave a torn file.
|
||||
|
||||
use super::parse::{parse_nip05, parse_pubkeys, parse_words, Format, PubkeySet, WordList};
|
||||
use log::{error, info, warn};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, RwLock};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Floor for `reload_secs`, so a typo cannot hammer the API.
|
||||
pub const MIN_RELOAD_SECS: u64 = 30;
|
||||
const DEFAULT_RELOAD_SECS: u64 = 300;
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
const DEFAULT_MAX_BYTES: u64 = 10 * 1024 * 1024;
|
||||
|
||||
/// One `[sources.<name>]` table.
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SourceConfig {
|
||||
/// `https://...`, `http://...`, `file:///abs/path` or a plain file path.
|
||||
pub url: String,
|
||||
/// How the body is parsed.
|
||||
pub format: Format,
|
||||
/// Name of the env var holding a bearer token for HTTP sources. The token
|
||||
/// itself never goes in the config file.
|
||||
#[serde(default)]
|
||||
pub token_env: Option<String>,
|
||||
/// Seconds between reloads. Default 300, minimum [`MIN_RELOAD_SECS`].
|
||||
#[serde(default)]
|
||||
pub reload_secs: Option<u64>,
|
||||
/// Per-request timeout in seconds for HTTP sources. Default 10.
|
||||
#[serde(default)]
|
||||
pub timeout_secs: Option<u64>,
|
||||
/// Bodies larger than this are rejected. Default 10 MiB.
|
||||
#[serde(default)]
|
||||
pub max_bytes: Option<u64>,
|
||||
/// Where to keep the last good body for restarts during an outage.
|
||||
#[serde(default)]
|
||||
pub cache_path: Option<String>,
|
||||
}
|
||||
|
||||
impl SourceConfig {
|
||||
pub fn reload_interval(&self) -> Duration {
|
||||
Duration::from_secs(
|
||||
self.reload_secs
|
||||
.unwrap_or(DEFAULT_RELOAD_SECS)
|
||||
.max(MIN_RELOAD_SECS),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn timeout(&self) -> Duration {
|
||||
Duration::from_secs(self.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS).max(1))
|
||||
}
|
||||
|
||||
pub fn max_bytes(&self) -> u64 {
|
||||
self.max_bytes.unwrap_or(DEFAULT_MAX_BYTES)
|
||||
}
|
||||
|
||||
pub fn is_http(&self) -> bool {
|
||||
self.url.starts_with("http://") || self.url.starts_with("https://")
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds since the unix epoch, the clock list expiries are compared to.
|
||||
pub fn now_unix() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Read all of `reader`, failing if it holds more than `max` bytes.
|
||||
pub(crate) fn read_capped(reader: impl Read, max: u64) -> Result<Vec<u8>, String> {
|
||||
let mut body = Vec::new();
|
||||
reader
|
||||
.take(max.saturating_add(1))
|
||||
.read_to_end(&mut body)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if body.len() as u64 > max {
|
||||
return Err(format!("body exceeds max_bytes ({max})"));
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn read_file(path: &str, max: u64) -> Result<Vec<u8>, String> {
|
||||
let file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
read_capped(file, max).map_err(|e| format!("{path}: {e}"))
|
||||
}
|
||||
|
||||
/// Fetch a source's raw body from wherever its `url` points.
|
||||
fn fetch(config: &SourceConfig) -> Result<Vec<u8>, String> {
|
||||
if config.is_http() {
|
||||
#[cfg(feature = "remote")]
|
||||
return super::http::fetch(config);
|
||||
#[cfg(not(feature = "remote"))]
|
||||
return Err("http(s) sources need the `remote` build feature".to_string());
|
||||
}
|
||||
let path = config.url.strip_prefix("file://").unwrap_or(&config.url);
|
||||
read_file(path, config.max_bytes())
|
||||
}
|
||||
|
||||
/// Atomically replace `path` with `body`: write a per-process temp file, then
|
||||
/// rename it over the target.
|
||||
fn write_cache(path: &str, body: &[u8]) -> std::io::Result<()> {
|
||||
let tmp = format!("{path}.tmp.{}", std::process::id());
|
||||
std::fs::write(&tmp, body)?;
|
||||
std::fs::rename(&tmp, path)
|
||||
}
|
||||
|
||||
/// A list type a source can hold.
|
||||
pub trait List: Send + Sync + Sized + 'static {
|
||||
/// Parse a body. Returns the list and how many entries were skipped.
|
||||
fn parse(format: Format, body: &[u8]) -> Result<(Self, usize), String>;
|
||||
fn len(&self) -> usize;
|
||||
}
|
||||
|
||||
impl List for PubkeySet {
|
||||
fn parse(format: Format, body: &[u8]) -> Result<(Self, usize), String> {
|
||||
match format {
|
||||
Format::Pubkeys => parse_pubkeys(body),
|
||||
Format::Nip05 => parse_nip05(body),
|
||||
Format::Words => Err("format `words` does not hold pubkeys".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
PubkeySet::len(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl List for WordList {
|
||||
fn parse(format: Format, body: &[u8]) -> Result<(Self, usize), String> {
|
||||
match format {
|
||||
Format::Words => parse_words(body),
|
||||
Format::Pubkeys | Format::Nip05 => {
|
||||
Err(format!("format `{format:?}` does not hold words"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// A named, reloadable list. `None` in the snapshot means it has never loaded
|
||||
/// (no fetch and no cache succeeded), which a gate treats differently from an
|
||||
/// empty list.
|
||||
pub struct Source<T> {
|
||||
name: String,
|
||||
config: SourceConfig,
|
||||
snapshot: RwLock<Option<Arc<T>>>,
|
||||
loaded_at: Mutex<Option<Instant>>,
|
||||
}
|
||||
|
||||
impl<T: List> Source<T> {
|
||||
fn new(name: &str, config: SourceConfig) -> Self {
|
||||
Source {
|
||||
name: name.to_string(),
|
||||
config,
|
||||
snapshot: RwLock::new(None),
|
||||
loaded_at: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
/// The current list, or `None` if it has never loaded. Cheap: one `Arc`
|
||||
/// clone under a read lock.
|
||||
pub fn get(&self) -> Option<Arc<T>> {
|
||||
self.snapshot
|
||||
.read()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub fn is_loaded(&self) -> bool {
|
||||
self.get().is_some()
|
||||
}
|
||||
|
||||
fn swap(&self, list: T) {
|
||||
*self
|
||||
.snapshot
|
||||
.write()
|
||||
.unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(list));
|
||||
*self
|
||||
.loaded_at
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner) = Some(Instant::now());
|
||||
}
|
||||
|
||||
/// Fetch, parse and swap in a new snapshot, then refresh the cache. On any
|
||||
/// error the current snapshot is left untouched. Returns the entry count.
|
||||
pub fn reload(&self) -> Result<usize, String> {
|
||||
let body = fetch(&self.config)?;
|
||||
let (list, skipped) = T::parse(self.config.format, &body)?;
|
||||
let count = list.len();
|
||||
self.swap(list);
|
||||
info!(
|
||||
"source {}: loaded {count} entries ({skipped} skipped)",
|
||||
self.name
|
||||
);
|
||||
if let Some(path) = &self.config.cache_path {
|
||||
if let Err(e) = write_cache(path, &body) {
|
||||
warn!("source {}: could not write cache {path}: {e}", self.name);
|
||||
}
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
fn load_cache(&self) -> Result<usize, String> {
|
||||
let path = self.config.cache_path.as_deref().ok_or("no cache_path")?;
|
||||
let body = read_file(path, self.config.max_bytes())?;
|
||||
let (list, _) = T::parse(self.config.format, &body)?;
|
||||
let count = list.len();
|
||||
self.swap(list);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// Startup load: the source itself, else the disk cache, else leave the
|
||||
/// list unavailable (logged as an error).
|
||||
pub fn initial_load(&self) {
|
||||
let Err(e) = self.reload() else { return };
|
||||
match self.load_cache() {
|
||||
Ok(n) => warn!(
|
||||
"source {}: fetch failed ({e}); using cached copy with {n} entries",
|
||||
self.name
|
||||
),
|
||||
Err(cache_err) => error!(
|
||||
"source {}: fetch failed ({e}) and no usable cache ({cache_err}); \
|
||||
list unavailable until a reload succeeds",
|
||||
self.name
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The type-erased view the reload thread needs.
|
||||
trait Reload: Send + Sync {
|
||||
fn initial_load(&self);
|
||||
fn reload_logged(&self);
|
||||
fn interval(&self) -> Duration;
|
||||
}
|
||||
|
||||
impl<T: List> Reload for Source<T> {
|
||||
fn initial_load(&self) {
|
||||
Source::initial_load(self)
|
||||
}
|
||||
|
||||
fn reload_logged(&self) {
|
||||
if let Err(e) = self.reload() {
|
||||
let age = self
|
||||
.loaded_at
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.map(|t| format!("{}s old", t.elapsed().as_secs()))
|
||||
.unwrap_or_else(|| "never loaded".to_string());
|
||||
warn!(
|
||||
"source {}: reload failed, keeping last good copy ({age}): {e}",
|
||||
self.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn interval(&self) -> Duration {
|
||||
self.config.reload_interval()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum Entry {
|
||||
Pubkeys(Arc<Source<PubkeySet>>),
|
||||
Words(Arc<Source<WordList>>),
|
||||
}
|
||||
|
||||
static REGISTRY: OnceLock<Mutex<HashMap<String, Entry>>> = OnceLock::new();
|
||||
|
||||
fn registry() -> MutexGuard<'static, HashMap<String, Entry>> {
|
||||
REGISTRY
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Sources registered by [`declare`] and not yet loaded; hand them to [`start`].
|
||||
pub struct Declared(Vec<Arc<dyn Reload>>);
|
||||
|
||||
/// Register every `[sources.<name>]` table so filters can resolve them, without
|
||||
/// loading anything yet. Fails on a config that can never work.
|
||||
pub fn declare(configs: &HashMap<String, SourceConfig>) -> Result<Declared, String> {
|
||||
let mut declared: Vec<Arc<dyn Reload>> = Vec::new();
|
||||
let mut reg = registry();
|
||||
for (name, config) in configs {
|
||||
if config.is_http() && !cfg!(feature = "remote") {
|
||||
return Err(format!(
|
||||
"source `{name}`: http(s) url needs a build with --features remote"
|
||||
));
|
||||
}
|
||||
// Log whether the token is there, never the token itself. A missing
|
||||
// token is not fatal: the fetch fails and the cache (if any) is used.
|
||||
if let Some(var) = &config.token_env {
|
||||
if std::env::var_os(var).is_some() {
|
||||
info!("source {name}: bearer token from ${var}");
|
||||
} else {
|
||||
error!("source {name}: token_env ${var} is not set");
|
||||
}
|
||||
}
|
||||
let entry = match config.format {
|
||||
Format::Pubkeys | Format::Nip05 => {
|
||||
let source = Arc::new(Source::<PubkeySet>::new(name, config.clone()));
|
||||
declared.push(source.clone());
|
||||
Entry::Pubkeys(source)
|
||||
}
|
||||
Format::Words => {
|
||||
let source = Arc::new(Source::<WordList>::new(name, config.clone()));
|
||||
declared.push(source.clone());
|
||||
Entry::Words(source)
|
||||
}
|
||||
};
|
||||
reg.insert(name.clone(), entry);
|
||||
}
|
||||
Ok(Declared(declared))
|
||||
}
|
||||
|
||||
/// Load every declared source once (synchronously), then reload each on its
|
||||
/// own interval from one background thread.
|
||||
pub fn start(declared: Declared) {
|
||||
let sources = declared.0;
|
||||
if sources.is_empty() {
|
||||
return;
|
||||
}
|
||||
for source in &sources {
|
||||
source.initial_load();
|
||||
}
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("noteguard-sources".to_string())
|
||||
.spawn(move || {
|
||||
let mut next: Vec<Instant> = sources
|
||||
.iter()
|
||||
.map(|s| Instant::now() + s.interval())
|
||||
.collect();
|
||||
loop {
|
||||
let (i, due) = next
|
||||
.iter()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.min_by_key(|(_, due)| *due)
|
||||
.expect("sources is non-empty");
|
||||
std::thread::sleep(due.saturating_duration_since(Instant::now()));
|
||||
sources[i].reload_logged();
|
||||
next[i] = Instant::now() + sources[i].interval();
|
||||
}
|
||||
})
|
||||
.expect("spawn source reload thread");
|
||||
}
|
||||
|
||||
fn unknown(name: &str) -> String {
|
||||
format!("unknown source `{name}`: declare it under [sources.{name}]")
|
||||
}
|
||||
|
||||
/// Resolve a declared pubkey source by name.
|
||||
pub fn pubkey_source(name: &str) -> Result<Arc<Source<PubkeySet>>, String> {
|
||||
match registry().get(name) {
|
||||
Some(Entry::Pubkeys(source)) => Ok(source.clone()),
|
||||
Some(_) => Err(format!("source `{name}` is not a pubkey list")),
|
||||
None => Err(unknown(name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a declared word source by name.
|
||||
pub fn word_source(name: &str) -> Result<Arc<Source<WordList>>, String> {
|
||||
match registry().get(name) {
|
||||
Some(Entry::Words(source)) => Ok(source.clone()),
|
||||
Some(_) => Err(format!("source `{name}` is not a word list")),
|
||||
None => Err(unknown(name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter config field naming a pubkey source, resolved while the filter
|
||||
/// deserializes (`exempt_source = "premium"`).
|
||||
pub struct PubkeyRef(Arc<Source<PubkeySet>>);
|
||||
|
||||
impl<'de> Deserialize<'de> for PubkeyRef {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let name = String::deserialize(deserializer)?;
|
||||
pubkey_source(&name)
|
||||
.map(PubkeyRef)
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl PubkeyRef {
|
||||
/// Whether `pubkey` is in the list and not expired. `false` while the list
|
||||
/// has never loaded.
|
||||
pub fn is_active(&self, pubkey: &str) -> bool {
|
||||
self.0
|
||||
.get()
|
||||
.is_some_and(|set| set.is_active(pubkey, now_unix()))
|
||||
}
|
||||
|
||||
pub fn is_loaded(&self) -> bool {
|
||||
self.0.is_loaded()
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
self.0.name()
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter config field naming a word source (`words_source = "words"`).
|
||||
pub struct WordsRef(Arc<Source<WordList>>);
|
||||
|
||||
impl<'de> Deserialize<'de> for WordsRef {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let name = String::deserialize(deserializer)?;
|
||||
word_source(&name)
|
||||
.map(WordsRef)
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl WordsRef {
|
||||
/// The current word list, or `None` if it has never loaded.
|
||||
pub fn get(&self) -> Option<Arc<WordList>> {
|
||||
self.0.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// Helpers for filter tests: register in-memory sources under unique names.
|
||||
#[cfg(test)]
|
||||
#[allow(dead_code)] // used by the filter tests as each filter gains sources
|
||||
pub(crate) mod testing {
|
||||
use super::*;
|
||||
|
||||
fn config(format: Format) -> SourceConfig {
|
||||
SourceConfig {
|
||||
url: "/nonexistent/noteguard-test-source".to_string(),
|
||||
format,
|
||||
token_env: None,
|
||||
reload_secs: None,
|
||||
timeout_secs: None,
|
||||
max_bytes: None,
|
||||
cache_path: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Register pubkey source `name`. `None` leaves it never loaded.
|
||||
pub fn pubkeys(name: &str, entries: Option<&[(&str, Option<u64>)]>) {
|
||||
let source = Arc::new(Source::<PubkeySet>::new(name, config(Format::Pubkeys)));
|
||||
if let Some(entries) = entries {
|
||||
let mut set = PubkeySet::default();
|
||||
for (pk, exp) in entries {
|
||||
set.insert(pk.to_string(), *exp);
|
||||
}
|
||||
source.swap(set);
|
||||
}
|
||||
registry().insert(name.to_string(), Entry::Pubkeys(source));
|
||||
}
|
||||
|
||||
/// Register word source `name`, or replace its snapshot if it exists (a
|
||||
/// simulated reload). `None` leaves a new source never loaded.
|
||||
pub fn words(name: &str, words: Option<&[&str]>) {
|
||||
let existing = word_source(name).ok();
|
||||
let source = existing
|
||||
.clone()
|
||||
.unwrap_or_else(|| Arc::new(Source::<WordList>::new(name, config(Format::Words))));
|
||||
if let Some(words) = words {
|
||||
source.swap(WordList(words.iter().map(|w| w.to_string()).collect()));
|
||||
}
|
||||
if existing.is_none() {
|
||||
registry().insert(name.to_string(), Entry::Words(source));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const A: &str = "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93";
|
||||
const B: &str = "879d67486027539073d6531d271e3791b15c3e48becbfe4c3727e93355330cc8";
|
||||
|
||||
/// A per-test temp path, so parallel tests never share files.
|
||||
fn tmp(name: &str) -> String {
|
||||
std::env::temp_dir()
|
||||
.join(format!("noteguard-src-{}-{name}", std::process::id()))
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
fn cfg(toml_cfg: &str) -> SourceConfig {
|
||||
toml::from_str(toml_cfg).expect("valid source config")
|
||||
}
|
||||
|
||||
/// Declare one source called `name` and return its pubkey handle.
|
||||
fn declare_pubkeys(name: &str, config: SourceConfig) -> Arc<Source<PubkeySet>> {
|
||||
declare(&HashMap::from([(name.to_string(), config)])).expect("declares");
|
||||
pubkey_source(name).expect("resolves")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_source_loads_at_start() {
|
||||
let path = tmp("loads");
|
||||
std::fs::write(&path, format!(r#"["{A}"]"#)).unwrap();
|
||||
let src = declare_pubkeys(
|
||||
"t_loads",
|
||||
cfg(&format!("url = \"file://{path}\"\nformat = \"pubkeys\"")),
|
||||
);
|
||||
assert!(!src.is_loaded());
|
||||
src.initial_load();
|
||||
assert!(src.get().unwrap().is_active(A, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_picks_up_change() {
|
||||
let path = tmp("change");
|
||||
std::fs::write(&path, format!(r#"["{A}"]"#)).unwrap();
|
||||
let src = declare_pubkeys(
|
||||
"t_change",
|
||||
cfg(&format!("url = \"{path}\"\nformat = \"pubkeys\"")),
|
||||
);
|
||||
src.initial_load();
|
||||
|
||||
std::fs::write(&path, format!(r#"["{B}"]"#)).unwrap();
|
||||
assert_eq!(src.reload(), Ok(1));
|
||||
let set = src.get().unwrap();
|
||||
assert!(!set.is_active(A, 0));
|
||||
assert!(set.is_active(B, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_reload_keeps_last_good() {
|
||||
let path = tmp("bad");
|
||||
std::fs::write(&path, format!(r#"["{A}"]"#)).unwrap();
|
||||
let src = declare_pubkeys(
|
||||
"t_bad",
|
||||
cfg(&format!("url = \"{path}\"\nformat = \"pubkeys\"")),
|
||||
);
|
||||
src.initial_load();
|
||||
|
||||
std::fs::write(&path, "<html>502</html>").unwrap();
|
||||
assert!(src.reload().is_err());
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert!(src.reload().is_err());
|
||||
assert!(src.get().unwrap().is_active(A, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversize_rejected_keeps_last_good() {
|
||||
let path = tmp("oversize");
|
||||
let body = format!(r#"["{A}"]"#);
|
||||
std::fs::write(&path, &body).unwrap();
|
||||
let src = declare_pubkeys(
|
||||
"t_oversize",
|
||||
cfg(&format!(
|
||||
"url = \"{path}\"\nformat = \"pubkeys\"\nmax_bytes = {}",
|
||||
body.len()
|
||||
)),
|
||||
);
|
||||
src.initial_load();
|
||||
assert!(src.is_loaded());
|
||||
|
||||
// One byte over the cap is rejected.
|
||||
std::fs::write(&path, format!(r#"["{B}" ]"#)).unwrap();
|
||||
assert!(src.reload().unwrap_err().contains("max_bytes"));
|
||||
assert!(src.get().unwrap().is_active(A, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_written_after_success() {
|
||||
let (path, cache) = (tmp("cw-src"), tmp("cw-cache"));
|
||||
let body = format!(r#"["{A}"]"#);
|
||||
std::fs::write(&path, &body).unwrap();
|
||||
let src = declare_pubkeys(
|
||||
"t_cache_write",
|
||||
cfg(&format!(
|
||||
"url = \"{path}\"\nformat = \"pubkeys\"\ncache_path = \"{cache}\""
|
||||
)),
|
||||
);
|
||||
src.initial_load();
|
||||
assert_eq!(std::fs::read_to_string(&cache).unwrap(), body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_used_when_source_missing_at_start() {
|
||||
let cache = tmp("cu-cache");
|
||||
std::fs::write(
|
||||
&cache,
|
||||
format!(r#"[{{"pubkey": "{A}", "expires_at": null}}]"#),
|
||||
)
|
||||
.unwrap();
|
||||
let src = declare_pubkeys(
|
||||
"t_cache_use",
|
||||
cfg(&format!(
|
||||
"url = \"{}\"\nformat = \"pubkeys\"\ncache_path = \"{cache}\"",
|
||||
tmp("cu-missing")
|
||||
)),
|
||||
);
|
||||
src.initial_load();
|
||||
assert!(src.get().unwrap().is_active(A, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_loaded_is_none() {
|
||||
let src = declare_pubkeys(
|
||||
"t_never",
|
||||
cfg(&format!(
|
||||
"url = \"{}\"\nformat = \"pubkeys\"",
|
||||
tmp("never-missing")
|
||||
)),
|
||||
);
|
||||
src.initial_load();
|
||||
assert!(src.get().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_mismatch_is_error() {
|
||||
declare(&HashMap::from([(
|
||||
"t_words_only".to_string(),
|
||||
cfg("url = \"/x\"\nformat = \"words\""),
|
||||
)]))
|
||||
.unwrap();
|
||||
assert!(pubkey_source("t_words_only")
|
||||
.err()
|
||||
.unwrap()
|
||||
.contains("not a pubkey list"));
|
||||
assert!(word_source("t_words_only").is_ok());
|
||||
assert!(pubkey_source("t_nobody_declared_this")
|
||||
.err()
|
||||
.unwrap()
|
||||
.contains("unknown source"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ref_resolves_while_deserializing() {
|
||||
testing::pubkeys("t_ref", Some(&[("pk", None)]));
|
||||
#[derive(Deserialize)]
|
||||
struct Filter {
|
||||
exempt_source: PubkeyRef,
|
||||
}
|
||||
let f: Filter = toml::from_str("exempt_source = \"t_ref\"").unwrap();
|
||||
assert!(f.exempt_source.is_active("pk"));
|
||||
assert_eq!(f.exempt_source.name(), "t_ref");
|
||||
|
||||
let err = toml::from_str::<Filter>("exempt_source = \"t_ref_typo\"")
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(err.to_string().contains("unknown source"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_interval_clamped() {
|
||||
assert_eq!(
|
||||
cfg("url = \"/x\"\nformat = \"words\"").reload_interval(),
|
||||
Duration::from_secs(300)
|
||||
);
|
||||
assert_eq!(
|
||||
cfg("url = \"/x\"\nformat = \"words\"\nreload_secs = 1").reload_interval(),
|
||||
Duration::from_secs(MIN_RELOAD_SECS)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_rejects_unknown_keys() {
|
||||
assert!(
|
||||
toml::from_str::<SourceConfig>("url = \"/x\"\nformat = \"words\"\nreload = 5").is_err()
|
||||
);
|
||||
assert!(toml::from_str::<SourceConfig>("url = \"/x\"\nformat = \"nope\"").is_err());
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "remote"))]
|
||||
#[test]
|
||||
fn http_url_without_feature_fails_declare() {
|
||||
let err = declare(&HashMap::from([(
|
||||
"t_http_nofeature".to_string(),
|
||||
cfg("url = \"https://example.com/list\"\nformat = \"pubkeys\""),
|
||||
)]))
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(err.contains("--features remote"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{"id":"eabb9491951fc64d85b6cba28a7d53c333c3f1d59779d63abccf9a8f61a0bdef","action":"reject","msg":"blocked: pubkey/ip not on the whitelist"}
|
||||
{"id":"70651d96a2b6b3431cc06b7543249ccd22ab5c203c6aa590b7688f916f252f8f","action":"reject","msg":"blocked: event marked as protected"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","action":"accept"}
|
||||
{"id":"kind30065_00","action":"reject","msg":"blocked: files on nostr is dumb"}
|
||||
{"id":"kind34550_00","action":"reject","msg":"blocked: please use a dedicated relay for moderated communities"}
|
||||
{"id":"content_plain_00","action":"shadowReject"}
|
||||
{"id":"content_homoglyph_00","action":"shadowReject"}
|
||||
{"id":"ratelimit_00","action":"reject","msg":"rate-limited: you note too much"}
|
||||
{"id":"ratelimit_01","action":"reject","msg":"rate-limited: you note too much"}
|
||||
{"id":"ratelimit_02","action":"reject","msg":"rate-limited: you note too much"}
|
||||
{"id":"ratelimit_03","action":"reject","msg":"rate-limited: you note too much"}
|
||||
{"id":"ratelimit_04","action":"reject","msg":"rate-limited: you note too much"}
|
||||
{"id":"ratelimit_05","action":"reject","msg":"rate-limited: you note too much"}
|
||||
{"id":"ratelimit_06","action":"reject","msg":"rate-limited: you note too much"}
|
||||
{"id":"ratelimit_07","action":"reject","msg":"rate-limited: you note too much"}
|
||||
{"id":"ratelimit_08","action":"reject","msg":"rate-limited: you note too much"}
|
||||
{"id":"ratelimit_09","action":"reject","msg":"banned: too many rate-limit violations, try again later"}
|
||||
{"id":"ratelimit_10","action":"reject","msg":"banned: too many rate-limit violations, try again later"}
|
||||
@@ -0,0 +1,30 @@
|
||||
{"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"}}
|
||||
{"type": "new","receivedAt":12345,"sourceType":"IP4","sourceInfo": "127.0.0.1","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.1","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.1","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.2","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.2","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.2","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.2","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.2","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.2","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.2","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.2","event":{"id": "68421a122cef086512b2c5bd29ca6285ced8bd8e302e347e3c5d90466c860a76","pubkey": "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at": 1720408658,"kind": 1,"tags": [],"content": "hi","sig": "7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"10.0.0.1","event":{"id":"kind30065_00","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":30065,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"10.0.0.1","event":{"id":"kind34550_00","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":34550,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"10.0.0.2","event":{"id":"content_plain_00","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"free Damus Airdrop here","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"10.0.0.2","event":{"id":"content_homoglyph_00","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"D\u0430mus \u0410irdrop is open","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_00","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_01","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_02","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_03","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_04","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_05","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_06","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_07","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_08","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_09","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
{"type":"new","receivedAt":12345,"sourceType":"IP4","sourceInfo":"127.0.0.2","event":{"id":"ratelimit_10","pubkey":"16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93","created_at":1720408658,"kind":1,"tags":[],"content":"hi","sig":"7b76471744ded2b720ca832cdc89e670f6093ce38aeef55a5c6a4e077883d7d80dda1e9051032fb1faa1c3c212c517e93ee42b3ceac8e8e9b04bad46a361de90"}}
|
||||
@@ -0,0 +1,71 @@
|
||||
# Frozen copy of the write-side noteguard.toml as of e5a3e47, used by tests/golden.rs.
|
||||
# Do not edit: it pins today's behavior so later changes can prove they kept it.
|
||||
|
||||
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"]
|
||||
ips = ["127.0.0.1"]
|
||||
|
||||
[filters.kinds]
|
||||
kinds = [30065, 1064, 34550, 4550]
|
||||
|
||||
[filters.kinds.messages]
|
||||
30065 = "blocked: files on nostr is dumb"
|
||||
1064 = "blocked: files on nostr is dumb"
|
||||
34550 = "blocked: please use a dedicated relay for moderated communities"
|
||||
4550 = "blocked: please use a dedicated relay for moderated communities"
|
||||
|
||||
[filters.protected_events]
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Golden-output test: pipes `test/golden.inputs` through the real binary with
|
||||
//! the frozen `test/golden.toml` and compares stdout line by line against
|
||||
//! `test/golden.expected`. It pins today's observable behavior (every accept,
|
||||
//! reject message and shadow reject) so later changes can prove they kept it.
|
||||
//!
|
||||
//! The inputs cover each write-side path: whitelist reject, protected event,
|
||||
//! per-kind messages, content shadow reject (plain and homoglyph), rate limit,
|
||||
//! and the rate-limit ban. They all arrive within one second, so the ratelimit
|
||||
//! token refill (whole seconds) never kicks in and the output is deterministic.
|
||||
//!
|
||||
//! To regenerate after an intentional behavior change:
|
||||
//! NOTEGUARD_CONFIG=test/golden.toml ./target/debug/noteguard \
|
||||
//! < test/golden.inputs > test/golden.expected
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
#[test]
|
||||
fn golden_output_matches() {
|
||||
let root = env!("CARGO_MANIFEST_DIR");
|
||||
let inputs = std::fs::read(format!("{root}/test/golden.inputs")).expect("read golden.inputs");
|
||||
let expected =
|
||||
std::fs::read_to_string(format!("{root}/test/golden.expected")).expect("read golden.expected");
|
||||
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_noteguard"))
|
||||
.env("NOTEGUARD_CONFIG", format!("{root}/test/golden.toml"))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("spawn noteguard");
|
||||
|
||||
// Drop stdin after writing so noteguard sees EOF and exits.
|
||||
child
|
||||
.stdin
|
||||
.take()
|
||||
.expect("stdin")
|
||||
.write_all(&inputs)
|
||||
.expect("write inputs");
|
||||
let out = child.wait_with_output().expect("noteguard output");
|
||||
assert!(out.status.success(), "noteguard exited with {}", out.status);
|
||||
|
||||
let actual = String::from_utf8(out.stdout).expect("utf8 stdout");
|
||||
let actual: Vec<&str> = actual.lines().collect();
|
||||
let expected: Vec<&str> = expected.lines().collect();
|
||||
for (i, (a, e)) in actual.iter().zip(&expected).enumerate() {
|
||||
assert_eq!(a, e, "golden mismatch at output line {}", i + 1);
|
||||
}
|
||||
assert_eq!(actual.len(), expected.len(), "golden output line count");
|
||||
}
|
||||
Reference in New Issue
Block a user