Skip to content
ZarielPublic

About

No description, website, or topics provided.

Resources

Stars

11 stars

Watchers

0 watching

Forks

Repository files navigation

brrpolice

brrpolice is a Rust service for qBittorrent seeding nodes. It watches peers, identifies peers that stay slow, do not make progress, or remain connected without receiving uploaded data, applies temporary bans, and stores state in SQLite so decisions survive restarts.

What It Does

brrpolice continuously:

  1. Polls qBittorrent for seeding torrents and connected peers.
  2. Tracks per-peer behavior over time (upload rate, progress change, observation window).
  3. Applies policy rules to decide whether a peer should be banned.
  4. Enforces bans in qBittorrent and reconciles ban expiry.

How It Works

  • Startup runs DB migrations, starts HTTP endpoints, then initializes qBittorrent access and recovery in the control loop.
  • Peer state, offence history, and active bans are stored in SQLite.
  • Retention pruning periodically deletes stale rows so SQLite size converges instead of growing without bound.
  • Ban duration increases by offence count using a configurable ban ladder.
  • Independent policies keep separate state and offence history. If multiple policies nominate the same IP in one poll, brrpolice records each offence but applies only the longest selected qBittorrent ban for that IP.
  • Expired bans are reconciled so qBittorrent and the database stay consistent.
  • Policy logic overview: docs/policy-engine.md.

Requirements

  • qBittorrent WebUI API reachable from this service
  • Docker (for container runs) or Rust toolchain (for local source runs)
  • Writable storage for SQLite (/data in the container image by default)
  • Writable temporary storage (/tmp), including when the root filesystem is read-only. SQLite uses it for large index builds and query sorts.
  • qBittorrent credentials only when WebUI auth is enabled

Quick Start (Docker)

Create a config.toml:

[qbittorrent]
base_url = "http://qbittorrent:8080"
username = ""
password_env = ""
api_key = ""

[database]
path = "/data/brrpolice.sqlite"

Build and run:

docker build -t brrpolice:latest .
docker run --rm -p 9090:9090 \
  -v "$(pwd)/config.toml:/app/config.toml:ro" \
  -v "$(pwd)/data:/data" \
  brrpolice:latest

If qBittorrent 5.1 username/password auth is enabled, set both qbittorrent.username and qbittorrent.password_env, then pass the password env var:

docker run --rm -p 9090:9090 \
  -e QBITTORRENT_PASSWORD='your-password' \
  -v "$(pwd)/config.toml:/app/config.toml:ro" \
  -v "$(pwd)/data:/data" \
  brrpolice:latest

Helm (Kubernetes)

The application chart is published only as an OCI artifact:

helm install brrpolice oci://ghcr.io/zariel/charts/brrpolice \
  --namespace default \
  --set config.qbittorrent.base_url=http://qbittorrent.default.svc.cluster.local

The chart provides persistent SQLite data, disk-backed temporary storage, a read-only root filesystem, and single-instance Recreate upgrades. See the chart documentation for existing PVCs, credentials, monitoring, and configuration values.

Run From Source

cargo run

Use a non-default config path:

BRRPOLICE_CONFIG=/path/to/config.toml cargo run

Or with CLI flags:

cargo run -- --config /path/to/config.toml --http-host 0.0.0.0 --http-port 9090

Configuration

Configuration load order:

  1. Built-in defaults
  2. config.toml in the working directory
  3. Environment variable overrides (BRRPOLICE_...)

If BRRPOLICE_CONFIG is set, the file is required. Any missing file, parse error, or validation error causes startup to fail.

Duration values use human-readable strings such as 30s, 5m, 1h.

qBittorrent auth rule:

  • Use exactly one auth mode: unauthenticated local access, cookie auth with both qbittorrent.username and qbittorrent.password_env, or qBittorrent 5.2+ API-key auth with qbittorrent.api_key.
  • qbittorrent.api_key cannot be combined with qbittorrent.username or qbittorrent.password_env.

qBittorrent Settings

Setting Env Var Default Impact
qbittorrent.base_url BRRPOLICE_QBITTORRENT__BASE_URL http://qbittorrent:8080 Base URL for qBittorrent WebUI API calls. Must be http or https and must not include credentials in the URL. Only the scheme, host, and port are logged or persisted; any path or query (for example a proxy API key) is redacted.
qbittorrent.username BRRPOLICE_QBITTORRENT__USERNAME "" Enables authenticated API mode when set together with password_env.
qbittorrent.password_env BRRPOLICE_QBITTORRENT__PASSWORD_ENV "" Name of the environment variable that contains the qBittorrent password. Used only when auth is enabled.
qbittorrent.api_key BRRPOLICE_QBITTORRENT__API_KEY "" qBittorrent 5.2+ API key sent as Authorization: Bearer .... Mutually exclusive with username/password cookie auth.
qbittorrent.poll_interval BRRPOLICE_QBITTORRENT__POLL_INTERVAL 10s Control loop polling frequency. Lower values react faster but increase API/database load.
qbittorrent.request_timeout BRRPOLICE_QBITTORRENT__REQUEST_TIMEOUT 10s Timeout per qBittorrent API request. Must be <= poll_interval.
qbittorrent.pool_idle_timeout BRRPOLICE_QBITTORRENT__POOL_IDLE_TIMEOUT 5s Maximum idle lifetime for pooled qBittorrent HTTP connections before closing and reopening.
qbittorrent.transient_retries BRRPOLICE_QBITTORRENT__TRANSIENT_RETRIES 10 Retries for transient qBittorrent request failures (connection resets, timeouts, and retryable HTTP status).

Policy Settings

Two ban policies are active by default:

  • Score policy: bans peers that stay slow and fail to make expected progress after the observation and sustain guardrails are met.
  • Receive-idle policy: bans peers that stay connected while qBittorrent reports no upload rate and no cumulative uploaded-byte progress. This policy requires qBittorrent peer uploaded telemetry; peers with missing or reset uploaded counters are treated as non-bannable for this policy.

Shared exemptions apply before either policy can ban: out-of-scope torrents, allowlisted peers, near-complete peers, new-peer grace period, and peers already under an active brrpolice ban.

Setting Env Var Default Impact
policy.new_peer_grace_period BRRPOLICE_POLICY__NEW_PEER_GRACE_PERIOD 60s New peers are exempt during this initial age window.
policy.decay_window BRRPOLICE_POLICY__DECAY_WINDOW 60m Window used to decay bad history and carry over peer state between sightings.
policy.ignore_peer_progress_at_or_above BRRPOLICE_POLICY__IGNORE_PEER_PROGRESS_AT_OR_ABOVE 0.95 Exempts peers at or above this completion ratio.
policy.min_total_seeders BRRPOLICE_POLICY__MIN_TOTAL_SEEDERS 3 Skips torrents below this seeder count.
policy.reban_cooldown BRRPOLICE_POLICY__REBAN_COOLDOWN 30m Deprecated alias for policy.score.reban_cooldown.
policy.score.enabled BRRPOLICE_POLICY__SCORE__ENABLED true Enables the score/rate-progress policy. Set false to run only other enabled peer policies.
policy.score.reban_cooldown BRRPOLICE_POLICY__SCORE__REBAN_COOLDOWN 30m Cooldown before the score policy can re-ban the same torrent/IP identity.
policy.score.ban_ladder.durations BRRPOLICE_POLICY__SCORE__BAN_LADDER__DURATIONS ["1h","6h","24h","168h"] Score-policy ban durations by policy-specific offence number. If offences exceed the list, the final duration is reused.
policy.score.target_rate_bps BRRPOLICE_POLICY__SCORE__TARGET_RATE_BPS 65536 Score model upload target in bytes/sec. Lower observed rates increase score risk.
policy.score.required_progress_delta BRRPOLICE_POLICY__SCORE__REQUIRED_PROGRESS_DELTA 0.02 Score model progress target as a fraction (0.02 = 2%). Lower progress increases score risk.
policy.score.progress_rate_scale_start BRRPOLICE_POLICY__SCORE__PROGRESS_RATE_SCALE_START 2.0 Upload-rate multiple where progress expectation starts relaxing for fast peers.
policy.score.progress_rate_scale_end BRRPOLICE_POLICY__SCORE__PROGRESS_RATE_SCALE_END 16.0 Upload-rate multiple where progress expectation reaches its minimum scale.
policy.score.progress_rate_min_scale BRRPOLICE_POLICY__SCORE__PROGRESS_RATE_MIN_SCALE 0.25 Lowest fraction of the base progress requirement that can apply to very fast peers.
policy.score.weight_rate BRRPOLICE_POLICY__SCORE__WEIGHT_RATE 0.35 Weight for upload-rate risk in score calculations.
policy.score.weight_progress BRRPOLICE_POLICY__SCORE__WEIGHT_PROGRESS 0.65 Weight for progress risk in score calculations.
policy.score.rate_risk_floor BRRPOLICE_POLICY__SCORE__RATE_RISK_FLOOR 0.4 Non-compensatory floor for upload-rate risk (sample_risk >= rate_risk_floor * rate_risk).
policy.score.ban_threshold BRRPOLICE_POLICY__SCORE__BAN_THRESHOLD 1.6 Score threshold that starts/continues ban-eligible accumulation.
policy.score.clear_threshold BRRPOLICE_POLICY__SCORE__CLEAR_THRESHOLD 0.8 Score threshold that resets accumulated above-threshold time.
policy.score.sustain_duration BRRPOLICE_POLICY__SCORE__SUSTAIN_DURATION 120s Time score must stay at or above ban_threshold before a ban is allowed.
policy.score.decay_per_second BRRPOLICE_POLICY__SCORE__DECAY_PER_SECOND 0.02 Passive score decay rate per second between observations.
policy.score.min_observation_duration BRRPOLICE_POLICY__SCORE__MIN_OBSERVATION_DURATION 2m Minimum tracked peer age before score-based bans can trigger.
policy.score.max_score BRRPOLICE_POLICY__SCORE__MAX_SCORE 5.0 Upper clamp for per-peer score state.
policy.score.churn.enabled BRRPOLICE_POLICY__SCORE__CHURN__ENABLED true Enables reconnect churn as a multiplier on already-bad samples.
policy.score.churn.reconnect_window BRRPOLICE_POLICY__SCORE__CHURN__RECONNECT_WINDOW 30m Time window used to count reconnects for churn scoring.
policy.score.churn.min_reconnects BRRPOLICE_POLICY__SCORE__CHURN__MIN_RECONNECTS 2 Minimum reconnect count in the churn window before churn amplification starts applying.
policy.score.churn.max_amplifier BRRPOLICE_POLICY__SCORE__CHURN__MAX_AMPLIFIER 1.0 Maximum extra multiplier applied to sample risk (effective = sample * (1 + churn_amplifier)).
policy.score.churn.decay_per_second BRRPOLICE_POLICY__SCORE__CHURN__DECAY_PER_SECOND 0.002 Decay rate for accumulated churn amplification between observations.
policy.receive_idle.enabled BRRPOLICE_POLICY__RECEIVE_IDLE__ENABLED false Enables the inactive/receive-idle policy.
policy.receive_idle.min_observation_duration BRRPOLICE_POLICY__RECEIVE_IDLE__MIN_OBSERVATION_DURATION 3m Minimum tracked peer age before receive-idle bans can trigger.
policy.receive_idle.sustain_duration BRRPOLICE_POLICY__RECEIVE_IDLE__SUSTAIN_DURATION 2m Time a peer must continuously show no upload rate and no uploaded-byte progress before a receive-idle ban is allowed.
policy.receive_idle.max_upload_rate_bps BRRPOLICE_POLICY__RECEIVE_IDLE__MAX_UPLOAD_RATE_BPS 0 Maximum current qBittorrent up_speed that still counts as idle. The default requires exactly zero current upload.
policy.receive_idle.max_uploaded_delta_bytes BRRPOLICE_POLICY__RECEIVE_IDLE__MAX_UPLOADED_DELTA_BYTES 0 Maximum cumulative uploaded-byte delta between samples that still counts as idle. The default requires no uploaded-byte progress.
policy.receive_idle.reban_cooldown BRRPOLICE_POLICY__RECEIVE_IDLE__REBAN_COOLDOWN 10m Cooldown before receive-idle can re-ban the same torrent/IP identity.
policy.receive_idle.ban_ladder.durations BRRPOLICE_POLICY__RECEIVE_IDLE__BAN_LADDER__DURATIONS ["10m","30m","2h","6h"] Receive-idle ban durations by policy-specific offence number. If offences exceed the list, the final duration is reused.
policy.ban_ladder.durations BRRPOLICE_POLICY__BAN_LADDER__DURATIONS ["1h","6h","24h","168h"] Deprecated alias for policy.score.ban_ladder.durations.

Example policy override:

[policy.score]
enabled = true
reban_cooldown = "30m"

[policy.score.ban_ladder]
durations = ["1h", "6h", "24h", "168h"]

[policy.receive_idle]
enabled = true
min_observation_duration = "3m"
sustain_duration = "2m"
max_upload_rate_bps = 0
max_uploaded_delta_bytes = 0
reban_cooldown = "10m"

[policy.receive_idle.ban_ladder]
durations = ["10m", "30m", "2h", "6h"]

Filter Settings

Setting Env Var Default Impact
filters.include_categories BRRPOLICE_FILTERS__INCLUDE_CATEGORIES [] Optional allow-list of torrent categories. If includes are configured, torrent category or tag must match.
filters.exclude_categories BRRPOLICE_FILTERS__EXCLUDE_CATEGORIES [] Deny-list of torrent categories. Excludes are applied before includes.
filters.include_tags BRRPOLICE_FILTERS__INCLUDE_TAGS [] Optional allow-list of torrent tags. Works with include_categories.
filters.exclude_tags BRRPOLICE_FILTERS__EXCLUDE_TAGS [] Deny-list of torrent tags. Excludes are applied before includes.
filters.allowlist_peer_ips BRRPOLICE_FILTERS__ALLOWLIST_PEER_IPS [] Peer IPs that are never banned.
filters.allowlist_peer_cidrs BRRPOLICE_FILTERS__ALLOWLIST_PEER_CIDRS [] Peer CIDR ranges that are never banned.

Retention Settings

Setting Env Var Default Impact
retention.enabled BRRPOLICE_RETENTION__ENABLED true Enables periodic SQLite retention pruning.
retention.prune_interval BRRPOLICE_RETENTION__PRUNE_INTERVAL 1h Minimum time between prune runs.
retention.peer_session_max_age BRRPOLICE_RETENTION__PEER_SESSION_MAX_AGE 7d Maximum age of peer session rows before they become prune-eligible.
retention.peer_offence_max_age BRRPOLICE_RETENTION__PEER_OFFENCE_MAX_AGE 90d Maximum age of offence history rows before they become prune-eligible while preserving ban-ladder continuity.
retention.reconciled_ban_max_age BRRPOLICE_RETENTION__RECONCILED_BAN_MAX_AGE 30d Maximum age of reconciled active ban rows before cleanup.
retention.pending_intent_max_age BRRPOLICE_RETENTION__PENDING_INTENT_MAX_AGE 24h Maximum time expired failed pending ban intents are retained before periodic cleanup. Replayable intents are retained.
retention.max_rows_per_run BRRPOLICE_RETENTION__MAX_ROWS_PER_RUN 5000 Per-table delete cap per prune run to bound write pressure.
retention.vacuum.mode BRRPOLICE_RETENTION__VACUUM__MODE incremental SQLite reclaim mode after prune runs (incremental or off).
retention.vacuum.incremental_pages BRRPOLICE_RETENTION__VACUUM__INCREMENTAL_PAGES 200 Number of SQLite pages requested per incremental vacuum run.

Storage, HTTP, and Logging Settings

Setting Env Var Default Impact
database.path BRRPOLICE_DATABASE__PATH /data/brrpolice.sqlite SQLite database location for sessions, bans, and offence history.
database.busy_timeout BRRPOLICE_DATABASE__BUSY_TIMEOUT 5s SQLite busy timeout for lock contention.
http.host BRRPOLICE_HTTP__HOST 0.0.0.0 HTTP bind host for /healthz, /readyz, and /metrics.
http.port BRRPOLICE_HTTP__PORT 9090 HTTP bind port for /healthz, /readyz, and /metrics.
logging.level BRRPOLICE_LOGGING__LEVEL warn Log level filter (for example trace, debug, info, warn, error). At info, peer policy decisions are emitted; at warn, non-fatal errors and peer bans are emitted.
logging.format BRRPOLICE_LOGGING__FORMAT json Output format: json, plain, or text.

Environment Overrides

Any setting can be overridden with env vars using:

BRRPOLICE_<SECTION>__<KEY>

Examples:

BRRPOLICE_QBITTORRENT__BASE_URL=http://qbittorrent.svc:8080
BRRPOLICE_POLICY__MIN_TOTAL_SEEDERS=5
BRRPOLICE_POLICY__BAN_LADDER__DURATIONS=1h,12h,48h
BRRPOLICE_FILTERS__EXCLUDE_TAGS=private,restricted
BRRPOLICE_HTTP__HOST=0.0.0.0
BRRPOLICE_HTTP__PORT=9090

For list values, use comma-separated entries.

Retention Tuning

  • Start with defaults and observe brrpolice_sqlite_size_bytes over multiple prune intervals.
  • Reduce retention.prune_interval or increase retention.max_rows_per_run when stale rows accumulate faster than cleanup.
  • Lower retention.peer_session_max_age first if database growth is dominated by session churn.
  • Keep retention.peer_offence_max_age long enough to preserve meaningful offence history for ban ladder continuity.
  • Use incremental vacuum for bounded background reclaim; switch to off only if disk reclaim is managed externally.

HTTP Endpoints

  • /healthz: process liveness
  • /readyz: readiness with gate diagnostics in JSON
  • /metrics: Prometheus metrics

Example:

curl -fsS http://127.0.0.1:9090/healthz
curl -fsS http://127.0.0.1:9090/readyz
curl -fsS http://127.0.0.1:9090/metrics

Grafana Dashboard

Set monitoring.dashboards.enabled: true in the Helm chart to deploy the operational dashboard through a Grafana sidecar or Grafana Operator. See the chart documentation for configuration. For manual imports, use brrpolice-overview.json.

The dashboard was donated to the project by buroa from buroa/grafana-dashboards. Thank you, buroa!

License

This project is licensed under the terms in LICENSE.

About

No description, website, or topics provided.

Resources

Stars

11 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages