cloudflare: escalate BanTracker IP-bans to a WAF IP list (edge block)
Add an optional, feature-gated Cloudflare integration that escalates any write-path IP-ban to the edge. Because both the ratelimit and content filters funnel their bans through the shared `BanTracker::strike`, that one hook is the single choke point: when a ban trips, the offender's IP is added to a Cloudflare WAF IP list for the ban's duration, then removed when it expires, so a banned IP is dropped by Cloudflare before it ever reaches the relay. A new `cloudflare` module owns a process-global background worker (std thread + mpsc, blocking `ureq`) shared by every `BanTracker`, armed once at startup from a top-level `[cloudflare]` config table. The worker is required because (a) HTTP must not block the note path and (b) a banned IP never reaches noteguard again, so the local `banned_until` can't drive cleanup — removals are scheduled on the worker's own expiry timer instead. The Lists API is async and deletes by item id, so removal resolves the id via `GET ?search=<ip>` then `DELETE`. The API token comes from the CLOUDFLARE_API_TOKEN env var (never the config file); the non-secret account_id/list_id live in `[cloudflare]`. The operator wires the list into a zone WAF custom rule once — noteguard only manages list membership. Entirely opt-in: with no `[cloudflare]` section, a missing token, or the feature compiled out, `edge_ban` is a no-op and noteguard behaves as before. Verified end-to-end against a mock Cloudflare endpoint: two spam notes trip a content ban, POST adds the IP with the right bearer token and body, and the 2s expiry timer fires the GET+DELETE. Worker scheduling/dedup/extend logic is unit-tested via a mock API (30 lib tests pass); default build is unchanged. Changelog-Added: Optional Cloudflare edge-banning (cloudflare feature): IP-bans from the ratelimit and content filters are pushed to a Cloudflare WAF IP list and removed when they expire Headway: headway:noteguard/fluid-tonight-siren Agentium: agentium:neck-case-fog Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
64f246e547
commit
fc5a3938b3
Generated
+417
-1
@@ -26,6 +26,12 @@ version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.3"
|
||||
@@ -129,11 +135,17 @@ dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"miniz_oxide",
|
||||
"miniz_oxide 0.7.4",
|
||||
"object 0.36.1",
|
||||
"rustc-demangle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.1"
|
||||
@@ -416,6 +428,17 @@ dependencies = [
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.18.0"
|
||||
@@ -485,6 +508,17 @@ version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d"
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"miniz_oxide 0.9.1",
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -512,6 +546,15 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures"
|
||||
version = "0.3.34"
|
||||
@@ -679,6 +722,110 @@ version = "2.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"potential_utf",
|
||||
"utf8_iter",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_core"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"litemap",
|
||||
"tinystr",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_normalizer_data",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"smallvec",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_collections",
|
||||
"icu_locale_core",
|
||||
"icu_properties_data",
|
||||
"icu_provider",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider"
|
||||
version = "2.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_locale_core",
|
||||
"writeable",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
|
||||
dependencies = [
|
||||
"idna_adapter",
|
||||
"smallvec",
|
||||
"utf8_iter",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna_adapter"
|
||||
version = "1.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
|
||||
dependencies = [
|
||||
"icu_normalizer",
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
@@ -751,6 +898,12 @@ version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
@@ -787,6 +940,16 @@ dependencies = [
|
||||
"adler",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "0.8.11"
|
||||
@@ -829,6 +992,7 @@ dependencies = [
|
||||
"tokio-tungstenite",
|
||||
"toml",
|
||||
"unicode-security",
|
||||
"ureq",
|
||||
"wasmtime",
|
||||
]
|
||||
|
||||
@@ -913,6 +1077,12 @@ dependencies = [
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.14"
|
||||
@@ -937,6 +1107,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
|
||||
dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.17"
|
||||
@@ -1058,6 +1237,20 @@ version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b"
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-demangle"
|
||||
version = "0.1.24"
|
||||
@@ -1096,6 +1289,41 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6725596c3f2c3a0aef021139e145d4eafe314a6623e4680ca83852b2c67ab2ba"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.18"
|
||||
@@ -1213,6 +1441,12 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.9"
|
||||
@@ -1247,6 +1481,12 @@ version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
@@ -1269,6 +1509,17 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-lexicon"
|
||||
version = "0.13.5"
|
||||
@@ -1337,6 +1588,16 @@ dependencies = [
|
||||
"syn 3.0.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.13.2"
|
||||
@@ -1469,12 +1730,54 @@ dependencies = [
|
||||
"unicode-script",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "2.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"flate2",
|
||||
"log",
|
||||
"once_cell",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"url",
|
||||
"webpki-roots 0.26.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "url"
|
||||
version = "2.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"idna",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf-8"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
@@ -1702,6 +2005,24 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "0.26.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||
dependencies = [
|
||||
"webpki-roots 1.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
@@ -1873,3 +2194,98 @@ name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
|
||||
dependencies = [
|
||||
"stable_deref_trait",
|
||||
"yoke-derive",
|
||||
"zerofrom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke-derive"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
|
||||
dependencies = [
|
||||
"zerofrom-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom-derive"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec"
|
||||
version = "0.11.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
|
||||
dependencies = [
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec-derive"
|
||||
version = "0.11.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"
|
||||
|
||||
@@ -7,6 +7,8 @@ edition = "2021"
|
||||
forwarder = ["tokio-tungstenite", "tokio", "futures-util"]
|
||||
# nscript: run user-submitted WASM note filters (Phase 0 spike)
|
||||
nscript = ["wasmtime"]
|
||||
# cloudflare: escalate BanTracker IP-bans to a Cloudflare WAF IP list (edge block)
|
||||
cloudflare = ["ureq"]
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
@@ -24,3 +26,6 @@ env_logger = "0.11.3"
|
||||
|
||||
# nscript deps
|
||||
wasmtime = { version = "48", optional = true, default-features = false, features = ["cranelift", "runtime", "std"] }
|
||||
|
||||
# cloudflare deps — blocking HTTP client for the edge-ban worker
|
||||
ureq = { version = "2", optional = true, features = ["json"] }
|
||||
|
||||
@@ -100,6 +100,30 @@ Settings:
|
||||
|
||||
- `ban_message` *optional*: the error message returned to a banned IP. Default is: `banned: too many rate-limit violations, try again later`
|
||||
|
||||
### Cloudflare edge-banning
|
||||
|
||||
*Requires the `cloudflare` build feature (`cargo build --features cloudflare`).*
|
||||
|
||||
Any IP-ban — from `ratelimit`'s consecutive streak **or** `content`'s cumulative one — can be escalated to the edge. When enabled, a banned IP is added to a Cloudflare WAF IP list for the ban's duration and removed when it expires, so offenders are dropped by Cloudflare before they ever reach the relay. It is a single shared worker, so one configuration covers every filter that bans.
|
||||
|
||||
One-time Cloudflare setup (noteguard does **not** do this for you): create an IP list and a WAF custom rule that blocks it, e.g. expression `(ip.src in $your_list)` with action *block*. noteguard only manages the list's membership.
|
||||
|
||||
Configure it with a top-level `[cloudflare]` table:
|
||||
|
||||
```toml
|
||||
[cloudflare]
|
||||
account_id = "<cloudflare account id>"
|
||||
list_id = "<ip list id>"
|
||||
# comment = "noteguard auto-ban" # optional; stamped on each list item
|
||||
# timeout_secs = 10 # optional; per-request HTTP timeout
|
||||
# api_base = "..." # optional; override the API base URL
|
||||
```
|
||||
|
||||
- The API token is read from the **`CLOUDFLARE_API_TOKEN`** environment variable (needs *Account → Account Filter Lists → Edit*), never from the config file. If the section is present but the env var is unset, edge-banning is logged as disabled and the relay keeps running with relay-local bans only.
|
||||
- Omit the `[cloudflare]` section (or build without the feature) to disable edge-banning entirely.
|
||||
|
||||
Caveats: strfry runs one plugin process per ingester thread, each with its own banner — Cloudflare de-duplicates list items by value, so redundant adds are harmless. If a process dies mid-ban its pending removal is lost and the IP lingers in the list until a later run (or a human) clears it; the per-item `comment` tags noteguard's entries so they are easy to find.
|
||||
|
||||
### Whitelist
|
||||
|
||||
* name: `whitelist`
|
||||
|
||||
@@ -30,6 +30,28 @@ filters = [
|
||||
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"]
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
//! Shared Cloudflare edge-ban integration for the write-path [`BanTracker`].
|
||||
//!
|
||||
//! When a filter's local ban trips (ratelimit's consecutive streak or content's
|
||||
//! cumulative one — both funnel through [`BanTracker::strike`](crate::filters)),
|
||||
//! we also add the offender's IP to a Cloudflare **WAF IP list**, and remove it
|
||||
//! again when the ban expires. The operator wires that list into a zone WAF
|
||||
//! custom rule once (`ip.src in $your_list` → *block*); noteguard only manages
|
||||
//! the list's *membership*, so a banned IP is dropped at Cloudflare's edge before
|
||||
//! it ever reaches the relay.
|
||||
//!
|
||||
//! The banner is a single process-global background worker shared by every
|
||||
//! `BanTracker` (both the ratelimit and content filters escalate to the same
|
||||
//! list), configured once from the top-level `[cloudflare]` table plus the
|
||||
//! `CLOUDFLARE_API_TOKEN` env var. It is entirely opt-in: with no `[cloudflare]`
|
||||
//! section (or the feature compiled out) [`edge_ban`] is a no-op and noteguard
|
||||
//! behaves exactly as before.
|
||||
//!
|
||||
//! ## Why a background worker and a timer
|
||||
//!
|
||||
//! Two things force the design:
|
||||
//!
|
||||
//! * **HTTP must not block the note path.** strfry feeds events line-by-line;
|
||||
//! a ban is rare but an API round-trip is slow, so bans are handed to a
|
||||
//! background thread over a channel and the filter returns immediately.
|
||||
//! * **Expiry can't be driven by the note path.** Once an IP is blocked at the
|
||||
//! edge it never reaches noteguard again, so nothing on the ingest side can
|
||||
//! notice the local ban elapsing. The worker therefore schedules each removal
|
||||
//! on a timer of its own.
|
||||
//!
|
||||
//! ## Caveats
|
||||
//!
|
||||
//! * strfry runs one plugin process per ingester thread, each with its own
|
||||
//! worker; several may add the same IP. Cloudflare's list de-duplicates by
|
||||
//! value, so the redundant adds are harmless, and each worker removes on its
|
||||
//! own timer.
|
||||
//! * If a process dies mid-ban its pending removal is lost and the IP lingers in
|
||||
//! the list until a later run (or a human) clears it. The per-item `comment`
|
||||
//! tags noteguard's entries so they're easy to find.
|
||||
|
||||
use log::{info, warn};
|
||||
use serde::Deserialize;
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::{BinaryHeap, HashMap};
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Cloudflare API base, overridable via config for tests / self-hosted gateways.
|
||||
fn default_api_base() -> String {
|
||||
"https://api.cloudflare.com/client/v4".to_string()
|
||||
}
|
||||
|
||||
/// The `[cloudflare]` config table. The API token is *not* here — it comes from
|
||||
/// the `CLOUDFLARE_API_TOKEN` environment variable so the secret stays out of
|
||||
/// the config file.
|
||||
#[derive(Deserialize, Clone)]
|
||||
pub struct CloudflareConfig {
|
||||
/// Cloudflare account that owns the IP list.
|
||||
pub account_id: String,
|
||||
/// Id of the WAF IP list to manage membership of.
|
||||
pub list_id: String,
|
||||
/// API base URL. Defaults to the public Cloudflare API.
|
||||
#[serde(default)]
|
||||
pub api_base: Option<String>,
|
||||
/// Comment stamped on each list item, so noteguard's entries are identifiable.
|
||||
#[serde(default)]
|
||||
pub comment: Option<String>,
|
||||
/// Per-request HTTP timeout in seconds. Defaults to 10.
|
||||
#[serde(default)]
|
||||
pub timeout_secs: Option<u64>,
|
||||
}
|
||||
|
||||
/// A request for the background worker: edge-ban `ip` for `duration`.
|
||||
struct BanCommand {
|
||||
ip: String,
|
||||
duration: Duration,
|
||||
}
|
||||
|
||||
/// The Cloudflare list operations the worker needs. Abstracted behind a trait so
|
||||
/// the worker's scheduling/dedup logic can be unit-tested without real HTTP.
|
||||
trait CfApi: Send {
|
||||
/// Append `ip` to the list (Cloudflare de-duplicates by value).
|
||||
fn add(&self, ip: &str);
|
||||
/// Resolve `ip`'s list-item id and delete it.
|
||||
fn remove(&self, ip: &str);
|
||||
}
|
||||
|
||||
/// Live Cloudflare Lists API client (`ureq`, blocking).
|
||||
#[cfg(feature = "cloudflare")]
|
||||
struct CloudflareApi {
|
||||
agent: ureq::Agent,
|
||||
token: String,
|
||||
account_id: String,
|
||||
list_id: String,
|
||||
api_base: String,
|
||||
comment: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "cloudflare")]
|
||||
impl CloudflareApi {
|
||||
fn items_url(&self) -> String {
|
||||
format!(
|
||||
"{}/accounts/{}/rules/lists/{}/items",
|
||||
self.api_base, self.account_id, self.list_id
|
||||
)
|
||||
}
|
||||
|
||||
fn bearer(&self) -> String {
|
||||
format!("Bearer {}", self.token)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "cloudflare")]
|
||||
impl CfApi for CloudflareApi {
|
||||
fn add(&self, ip: &str) {
|
||||
// POST a one-element batch; the Lists API is async and returns an
|
||||
// operation_id, but for a single IP we fire-and-forget — membership
|
||||
// settles within seconds and the local ban covers the gap.
|
||||
let body = serde_json::json!([{ "ip": ip, "comment": self.comment }]);
|
||||
match self
|
||||
.agent
|
||||
.post(&self.items_url())
|
||||
.set("Authorization", &self.bearer())
|
||||
.send_json(body)
|
||||
{
|
||||
Ok(_) => info!("cloudflare: queued edge-ban add for {ip}"),
|
||||
Err(e) => warn!("cloudflare: failed to add {ip} to list: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&self, ip: &str) {
|
||||
// Deletion is by item id, so resolve it first. `search` is a substring
|
||||
// match, hence the exact-ip filter on the returned items.
|
||||
let resp = match self
|
||||
.agent
|
||||
.get(&self.items_url())
|
||||
.query("search", ip)
|
||||
.set("Authorization", &self.bearer())
|
||||
.call()
|
||||
{
|
||||
Ok(resp) => resp,
|
||||
Err(e) => {
|
||||
warn!("cloudflare: failed to look up list item for {ip}: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let json: serde_json::Value = match resp.into_json() {
|
||||
Ok(json) => json,
|
||||
Err(e) => {
|
||||
warn!("cloudflare: bad list-items response for {ip}: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let item_id = json["result"]
|
||||
.as_array()
|
||||
.and_then(|items| items.iter().find(|it| it["ip"].as_str() == Some(ip)))
|
||||
.and_then(|it| it["id"].as_str().map(str::to_owned));
|
||||
|
||||
let Some(item_id) = item_id else {
|
||||
warn!("cloudflare: no list item for {ip}; nothing to remove");
|
||||
return;
|
||||
};
|
||||
|
||||
let body = serde_json::json!({ "items": [ { "id": item_id } ] });
|
||||
match self
|
||||
.agent
|
||||
.delete(&self.items_url())
|
||||
.set("Authorization", &self.bearer())
|
||||
.send_json(body)
|
||||
{
|
||||
Ok(_) => info!("cloudflare: queued edge-ban removal for {ip}"),
|
||||
Err(e) => warn!("cloudflare: failed to remove {ip} from list: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Background worker: owns the API client and the set of currently edge-banned
|
||||
/// IPs, and schedules each removal on its own expiry timer.
|
||||
struct BanWorker<A: CfApi> {
|
||||
api: A,
|
||||
/// ip -> the deadline its ban currently expires at.
|
||||
active: HashMap<String, Instant>,
|
||||
/// Min-heap (via `Reverse`) of `(deadline, ip)` driving removals. May hold
|
||||
/// stale entries superseded by an extension; [`sweep`](Self::sweep) skips
|
||||
/// any whose deadline no longer matches `active`.
|
||||
expiries: BinaryHeap<Reverse<(Instant, String)>>,
|
||||
}
|
||||
|
||||
impl<A: CfApi> BanWorker<A> {
|
||||
fn new(api: A) -> Self {
|
||||
BanWorker {
|
||||
api,
|
||||
active: HashMap::new(),
|
||||
expiries: BinaryHeap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a ban for `ip` expiring at `deadline`. Adds to the Cloudflare list
|
||||
/// only on the first ban for an IP; a later ban merely extends the deadline
|
||||
/// (a shorter one is ignored so a ban is never cut short).
|
||||
fn on_ban(&mut self, ip: String, deadline: Instant) {
|
||||
match self.active.get(&ip) {
|
||||
Some(¤t) if current >= deadline => {} // already banned at least this long
|
||||
Some(_) => {
|
||||
// Extend: record the later deadline and push a fresh heap entry.
|
||||
// The old entry becomes stale and is skipped on sweep.
|
||||
self.active.insert(ip.clone(), deadline);
|
||||
self.expiries.push(Reverse((deadline, ip)));
|
||||
}
|
||||
None => {
|
||||
self.active.insert(ip.clone(), deadline);
|
||||
self.expiries.push(Reverse((deadline, ip.clone())));
|
||||
self.api.add(&ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove from the list every ban whose deadline has passed as of `now`.
|
||||
fn sweep(&mut self, now: Instant) {
|
||||
while let Some(Reverse((deadline, _))) = self.expiries.peek() {
|
||||
if *deadline > now {
|
||||
break;
|
||||
}
|
||||
let Reverse((deadline, ip)) = self.expiries.pop().expect("peeked");
|
||||
// Act only if this entry is the live deadline for the IP; an entry
|
||||
// superseded by an extension has a different `active` deadline.
|
||||
if self.active.get(&ip) == Some(&deadline) {
|
||||
self.api.remove(&ip);
|
||||
self.active.remove(&ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The soonest scheduled removal, if any — how long the run loop may block.
|
||||
fn next_deadline(&self) -> Option<Instant> {
|
||||
self.expiries.peek().map(|Reverse((d, _))| *d)
|
||||
}
|
||||
|
||||
/// Drive the worker: block until the next command or the next removal is due,
|
||||
/// whichever comes first, then apply it. Exits when the sender is dropped.
|
||||
fn run(mut self, rx: Receiver<BanCommand>) {
|
||||
loop {
|
||||
let received = match self.next_deadline() {
|
||||
Some(deadline) => rx.recv_timeout(deadline.saturating_duration_since(Instant::now())),
|
||||
None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected),
|
||||
};
|
||||
match received {
|
||||
Ok(cmd) => self.on_ban(cmd.ip, Instant::now() + cmd.duration),
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
self.sweep(Instant::now());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The process-global banner. `None` once initialized without a usable config
|
||||
/// (e.g. missing token), so [`edge_ban`] stays a no-op in that case.
|
||||
static BANNER: OnceLock<Option<Sender<BanCommand>>> = OnceLock::new();
|
||||
|
||||
/// Initialize the shared edge-banner from `[cloudflare]` config. Call once at
|
||||
/// startup. A missing `CLOUDFLARE_API_TOKEN` disables edge-banning (logged, not
|
||||
/// fatal — the relay still runs with relay-local bans).
|
||||
#[cfg(feature = "cloudflare")]
|
||||
pub fn init(config: CloudflareConfig) {
|
||||
let _ = BANNER.set(spawn(config));
|
||||
}
|
||||
|
||||
#[cfg(feature = "cloudflare")]
|
||||
fn spawn(config: CloudflareConfig) -> Option<Sender<BanCommand>> {
|
||||
let token = match std::env::var("CLOUDFLARE_API_TOKEN") {
|
||||
Ok(t) if !t.is_empty() => t,
|
||||
_ => {
|
||||
warn!(
|
||||
"cloudflare: [cloudflare] configured but CLOUDFLARE_API_TOKEN is unset; \
|
||||
edge-banning disabled"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let list_id = config.list_id.clone();
|
||||
let api = CloudflareApi {
|
||||
agent: ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(config.timeout_secs.unwrap_or(10)))
|
||||
.build(),
|
||||
token,
|
||||
account_id: config.account_id,
|
||||
list_id: config.list_id,
|
||||
api_base: config.api_base.unwrap_or_else(default_api_base),
|
||||
comment: config.comment.unwrap_or_else(|| "noteguard auto-ban".to_string()),
|
||||
};
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("cloudflare-banner".to_string())
|
||||
.spawn(move || BanWorker::new(api).run(rx))
|
||||
.expect("spawn cloudflare-banner thread");
|
||||
|
||||
info!("cloudflare: edge-banning enabled (list {list_id})");
|
||||
Some(tx)
|
||||
}
|
||||
|
||||
/// Escalate a local ban to the edge: add `ip` to the Cloudflare list for
|
||||
/// `duration`. A no-op unless [`init`] configured a live banner. Never blocks —
|
||||
/// the request is handed to the background worker.
|
||||
pub fn edge_ban(ip: &str, duration: Duration) {
|
||||
if let Some(Some(tx)) = BANNER.get() {
|
||||
if tx
|
||||
.send(BanCommand {
|
||||
ip: ip.to_owned(),
|
||||
duration,
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
warn!("cloudflare: banner worker is gone; dropping edge-ban for {ip}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Records `(op, ip)` calls instead of hitting the network.
|
||||
#[derive(Clone, Default)]
|
||||
struct MockApi {
|
||||
calls: Arc<Mutex<Vec<(String, String)>>>,
|
||||
}
|
||||
|
||||
impl MockApi {
|
||||
fn calls(&self) -> Vec<(String, String)> {
|
||||
self.calls.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl CfApi for MockApi {
|
||||
fn add(&self, ip: &str) {
|
||||
self.calls.lock().unwrap().push(("add".into(), ip.into()));
|
||||
}
|
||||
fn remove(&self, ip: &str) {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(("remove".into(), ip.into()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_parses_with_token_out_of_band() {
|
||||
let cfg: CloudflareConfig = toml::from_str(
|
||||
"account_id = \"acct\"\nlist_id = \"lst\"\ncomment = \"banned by noteguard\"\n",
|
||||
)
|
||||
.expect("valid cloudflare config");
|
||||
assert_eq!(cfg.account_id, "acct");
|
||||
assert_eq!(cfg.list_id, "lst");
|
||||
assert_eq!(cfg.comment.as_deref(), Some("banned by noteguard"));
|
||||
assert!(cfg.api_base.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adds_once_and_removes_on_expiry() {
|
||||
let api = MockApi::default();
|
||||
let mut w = BanWorker::new(api.clone());
|
||||
let t0 = Instant::now();
|
||||
let deadline = t0 + Duration::from_secs(60);
|
||||
|
||||
w.on_ban("1.2.3.4".into(), deadline);
|
||||
// A second ban for the same IP within the window must not re-add it.
|
||||
w.on_ban("1.2.3.4".into(), deadline);
|
||||
w.sweep(t0 + Duration::from_secs(1)); // not yet expired
|
||||
assert_eq!(api.calls(), vec![("add".into(), "1.2.3.4".into())]);
|
||||
|
||||
// Once the deadline passes, the IP is removed exactly once.
|
||||
w.sweep(t0 + Duration::from_secs(61));
|
||||
assert_eq!(
|
||||
api.calls(),
|
||||
vec![
|
||||
("add".into(), "1.2.3.4".into()),
|
||||
("remove".into(), "1.2.3.4".into()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extending_a_ban_defers_removal_and_never_double_removes() {
|
||||
let api = MockApi::default();
|
||||
let mut w = BanWorker::new(api.clone());
|
||||
let t0 = Instant::now();
|
||||
|
||||
w.on_ban("9.9.9.9".into(), t0 + Duration::from_secs(60));
|
||||
// Re-ban with a later deadline before the first elapses: extend it.
|
||||
w.on_ban("9.9.9.9".into(), t0 + Duration::from_secs(120));
|
||||
|
||||
// At the original deadline the (now stale) entry must NOT trigger a removal.
|
||||
w.sweep(t0 + Duration::from_secs(61));
|
||||
assert_eq!(api.calls(), vec![("add".into(), "9.9.9.9".into())]);
|
||||
|
||||
// Only the extended deadline removes it, and only once.
|
||||
w.sweep(t0 + Duration::from_secs(121));
|
||||
assert_eq!(
|
||||
api.calls(),
|
||||
vec![
|
||||
("add".into(), "9.9.9.9".into()),
|
||||
("remove".into(), "9.9.9.9".into()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_ips_are_tracked_independently() {
|
||||
let api = MockApi::default();
|
||||
let mut w = BanWorker::new(api.clone());
|
||||
let t0 = Instant::now();
|
||||
|
||||
w.on_ban("1.1.1.1".into(), t0 + Duration::from_secs(30));
|
||||
w.on_ban("2.2.2.2".into(), t0 + Duration::from_secs(90));
|
||||
|
||||
w.sweep(t0 + Duration::from_secs(31)); // only the first expired
|
||||
assert_eq!(
|
||||
api.calls(),
|
||||
vec![
|
||||
("add".into(), "1.1.1.1".into()),
|
||||
("add".into(), "2.2.2.2".into()),
|
||||
("remove".into(), "1.1.1.1".into()),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,12 @@ impl BanTracker {
|
||||
.ban_duration_secs
|
||||
.unwrap_or(DEFAULT_BAN_DURATION_SECS);
|
||||
state.banned_until = Some(now + Duration::from_secs(secs));
|
||||
// Escalate to the edge if a Cloudflare banner is configured. This is
|
||||
// the single choke point every write-path filter's ban flows through,
|
||||
// so both ratelimit and content get edge-banning for free. No-op
|
||||
// unless the `cloudflare` feature is built and `[cloudflare]` is set.
|
||||
#[cfg(feature = "cloudflare")]
|
||||
crate::cloudflare::edge_ban(ip, Duration::from_secs(secs));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
|
||||
@@ -6,6 +6,9 @@ pub mod readfilters;
|
||||
pub mod readmsg;
|
||||
pub mod readpolicy;
|
||||
|
||||
#[cfg(feature = "cloudflare")]
|
||||
pub mod cloudflare;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
pub mod nscript;
|
||||
|
||||
|
||||
+14
@@ -17,6 +17,13 @@ use std::io;
|
||||
struct Config {
|
||||
pipeline: Vec<String>,
|
||||
filters: HashMap<String, toml::Value>,
|
||||
|
||||
/// Shared Cloudflare edge-ban config, consumed once at startup to arm the
|
||||
/// process-global banner every `BanTracker` escalates to. Ignored when the
|
||||
/// `cloudflare` feature is not built.
|
||||
#[cfg(feature = "cloudflare")]
|
||||
#[serde(default)]
|
||||
cloudflare: Option<noteguard::cloudflare::CloudflareConfig>,
|
||||
}
|
||||
|
||||
type ConstructFilter = Box<fn(toml::Value) -> Result<Box<dyn NoteFilter>, toml::de::Error>>;
|
||||
@@ -152,6 +159,13 @@ fn noteguard() {
|
||||
.load_config(&config)
|
||||
.expect("Expected filter config to be loaded ok");
|
||||
|
||||
// Arm the shared Cloudflare edge-banner before processing notes, so the very
|
||||
// first ban can escalate to the edge.
|
||||
#[cfg(feature = "cloudflare")]
|
||||
if let Some(cf) = config.cloudflare.clone() {
|
||||
noteguard::cloudflare::init(cf);
|
||||
}
|
||||
|
||||
let stdin = io::stdin();
|
||||
|
||||
for line in stdin.lines() {
|
||||
|
||||
Reference in New Issue
Block a user