Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b25aa6cf8 | ||
|
|
d2f160e0f3 | ||
|
|
059e763022 | ||
|
|
f63e2d9087 | ||
|
|
70a69aa114 | ||
|
|
9ee6254697 | ||
|
|
a9e4c044bf | ||
|
|
0e29aab85a | ||
|
|
3fdd9738c9 | ||
|
|
215b98576e | ||
|
|
d867e64974 | ||
|
|
c46029d2d7 | ||
|
|
44d61df9c9 |
@@ -9,6 +9,8 @@ forwarder = ["tokio-tungstenite", "tokio", "futures-util"]
|
||||
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"] }
|
||||
|
||||
@@ -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,8 +1,27 @@
|
||||
# noteguard
|
||||
# Azzamo Noteguard
|
||||
|
||||
A high performance note filter plugin system for [strfry]
|
||||
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`:
|
||||
|
||||
WIP!
|
||||
| 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) |
|
||||
|
||||
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
|
||||
|
||||
@@ -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,17 +211,19 @@ 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 rate-limit violations, try again later`
|
||||
- `ban_message` *optional*: the error message returned to a banned IP. Default is: `banned: too many violations, try again later`
|
||||
|
||||
### Cloudflare edge-banning
|
||||
|
||||
@@ -134,7 +259,15 @@ The whitelist filter only allows notes to pass if it matches a particular pubkey
|
||||
|
||||
- `ips` *optional*: a list of ip addresses to let through
|
||||
|
||||
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
|
||||
|
||||
@@ -148,6 +281,25 @@ The blacklist filter blocks notes that match any pubkey, ip, or CIDR range:
|
||||
|
||||
- `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
|
||||
|
||||
* name: `kinds`
|
||||
@@ -158,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
|
||||
@@ -175,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`
|
||||
@@ -409,7 +565,21 @@ 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
|
||||
@@ -417,5 +587,15 @@ $ <test/inputs ./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"]
|
||||
+117
-9
@@ -1,3 +1,4 @@
|
||||
use crate::sources::PubkeyRef;
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use ipnetwork::IpNetwork;
|
||||
use serde::Deserialize;
|
||||
@@ -9,6 +10,11 @@ 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)]
|
||||
@@ -16,6 +22,8 @@ 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 {
|
||||
@@ -33,11 +41,25 @@ impl<'de> Deserialize<'de> for Blacklist {
|
||||
.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()) {
|
||||
@@ -59,16 +81,14 @@ impl Blacklist {
|
||||
|
||||
impl NoteFilter for Blacklist {
|
||||
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
|
||||
let reject_message = "blocked: pubkey/ip is blacklisted".to_string();
|
||||
let reject_message = self
|
||||
.message
|
||||
.as_deref()
|
||||
.unwrap_or("blocked: pubkey/ip is blacklisted")
|
||||
.to_owned();
|
||||
|
||||
if let Some(pubkeys) = &self.pubkeys {
|
||||
if pubkeys.contains(&msg.event.pubkey) {
|
||||
return OutputMessage::new(
|
||||
msg.event.id.clone(),
|
||||
Action::Reject,
|
||||
Some(reject_message),
|
||||
);
|
||||
}
|
||||
if self.is_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) {
|
||||
@@ -82,3 +102,91 @@ impl NoteFilter for Blacklist {
|
||||
"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);
|
||||
}
|
||||
}
|
||||
|
||||
+149
-14
@@ -1,6 +1,8 @@
|
||||
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;
|
||||
|
||||
@@ -15,6 +17,20 @@ pub struct Content {
|
||||
#[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
|
||||
@@ -32,29 +48,58 @@ 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 {
|
||||
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.
|
||||
if self.ban.is_banned(&msg.source_info, now) {
|
||||
// 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);
|
||||
}
|
||||
|
||||
let matched = {
|
||||
let normalized = self
|
||||
.normalized
|
||||
.get_or_insert_with(|| self.filters.iter().map(|f| normalize(f)).collect());
|
||||
let content = normalize(&msg.event.content);
|
||||
normalized.iter().any(|filter| content.contains(filter))
|
||||
};
|
||||
|
||||
if matched {
|
||||
if self.matches(&msg.event.content) {
|
||||
// Count the violation (may trip a ban for next time); either way this
|
||||
// note is shadow-rejected.
|
||||
self.ban.strike(&msg.source_info, now);
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -69,14 +114,19 @@ impl NoteFilter for 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: "pk".to_string(),
|
||||
pubkey: pubkey.to_string(),
|
||||
created_at: 0,
|
||||
kind: 1,
|
||||
tags: vec![],
|
||||
@@ -141,4 +191,89 @@ mod tests {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::filters::ban::BanTracker;
|
||||
use crate::sources::PubkeyRef;
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
@@ -15,6 +16,10 @@ pub struct RateLimit {
|
||||
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.
|
||||
@@ -37,6 +42,15 @@ 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
|
||||
@@ -113,14 +127,19 @@ impl NoteFilter for RateLimit {
|
||||
#[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: "pk".to_string(),
|
||||
pubkey: pubkey.to_string(),
|
||||
created_at: 0,
|
||||
kind: 1,
|
||||
tags: vec![],
|
||||
@@ -203,4 +222,78 @@ mod tests {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ mod read_filter;
|
||||
pub mod readfilters;
|
||||
pub mod readmsg;
|
||||
pub mod readpolicy;
|
||||
pub mod sources;
|
||||
|
||||
#[cfg(feature = "cloudflare")]
|
||||
pub mod cloudflare;
|
||||
|
||||
+218
-2
@@ -24,6 +24,10 @@ struct Config {
|
||||
#[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>>;
|
||||
@@ -371,6 +375,13 @@ fn noteguard() {
|
||||
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");
|
||||
@@ -503,10 +514,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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"]
|
||||
@@ -694,6 +705,211 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// 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#"
|
||||
|
||||
@@ -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